TheHassanSaud commited on
Commit
272ec2d
·
1 Parent(s): 2b111dd

Upload folder using huggingface_hub (part 15)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +24 -0
  2. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/LICENSE.txt +934 -0
  3. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/METADATA +1082 -0
  4. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/RECORD +0 -0
  5. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/WHEEL +6 -0
  6. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 +3 -0
  7. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 +3 -0
  8. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 +3 -0
  9. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 +3 -0
  10. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_mstats_extras.py +521 -0
  11. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_multicomp.py +449 -0
  12. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_multivariate.py +0 -0
  13. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_mvn.cpython-311-x86_64-linux-gnu.so +0 -0
  14. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_new_distributions.py +375 -0
  15. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_odds_ratio.py +466 -0
  16. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_page_trend_test.py +479 -0
  17. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_probability_distribution.py +1742 -0
  18. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc.py +0 -0
  19. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc_cy.cpython-311-x86_64-linux-gnu.so +3 -0
  20. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc_cy.pyi +54 -0
  21. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmvnt.py +533 -0
  22. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/__init__.py +4 -0
  23. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-311.pyc +0 -0
  24. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/rcont.cpython-311-x86_64-linux-gnu.so +3 -0
  25. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_relative_risk.py +263 -0
  26. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_resampling.py +0 -0
  27. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_result_classes.py +40 -0
  28. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sampling.py +1314 -0
  29. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sensitivity_analysis.py +713 -0
  30. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol.cpython-311-x86_64-linux-gnu.so +3 -0
  31. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol.pyi +54 -0
  32. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol_direction_numbers.npz +3 -0
  33. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats.cpython-311-x86_64-linux-gnu.so +3 -0
  34. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats.pxd +10 -0
  35. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_mstats_common.py +303 -0
  36. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_py.py +0 -0
  37. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_pythran.cpython-311-x86_64-linux-gnu.so +3 -0
  38. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_survival.py +683 -0
  39. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_tukeylambda_stats.py +199 -0
  40. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/__init__.py +0 -0
  41. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-311-x86_64-linux-gnu.so +3 -0
  42. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi +178 -0
  43. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_variation.py +128 -0
  44. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_warnings_errors.py +38 -0
  45. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_wilcoxon.py +259 -0
  46. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/biasedurn.py +16 -0
  47. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/contingency.py +521 -0
  48. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/distributions.py +24 -0
  49. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/kde.py +18 -0
  50. pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/morestats.py +27 -0
.gitattributes CHANGED
@@ -1201,3 +1201,27 @@ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/
1201
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_stats_py.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1202
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1203
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_biasedurn.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1201
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_stats_py.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1202
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1203
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_biasedurn.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1204
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc_cy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1205
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/rcont.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1206
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1207
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1208
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_pythran.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1209
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1210
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
1211
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
1212
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 filter=lfs diff=lfs merge=lfs -text
1213
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 filter=lfs diff=lfs merge=lfs -text
1214
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libscipy_openblas-68440149.so filter=lfs diff=lfs merge=lfs -text
1215
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/core/__pycache__/expr.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1216
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/core/__pycache__/function.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1217
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/core/__pycache__/numbers.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1218
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1219
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1220
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1221
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/functions/special/__pycache__/bessel.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1222
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1223
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/geometry/__pycache__/polygon.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1224
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/integrals/__pycache__/laplace.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1225
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/integrals/__pycache__/meijerint.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1226
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/logic/__pycache__/boolalg.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1227
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,934 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2001-2002 Enthought, Inc. 2003-2024, SciPy Developers.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions
6
+ are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above
12
+ copyright notice, this list of conditions and the following
13
+ disclaimer in the documentation and/or other materials provided
14
+ with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived
18
+ from this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ ----
33
+
34
+ This binary distribution of SciPy can also bundle the following software
35
+ (depending on the build):
36
+
37
+
38
+ Name: OpenBLAS
39
+ Files: scipy.libs/libscipy_openblas*.so
40
+ Description: bundled as a dynamically linked library
41
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
42
+ License: BSD-3-Clause-Attribution
43
+ Copyright (c) 2011-2014, The OpenBLAS Project
44
+ All rights reserved.
45
+
46
+ Redistribution and use in source and binary forms, with or without
47
+ modification, are permitted provided that the following conditions are
48
+ met:
49
+
50
+ 1. Redistributions of source code must retain the above copyright
51
+ notice, this list of conditions and the following disclaimer.
52
+
53
+ 2. Redistributions in binary form must reproduce the above copyright
54
+ notice, this list of conditions and the following disclaimer in
55
+ the documentation and/or other materials provided with the
56
+ distribution.
57
+ 3. Neither the name of the OpenBLAS project nor the names of
58
+ its contributors may be used to endorse or promote products
59
+ derived from this software without specific prior written
60
+ permission.
61
+
62
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
63
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
66
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
68
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
69
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
70
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
71
+ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
72
+
73
+
74
+ Name: LAPACK
75
+ Files: scipy.libs/libscipy_openblas*.so
76
+ Description: bundled in OpenBLAS
77
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
78
+ License: BSD-3-Clause-Attribution
79
+ Copyright (c) 1992-2013 The University of Tennessee and The University
80
+ of Tennessee Research Foundation. All rights
81
+ reserved.
82
+ Copyright (c) 2000-2013 The University of California Berkeley. All
83
+ rights reserved.
84
+ Copyright (c) 2006-2013 The University of Colorado Denver. All rights
85
+ reserved.
86
+
87
+ $COPYRIGHT$
88
+
89
+ Additional copyrights may follow
90
+
91
+ $HEADER$
92
+
93
+ Redistribution and use in source and binary forms, with or without
94
+ modification, are permitted provided that the following conditions are
95
+ met:
96
+
97
+ - Redistributions of source code must retain the above copyright
98
+ notice, this list of conditions and the following disclaimer.
99
+
100
+ - Redistributions in binary form must reproduce the above copyright
101
+ notice, this list of conditions and the following disclaimer listed
102
+ in this license in the documentation and/or other materials
103
+ provided with the distribution.
104
+
105
+ - Neither the name of the copyright holders nor the names of its
106
+ contributors may be used to endorse or promote products derived from
107
+ this software without specific prior written permission.
108
+
109
+ The copyright holders provide no reassurances that the source code
110
+ provided does not infringe any patent, copyright, or any other
111
+ intellectual property rights of third parties. The copyright holders
112
+ disclaim any liability to any recipient for claims brought against
113
+ recipient by any third party for infringement of that parties
114
+ intellectual property rights.
115
+
116
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
117
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
118
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
119
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
120
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
121
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
122
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
123
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
124
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
125
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
126
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
127
+
128
+
129
+ Name: GCC runtime library
130
+ Files: scipy.libs/libgfortran*.so
131
+ Description: dynamically linked to files compiled with gcc
132
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran
133
+ License: GPL-3.0-with-GCC-exception
134
+ Copyright (C) 2002-2017 Free Software Foundation, Inc.
135
+
136
+ Libgfortran is free software; you can redistribute it and/or modify
137
+ it under the terms of the GNU General Public License as published by
138
+ the Free Software Foundation; either version 3, or (at your option)
139
+ any later version.
140
+
141
+ Libgfortran is distributed in the hope that it will be useful,
142
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
143
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
144
+ GNU General Public License for more details.
145
+
146
+ Under Section 7 of GPL version 3, you are granted additional
147
+ permissions described in the GCC Runtime Library Exception, version
148
+ 3.1, as published by the Free Software Foundation.
149
+
150
+ You should have received a copy of the GNU General Public License and
151
+ a copy of the GCC Runtime Library Exception along with this program;
152
+ see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
153
+ <http://www.gnu.org/licenses/>.
154
+
155
+ ----
156
+
157
+ Full text of license texts referred to above follows (that they are
158
+ listed below does not necessarily imply the conditions apply to the
159
+ present binary release):
160
+
161
+ ----
162
+
163
+ GCC RUNTIME LIBRARY EXCEPTION
164
+
165
+ Version 3.1, 31 March 2009
166
+
167
+ Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
168
+
169
+ Everyone is permitted to copy and distribute verbatim copies of this
170
+ license document, but changing it is not allowed.
171
+
172
+ This GCC Runtime Library Exception ("Exception") is an additional
173
+ permission under section 7 of the GNU General Public License, version
174
+ 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that
175
+ bears a notice placed by the copyright holder of the file stating that
176
+ the file is governed by GPLv3 along with this Exception.
177
+
178
+ When you use GCC to compile a program, GCC may combine portions of
179
+ certain GCC header files and runtime libraries with the compiled
180
+ program. The purpose of this Exception is to allow compilation of
181
+ non-GPL (including proprietary) programs to use, in this way, the
182
+ header files and runtime libraries covered by this Exception.
183
+
184
+ 0. Definitions.
185
+
186
+ A file is an "Independent Module" if it either requires the Runtime
187
+ Library for execution after a Compilation Process, or makes use of an
188
+ interface provided by the Runtime Library, but is not otherwise based
189
+ on the Runtime Library.
190
+
191
+ "GCC" means a version of the GNU Compiler Collection, with or without
192
+ modifications, governed by version 3 (or a specified later version) of
193
+ the GNU General Public License (GPL) with the option of using any
194
+ subsequent versions published by the FSF.
195
+
196
+ "GPL-compatible Software" is software whose conditions of propagation,
197
+ modification and use would permit combination with GCC in accord with
198
+ the license of GCC.
199
+
200
+ "Target Code" refers to output from any compiler for a real or virtual
201
+ target processor architecture, in executable form or suitable for
202
+ input to an assembler, loader, linker and/or execution
203
+ phase. Notwithstanding that, Target Code does not include data in any
204
+ format that is used as a compiler intermediate representation, or used
205
+ for producing a compiler intermediate representation.
206
+
207
+ The "Compilation Process" transforms code entirely represented in
208
+ non-intermediate languages designed for human-written code, and/or in
209
+ Java Virtual Machine byte code, into Target Code. Thus, for example,
210
+ use of source code generators and preprocessors need not be considered
211
+ part of the Compilation Process, since the Compilation Process can be
212
+ understood as starting with the output of the generators or
213
+ preprocessors.
214
+
215
+ A Compilation Process is "Eligible" if it is done using GCC, alone or
216
+ with other GPL-compatible software, or if it is done without using any
217
+ work based on GCC. For example, using non-GPL-compatible Software to
218
+ optimize any GCC intermediate representations would not qualify as an
219
+ Eligible Compilation Process.
220
+
221
+ 1. Grant of Additional Permission.
222
+
223
+ You have permission to propagate a work of Target Code formed by
224
+ combining the Runtime Library with Independent Modules, even if such
225
+ propagation would otherwise violate the terms of GPLv3, provided that
226
+ all Target Code was generated by Eligible Compilation Processes. You
227
+ may then convey such a combination under terms of your choice,
228
+ consistent with the licensing of the Independent Modules.
229
+
230
+ 2. No Weakening of GCC Copyleft.
231
+
232
+ The availability of this Exception does not imply any general
233
+ presumption that third-party software is unaffected by the copyleft
234
+ requirements of the license of GCC.
235
+
236
+ ----
237
+
238
+ GNU GENERAL PUBLIC LICENSE
239
+ Version 3, 29 June 2007
240
+
241
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
242
+ Everyone is permitted to copy and distribute verbatim copies
243
+ of this license document, but changing it is not allowed.
244
+
245
+ Preamble
246
+
247
+ The GNU General Public License is a free, copyleft license for
248
+ software and other kinds of works.
249
+
250
+ The licenses for most software and other practical works are designed
251
+ to take away your freedom to share and change the works. By contrast,
252
+ the GNU General Public License is intended to guarantee your freedom to
253
+ share and change all versions of a program--to make sure it remains free
254
+ software for all its users. We, the Free Software Foundation, use the
255
+ GNU General Public License for most of our software; it applies also to
256
+ any other work released this way by its authors. You can apply it to
257
+ your programs, too.
258
+
259
+ When we speak of free software, we are referring to freedom, not
260
+ price. Our General Public Licenses are designed to make sure that you
261
+ have the freedom to distribute copies of free software (and charge for
262
+ them if you wish), that you receive source code or can get it if you
263
+ want it, that you can change the software or use pieces of it in new
264
+ free programs, and that you know you can do these things.
265
+
266
+ To protect your rights, we need to prevent others from denying you
267
+ these rights or asking you to surrender the rights. Therefore, you have
268
+ certain responsibilities if you distribute copies of the software, or if
269
+ you modify it: responsibilities to respect the freedom of others.
270
+
271
+ For example, if you distribute copies of such a program, whether
272
+ gratis or for a fee, you must pass on to the recipients the same
273
+ freedoms that you received. You must make sure that they, too, receive
274
+ or can get the source code. And you must show them these terms so they
275
+ know their rights.
276
+
277
+ Developers that use the GNU GPL protect your rights with two steps:
278
+ (1) assert copyright on the software, and (2) offer you this License
279
+ giving you legal permission to copy, distribute and/or modify it.
280
+
281
+ For the developers' and authors' protection, the GPL clearly explains
282
+ that there is no warranty for this free software. For both users' and
283
+ authors' sake, the GPL requires that modified versions be marked as
284
+ changed, so that their problems will not be attributed erroneously to
285
+ authors of previous versions.
286
+
287
+ Some devices are designed to deny users access to install or run
288
+ modified versions of the software inside them, although the manufacturer
289
+ can do so. This is fundamentally incompatible with the aim of
290
+ protecting users' freedom to change the software. The systematic
291
+ pattern of such abuse occurs in the area of products for individuals to
292
+ use, which is precisely where it is most unacceptable. Therefore, we
293
+ have designed this version of the GPL to prohibit the practice for those
294
+ products. If such problems arise substantially in other domains, we
295
+ stand ready to extend this provision to those domains in future versions
296
+ of the GPL, as needed to protect the freedom of users.
297
+
298
+ Finally, every program is threatened constantly by software patents.
299
+ States should not allow patents to restrict development and use of
300
+ software on general-purpose computers, but in those that do, we wish to
301
+ avoid the special danger that patents applied to a free program could
302
+ make it effectively proprietary. To prevent this, the GPL assures that
303
+ patents cannot be used to render the program non-free.
304
+
305
+ The precise terms and conditions for copying, distribution and
306
+ modification follow.
307
+
308
+ TERMS AND CONDITIONS
309
+
310
+ 0. Definitions.
311
+
312
+ "This License" refers to version 3 of the GNU General Public License.
313
+
314
+ "Copyright" also means copyright-like laws that apply to other kinds of
315
+ works, such as semiconductor masks.
316
+
317
+ "The Program" refers to any copyrightable work licensed under this
318
+ License. Each licensee is addressed as "you". "Licensees" and
319
+ "recipients" may be individuals or organizations.
320
+
321
+ To "modify" a work means to copy from or adapt all or part of the work
322
+ in a fashion requiring copyright permission, other than the making of an
323
+ exact copy. The resulting work is called a "modified version" of the
324
+ earlier work or a work "based on" the earlier work.
325
+
326
+ A "covered work" means either the unmodified Program or a work based
327
+ on the Program.
328
+
329
+ To "propagate" a work means to do anything with it that, without
330
+ permission, would make you directly or secondarily liable for
331
+ infringement under applicable copyright law, except executing it on a
332
+ computer or modifying a private copy. Propagation includes copying,
333
+ distribution (with or without modification), making available to the
334
+ public, and in some countries other activities as well.
335
+
336
+ To "convey" a work means any kind of propagation that enables other
337
+ parties to make or receive copies. Mere interaction with a user through
338
+ a computer network, with no transfer of a copy, is not conveying.
339
+
340
+ An interactive user interface displays "Appropriate Legal Notices"
341
+ to the extent that it includes a convenient and prominently visible
342
+ feature that (1) displays an appropriate copyright notice, and (2)
343
+ tells the user that there is no warranty for the work (except to the
344
+ extent that warranties are provided), that licensees may convey the
345
+ work under this License, and how to view a copy of this License. If
346
+ the interface presents a list of user commands or options, such as a
347
+ menu, a prominent item in the list meets this criterion.
348
+
349
+ 1. Source Code.
350
+
351
+ The "source code" for a work means the preferred form of the work
352
+ for making modifications to it. "Object code" means any non-source
353
+ form of a work.
354
+
355
+ A "Standard Interface" means an interface that either is an official
356
+ standard defined by a recognized standards body, or, in the case of
357
+ interfaces specified for a particular programming language, one that
358
+ is widely used among developers working in that language.
359
+
360
+ The "System Libraries" of an executable work include anything, other
361
+ than the work as a whole, that (a) is included in the normal form of
362
+ packaging a Major Component, but which is not part of that Major
363
+ Component, and (b) serves only to enable use of the work with that
364
+ Major Component, or to implement a Standard Interface for which an
365
+ implementation is available to the public in source code form. A
366
+ "Major Component", in this context, means a major essential component
367
+ (kernel, window system, and so on) of the specific operating system
368
+ (if any) on which the executable work runs, or a compiler used to
369
+ produce the work, or an object code interpreter used to run it.
370
+
371
+ The "Corresponding Source" for a work in object code form means all
372
+ the source code needed to generate, install, and (for an executable
373
+ work) run the object code and to modify the work, including scripts to
374
+ control those activities. However, it does not include the work's
375
+ System Libraries, or general-purpose tools or generally available free
376
+ programs which are used unmodified in performing those activities but
377
+ which are not part of the work. For example, Corresponding Source
378
+ includes interface definition files associated with source files for
379
+ the work, and the source code for shared libraries and dynamically
380
+ linked subprograms that the work is specifically designed to require,
381
+ such as by intimate data communication or control flow between those
382
+ subprograms and other parts of the work.
383
+
384
+ The Corresponding Source need not include anything that users
385
+ can regenerate automatically from other parts of the Corresponding
386
+ Source.
387
+
388
+ The Corresponding Source for a work in source code form is that
389
+ same work.
390
+
391
+ 2. Basic Permissions.
392
+
393
+ All rights granted under this License are granted for the term of
394
+ copyright on the Program, and are irrevocable provided the stated
395
+ conditions are met. This License explicitly affirms your unlimited
396
+ permission to run the unmodified Program. The output from running a
397
+ covered work is covered by this License only if the output, given its
398
+ content, constitutes a covered work. This License acknowledges your
399
+ rights of fair use or other equivalent, as provided by copyright law.
400
+
401
+ You may make, run and propagate covered works that you do not
402
+ convey, without conditions so long as your license otherwise remains
403
+ in force. You may convey covered works to others for the sole purpose
404
+ of having them make modifications exclusively for you, or provide you
405
+ with facilities for running those works, provided that you comply with
406
+ the terms of this License in conveying all material for which you do
407
+ not control copyright. Those thus making or running the covered works
408
+ for you must do so exclusively on your behalf, under your direction
409
+ and control, on terms that prohibit them from making any copies of
410
+ your copyrighted material outside their relationship with you.
411
+
412
+ Conveying under any other circumstances is permitted solely under
413
+ the conditions stated below. Sublicensing is not allowed; section 10
414
+ makes it unnecessary.
415
+
416
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
417
+
418
+ No covered work shall be deemed part of an effective technological
419
+ measure under any applicable law fulfilling obligations under article
420
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
421
+ similar laws prohibiting or restricting circumvention of such
422
+ measures.
423
+
424
+ When you convey a covered work, you waive any legal power to forbid
425
+ circumvention of technological measures to the extent such circumvention
426
+ is effected by exercising rights under this License with respect to
427
+ the covered work, and you disclaim any intention to limit operation or
428
+ modification of the work as a means of enforcing, against the work's
429
+ users, your or third parties' legal rights to forbid circumvention of
430
+ technological measures.
431
+
432
+ 4. Conveying Verbatim Copies.
433
+
434
+ You may convey verbatim copies of the Program's source code as you
435
+ receive it, in any medium, provided that you conspicuously and
436
+ appropriately publish on each copy an appropriate copyright notice;
437
+ keep intact all notices stating that this License and any
438
+ non-permissive terms added in accord with section 7 apply to the code;
439
+ keep intact all notices of the absence of any warranty; and give all
440
+ recipients a copy of this License along with the Program.
441
+
442
+ You may charge any price or no price for each copy that you convey,
443
+ and you may offer support or warranty protection for a fee.
444
+
445
+ 5. Conveying Modified Source Versions.
446
+
447
+ You may convey a work based on the Program, or the modifications to
448
+ produce it from the Program, in the form of source code under the
449
+ terms of section 4, provided that you also meet all of these conditions:
450
+
451
+ a) The work must carry prominent notices stating that you modified
452
+ it, and giving a relevant date.
453
+
454
+ b) The work must carry prominent notices stating that it is
455
+ released under this License and any conditions added under section
456
+ 7. This requirement modifies the requirement in section 4 to
457
+ "keep intact all notices".
458
+
459
+ c) You must license the entire work, as a whole, under this
460
+ License to anyone who comes into possession of a copy. This
461
+ License will therefore apply, along with any applicable section 7
462
+ additional terms, to the whole of the work, and all its parts,
463
+ regardless of how they are packaged. This License gives no
464
+ permission to license the work in any other way, but it does not
465
+ invalidate such permission if you have separately received it.
466
+
467
+ d) If the work has interactive user interfaces, each must display
468
+ Appropriate Legal Notices; however, if the Program has interactive
469
+ interfaces that do not display Appropriate Legal Notices, your
470
+ work need not make them do so.
471
+
472
+ A compilation of a covered work with other separate and independent
473
+ works, which are not by their nature extensions of the covered work,
474
+ and which are not combined with it such as to form a larger program,
475
+ in or on a volume of a storage or distribution medium, is called an
476
+ "aggregate" if the compilation and its resulting copyright are not
477
+ used to limit the access or legal rights of the compilation's users
478
+ beyond what the individual works permit. Inclusion of a covered work
479
+ in an aggregate does not cause this License to apply to the other
480
+ parts of the aggregate.
481
+
482
+ 6. Conveying Non-Source Forms.
483
+
484
+ You may convey a covered work in object code form under the terms
485
+ of sections 4 and 5, provided that you also convey the
486
+ machine-readable Corresponding Source under the terms of this License,
487
+ in one of these ways:
488
+
489
+ a) Convey the object code in, or embodied in, a physical product
490
+ (including a physical distribution medium), accompanied by the
491
+ Corresponding Source fixed on a durable physical medium
492
+ customarily used for software interchange.
493
+
494
+ b) Convey the object code in, or embodied in, a physical product
495
+ (including a physical distribution medium), accompanied by a
496
+ written offer, valid for at least three years and valid for as
497
+ long as you offer spare parts or customer support for that product
498
+ model, to give anyone who possesses the object code either (1) a
499
+ copy of the Corresponding Source for all the software in the
500
+ product that is covered by this License, on a durable physical
501
+ medium customarily used for software interchange, for a price no
502
+ more than your reasonable cost of physically performing this
503
+ conveying of source, or (2) access to copy the
504
+ Corresponding Source from a network server at no charge.
505
+
506
+ c) Convey individual copies of the object code with a copy of the
507
+ written offer to provide the Corresponding Source. This
508
+ alternative is allowed only occasionally and noncommercially, and
509
+ only if you received the object code with such an offer, in accord
510
+ with subsection 6b.
511
+
512
+ d) Convey the object code by offering access from a designated
513
+ place (gratis or for a charge), and offer equivalent access to the
514
+ Corresponding Source in the same way through the same place at no
515
+ further charge. You need not require recipients to copy the
516
+ Corresponding Source along with the object code. If the place to
517
+ copy the object code is a network server, the Corresponding Source
518
+ may be on a different server (operated by you or a third party)
519
+ that supports equivalent copying facilities, provided you maintain
520
+ clear directions next to the object code saying where to find the
521
+ Corresponding Source. Regardless of what server hosts the
522
+ Corresponding Source, you remain obligated to ensure that it is
523
+ available for as long as needed to satisfy these requirements.
524
+
525
+ e) Convey the object code using peer-to-peer transmission, provided
526
+ you inform other peers where the object code and Corresponding
527
+ Source of the work are being offered to the general public at no
528
+ charge under subsection 6d.
529
+
530
+ A separable portion of the object code, whose source code is excluded
531
+ from the Corresponding Source as a System Library, need not be
532
+ included in conveying the object code work.
533
+
534
+ A "User Product" is either (1) a "consumer product", which means any
535
+ tangible personal property which is normally used for personal, family,
536
+ or household purposes, or (2) anything designed or sold for incorporation
537
+ into a dwelling. In determining whether a product is a consumer product,
538
+ doubtful cases shall be resolved in favor of coverage. For a particular
539
+ product received by a particular user, "normally used" refers to a
540
+ typical or common use of that class of product, regardless of the status
541
+ of the particular user or of the way in which the particular user
542
+ actually uses, or expects or is expected to use, the product. A product
543
+ is a consumer product regardless of whether the product has substantial
544
+ commercial, industrial or non-consumer uses, unless such uses represent
545
+ the only significant mode of use of the product.
546
+
547
+ "Installation Information" for a User Product means any methods,
548
+ procedures, authorization keys, or other information required to install
549
+ and execute modified versions of a covered work in that User Product from
550
+ a modified version of its Corresponding Source. The information must
551
+ suffice to ensure that the continued functioning of the modified object
552
+ code is in no case prevented or interfered with solely because
553
+ modification has been made.
554
+
555
+ If you convey an object code work under this section in, or with, or
556
+ specifically for use in, a User Product, and the conveying occurs as
557
+ part of a transaction in which the right of possession and use of the
558
+ User Product is transferred to the recipient in perpetuity or for a
559
+ fixed term (regardless of how the transaction is characterized), the
560
+ Corresponding Source conveyed under this section must be accompanied
561
+ by the Installation Information. But this requirement does not apply
562
+ if neither you nor any third party retains the ability to install
563
+ modified object code on the User Product (for example, the work has
564
+ been installed in ROM).
565
+
566
+ The requirement to provide Installation Information does not include a
567
+ requirement to continue to provide support service, warranty, or updates
568
+ for a work that has been modified or installed by the recipient, or for
569
+ the User Product in which it has been modified or installed. Access to a
570
+ network may be denied when the modification itself materially and
571
+ adversely affects the operation of the network or violates the rules and
572
+ protocols for communication across the network.
573
+
574
+ Corresponding Source conveyed, and Installation Information provided,
575
+ in accord with this section must be in a format that is publicly
576
+ documented (and with an implementation available to the public in
577
+ source code form), and must require no special password or key for
578
+ unpacking, reading or copying.
579
+
580
+ 7. Additional Terms.
581
+
582
+ "Additional permissions" are terms that supplement the terms of this
583
+ License by making exceptions from one or more of its conditions.
584
+ Additional permissions that are applicable to the entire Program shall
585
+ be treated as though they were included in this License, to the extent
586
+ that they are valid under applicable law. If additional permissions
587
+ apply only to part of the Program, that part may be used separately
588
+ under those permissions, but the entire Program remains governed by
589
+ this License without regard to the additional permissions.
590
+
591
+ When you convey a copy of a covered work, you may at your option
592
+ remove any additional permissions from that copy, or from any part of
593
+ it. (Additional permissions may be written to require their own
594
+ removal in certain cases when you modify the work.) You may place
595
+ additional permissions on material, added by you to a covered work,
596
+ for which you have or can give appropriate copyright permission.
597
+
598
+ Notwithstanding any other provision of this License, for material you
599
+ add to a covered work, you may (if authorized by the copyright holders of
600
+ that material) supplement the terms of this License with terms:
601
+
602
+ a) Disclaiming warranty or limiting liability differently from the
603
+ terms of sections 15 and 16 of this License; or
604
+
605
+ b) Requiring preservation of specified reasonable legal notices or
606
+ author attributions in that material or in the Appropriate Legal
607
+ Notices displayed by works containing it; or
608
+
609
+ c) Prohibiting misrepresentation of the origin of that material, or
610
+ requiring that modified versions of such material be marked in
611
+ reasonable ways as different from the original version; or
612
+
613
+ d) Limiting the use for publicity purposes of names of licensors or
614
+ authors of the material; or
615
+
616
+ e) Declining to grant rights under trademark law for use of some
617
+ trade names, trademarks, or service marks; or
618
+
619
+ f) Requiring indemnification of licensors and authors of that
620
+ material by anyone who conveys the material (or modified versions of
621
+ it) with contractual assumptions of liability to the recipient, for
622
+ any liability that these contractual assumptions directly impose on
623
+ those licensors and authors.
624
+
625
+ All other non-permissive additional terms are considered "further
626
+ restrictions" within the meaning of section 10. If the Program as you
627
+ received it, or any part of it, contains a notice stating that it is
628
+ governed by this License along with a term that is a further
629
+ restriction, you may remove that term. If a license document contains
630
+ a further restriction but permits relicensing or conveying under this
631
+ License, you may add to a covered work material governed by the terms
632
+ of that license document, provided that the further restriction does
633
+ not survive such relicensing or conveying.
634
+
635
+ If you add terms to a covered work in accord with this section, you
636
+ must place, in the relevant source files, a statement of the
637
+ additional terms that apply to those files, or a notice indicating
638
+ where to find the applicable terms.
639
+
640
+ Additional terms, permissive or non-permissive, may be stated in the
641
+ form of a separately written license, or stated as exceptions;
642
+ the above requirements apply either way.
643
+
644
+ 8. Termination.
645
+
646
+ You may not propagate or modify a covered work except as expressly
647
+ provided under this License. Any attempt otherwise to propagate or
648
+ modify it is void, and will automatically terminate your rights under
649
+ this License (including any patent licenses granted under the third
650
+ paragraph of section 11).
651
+
652
+ However, if you cease all violation of this License, then your
653
+ license from a particular copyright holder is reinstated (a)
654
+ provisionally, unless and until the copyright holder explicitly and
655
+ finally terminates your license, and (b) permanently, if the copyright
656
+ holder fails to notify you of the violation by some reasonable means
657
+ prior to 60 days after the cessation.
658
+
659
+ Moreover, your license from a particular copyright holder is
660
+ reinstated permanently if the copyright holder notifies you of the
661
+ violation by some reasonable means, this is the first time you have
662
+ received notice of violation of this License (for any work) from that
663
+ copyright holder, and you cure the violation prior to 30 days after
664
+ your receipt of the notice.
665
+
666
+ Termination of your rights under this section does not terminate the
667
+ licenses of parties who have received copies or rights from you under
668
+ this License. If your rights have been terminated and not permanently
669
+ reinstated, you do not qualify to receive new licenses for the same
670
+ material under section 10.
671
+
672
+ 9. Acceptance Not Required for Having Copies.
673
+
674
+ You are not required to accept this License in order to receive or
675
+ run a copy of the Program. Ancillary propagation of a covered work
676
+ occurring solely as a consequence of using peer-to-peer transmission
677
+ to receive a copy likewise does not require acceptance. However,
678
+ nothing other than this License grants you permission to propagate or
679
+ modify any covered work. These actions infringe copyright if you do
680
+ not accept this License. Therefore, by modifying or propagating a
681
+ covered work, you indicate your acceptance of this License to do so.
682
+
683
+ 10. Automatic Licensing of Downstream Recipients.
684
+
685
+ Each time you convey a covered work, the recipient automatically
686
+ receives a license from the original licensors, to run, modify and
687
+ propagate that work, subject to this License. You are not responsible
688
+ for enforcing compliance by third parties with this License.
689
+
690
+ An "entity transaction" is a transaction transferring control of an
691
+ organization, or substantially all assets of one, or subdividing an
692
+ organization, or merging organizations. If propagation of a covered
693
+ work results from an entity transaction, each party to that
694
+ transaction who receives a copy of the work also receives whatever
695
+ licenses to the work the party's predecessor in interest had or could
696
+ give under the previous paragraph, plus a right to possession of the
697
+ Corresponding Source of the work from the predecessor in interest, if
698
+ the predecessor has it or can get it with reasonable efforts.
699
+
700
+ You may not impose any further restrictions on the exercise of the
701
+ rights granted or affirmed under this License. For example, you may
702
+ not impose a license fee, royalty, or other charge for exercise of
703
+ rights granted under this License, and you may not initiate litigation
704
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
705
+ any patent claim is infringed by making, using, selling, offering for
706
+ sale, or importing the Program or any portion of it.
707
+
708
+ 11. Patents.
709
+
710
+ A "contributor" is a copyright holder who authorizes use under this
711
+ License of the Program or a work on which the Program is based. The
712
+ work thus licensed is called the contributor's "contributor version".
713
+
714
+ A contributor's "essential patent claims" are all patent claims
715
+ owned or controlled by the contributor, whether already acquired or
716
+ hereafter acquired, that would be infringed by some manner, permitted
717
+ by this License, of making, using, or selling its contributor version,
718
+ but do not include claims that would be infringed only as a
719
+ consequence of further modification of the contributor version. For
720
+ purposes of this definition, "control" includes the right to grant
721
+ patent sublicenses in a manner consistent with the requirements of
722
+ this License.
723
+
724
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
725
+ patent license under the contributor's essential patent claims, to
726
+ make, use, sell, offer for sale, import and otherwise run, modify and
727
+ propagate the contents of its contributor version.
728
+
729
+ In the following three paragraphs, a "patent license" is any express
730
+ agreement or commitment, however denominated, not to enforce a patent
731
+ (such as an express permission to practice a patent or covenant not to
732
+ sue for patent infringement). To "grant" such a patent license to a
733
+ party means to make such an agreement or commitment not to enforce a
734
+ patent against the party.
735
+
736
+ If you convey a covered work, knowingly relying on a patent license,
737
+ and the Corresponding Source of the work is not available for anyone
738
+ to copy, free of charge and under the terms of this License, through a
739
+ publicly available network server or other readily accessible means,
740
+ then you must either (1) cause the Corresponding Source to be so
741
+ available, or (2) arrange to deprive yourself of the benefit of the
742
+ patent license for this particular work, or (3) arrange, in a manner
743
+ consistent with the requirements of this License, to extend the patent
744
+ license to downstream recipients. "Knowingly relying" means you have
745
+ actual knowledge that, but for the patent license, your conveying the
746
+ covered work in a country, or your recipient's use of the covered work
747
+ in a country, would infringe one or more identifiable patents in that
748
+ country that you have reason to believe are valid.
749
+
750
+ If, pursuant to or in connection with a single transaction or
751
+ arrangement, you convey, or propagate by procuring conveyance of, a
752
+ covered work, and grant a patent license to some of the parties
753
+ receiving the covered work authorizing them to use, propagate, modify
754
+ or convey a specific copy of the covered work, then the patent license
755
+ you grant is automatically extended to all recipients of the covered
756
+ work and works based on it.
757
+
758
+ A patent license is "discriminatory" if it does not include within
759
+ the scope of its coverage, prohibits the exercise of, or is
760
+ conditioned on the non-exercise of one or more of the rights that are
761
+ specifically granted under this License. You may not convey a covered
762
+ work if you are a party to an arrangement with a third party that is
763
+ in the business of distributing software, under which you make payment
764
+ to the third party based on the extent of your activity of conveying
765
+ the work, and under which the third party grants, to any of the
766
+ parties who would receive the covered work from you, a discriminatory
767
+ patent license (a) in connection with copies of the covered work
768
+ conveyed by you (or copies made from those copies), or (b) primarily
769
+ for and in connection with specific products or compilations that
770
+ contain the covered work, unless you entered into that arrangement,
771
+ or that patent license was granted, prior to 28 March 2007.
772
+
773
+ Nothing in this License shall be construed as excluding or limiting
774
+ any implied license or other defenses to infringement that may
775
+ otherwise be available to you under applicable patent law.
776
+
777
+ 12. No Surrender of Others' Freedom.
778
+
779
+ If conditions are imposed on you (whether by court order, agreement or
780
+ otherwise) that contradict the conditions of this License, they do not
781
+ excuse you from the conditions of this License. If you cannot convey a
782
+ covered work so as to satisfy simultaneously your obligations under this
783
+ License and any other pertinent obligations, then as a consequence you may
784
+ not convey it at all. For example, if you agree to terms that obligate you
785
+ to collect a royalty for further conveying from those to whom you convey
786
+ the Program, the only way you could satisfy both those terms and this
787
+ License would be to refrain entirely from conveying the Program.
788
+
789
+ 13. Use with the GNU Affero General Public License.
790
+
791
+ Notwithstanding any other provision of this License, you have
792
+ permission to link or combine any covered work with a work licensed
793
+ under version 3 of the GNU Affero General Public License into a single
794
+ combined work, and to convey the resulting work. The terms of this
795
+ License will continue to apply to the part which is the covered work,
796
+ but the special requirements of the GNU Affero General Public License,
797
+ section 13, concerning interaction through a network will apply to the
798
+ combination as such.
799
+
800
+ 14. Revised Versions of this License.
801
+
802
+ The Free Software Foundation may publish revised and/or new versions of
803
+ the GNU General Public License from time to time. Such new versions will
804
+ be similar in spirit to the present version, but may differ in detail to
805
+ address new problems or concerns.
806
+
807
+ Each version is given a distinguishing version number. If the
808
+ Program specifies that a certain numbered version of the GNU General
809
+ Public License "or any later version" applies to it, you have the
810
+ option of following the terms and conditions either of that numbered
811
+ version or of any later version published by the Free Software
812
+ Foundation. If the Program does not specify a version number of the
813
+ GNU General Public License, you may choose any version ever published
814
+ by the Free Software Foundation.
815
+
816
+ If the Program specifies that a proxy can decide which future
817
+ versions of the GNU General Public License can be used, that proxy's
818
+ public statement of acceptance of a version permanently authorizes you
819
+ to choose that version for the Program.
820
+
821
+ Later license versions may give you additional or different
822
+ permissions. However, no additional obligations are imposed on any
823
+ author or copyright holder as a result of your choosing to follow a
824
+ later version.
825
+
826
+ 15. Disclaimer of Warranty.
827
+
828
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
829
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
830
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
831
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
832
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
833
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
834
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
835
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
836
+
837
+ 16. Limitation of Liability.
838
+
839
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
840
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
841
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
842
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
843
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
844
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
845
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
846
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
847
+ SUCH DAMAGES.
848
+
849
+ 17. Interpretation of Sections 15 and 16.
850
+
851
+ If the disclaimer of warranty and limitation of liability provided
852
+ above cannot be given local legal effect according to their terms,
853
+ reviewing courts shall apply local law that most closely approximates
854
+ an absolute waiver of all civil liability in connection with the
855
+ Program, unless a warranty or assumption of liability accompanies a
856
+ copy of the Program in return for a fee.
857
+
858
+ END OF TERMS AND CONDITIONS
859
+
860
+ How to Apply These Terms to Your New Programs
861
+
862
+ If you develop a new program, and you want it to be of the greatest
863
+ possible use to the public, the best way to achieve this is to make it
864
+ free software which everyone can redistribute and change under these terms.
865
+
866
+ To do so, attach the following notices to the program. It is safest
867
+ to attach them to the start of each source file to most effectively
868
+ state the exclusion of warranty; and each file should have at least
869
+ the "copyright" line and a pointer to where the full notice is found.
870
+
871
+ <one line to give the program's name and a brief idea of what it does.>
872
+ Copyright (C) <year> <name of author>
873
+
874
+ This program is free software: you can redistribute it and/or modify
875
+ it under the terms of the GNU General Public License as published by
876
+ the Free Software Foundation, either version 3 of the License, or
877
+ (at your option) any later version.
878
+
879
+ This program is distributed in the hope that it will be useful,
880
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
881
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
882
+ GNU General Public License for more details.
883
+
884
+ You should have received a copy of the GNU General Public License
885
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
886
+
887
+ Also add information on how to contact you by electronic and paper mail.
888
+
889
+ If the program does terminal interaction, make it output a short
890
+ notice like this when it starts in an interactive mode:
891
+
892
+ <program> Copyright (C) <year> <name of author>
893
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
894
+ This is free software, and you are welcome to redistribute it
895
+ under certain conditions; type `show c' for details.
896
+
897
+ The hypothetical commands `show w' and `show c' should show the appropriate
898
+ parts of the General Public License. Of course, your program's commands
899
+ might be different; for a GUI interface, you would use an "about box".
900
+
901
+ You should also get your employer (if you work as a programmer) or school,
902
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
903
+ For more information on this, and how to apply and follow the GNU GPL, see
904
+ <http://www.gnu.org/licenses/>.
905
+
906
+ The GNU General Public License does not permit incorporating your program
907
+ into proprietary programs. If your program is a subroutine library, you
908
+ may consider it more useful to permit linking proprietary applications with
909
+ the library. If this is what you want to do, use the GNU Lesser General
910
+ Public License instead of this License. But first, please read
911
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
912
+
913
+
914
+ Name: libquadmath
915
+ Files: scipy.libs/libquadmath*.so
916
+ Description: dynamically linked to files compiled with gcc
917
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath
918
+ License: LGPL-2.1-or-later
919
+
920
+ GCC Quad-Precision Math Library
921
+ Copyright (C) 2010-2019 Free Software Foundation, Inc.
922
+ Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org>
923
+
924
+ This file is part of the libquadmath library.
925
+ Libquadmath is free software; you can redistribute it and/or
926
+ modify it under the terms of the GNU Library General Public
927
+ License as published by the Free Software Foundation; either
928
+ version 2.1 of the License, or (at your option) any later version.
929
+
930
+ Libquadmath is distributed in the hope that it will be useful,
931
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
932
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
933
+ Lesser General Public License for more details.
934
+ https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/METADATA ADDED
@@ -0,0 +1,1082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: scipy
3
+ Version: 1.15.3
4
+ Summary: Fundamental algorithms for scientific computing in Python
5
+ Maintainer-Email: SciPy Developers <scipy-dev@python.org>
6
+ License: Copyright (c) 2001-2002 Enthought, Inc. 2003-2024, SciPy Developers.
7
+ All rights reserved.
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions
11
+ are met:
12
+
13
+ 1. Redistributions of source code must retain the above copyright
14
+ notice, this list of conditions and the following disclaimer.
15
+
16
+ 2. Redistributions in binary form must reproduce the above
17
+ copyright notice, this list of conditions and the following
18
+ disclaimer in the documentation and/or other materials provided
19
+ with the distribution.
20
+
21
+ 3. Neither the name of the copyright holder nor the names of its
22
+ contributors may be used to endorse or promote products derived
23
+ from this software without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
+
37
+ ----
38
+
39
+ This binary distribution of SciPy can also bundle the following software
40
+ (depending on the build):
41
+
42
+
43
+ Name: OpenBLAS
44
+ Files: scipy.libs/libscipy_openblas*.so
45
+ Description: bundled as a dynamically linked library
46
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
47
+ License: BSD-3-Clause-Attribution
48
+ Copyright (c) 2011-2014, The OpenBLAS Project
49
+ All rights reserved.
50
+
51
+ Redistribution and use in source and binary forms, with or without
52
+ modification, are permitted provided that the following conditions are
53
+ met:
54
+
55
+ 1. Redistributions of source code must retain the above copyright
56
+ notice, this list of conditions and the following disclaimer.
57
+
58
+ 2. Redistributions in binary form must reproduce the above copyright
59
+ notice, this list of conditions and the following disclaimer in
60
+ the documentation and/or other materials provided with the
61
+ distribution.
62
+ 3. Neither the name of the OpenBLAS project nor the names of
63
+ its contributors may be used to endorse or promote products
64
+ derived from this software without specific prior written
65
+ permission.
66
+
67
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
68
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
70
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
71
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
72
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
73
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
74
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
75
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
76
+ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
77
+
78
+
79
+ Name: LAPACK
80
+ Files: scipy.libs/libscipy_openblas*.so
81
+ Description: bundled in OpenBLAS
82
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
83
+ License: BSD-3-Clause-Attribution
84
+ Copyright (c) 1992-2013 The University of Tennessee and The University
85
+ of Tennessee Research Foundation. All rights
86
+ reserved.
87
+ Copyright (c) 2000-2013 The University of California Berkeley. All
88
+ rights reserved.
89
+ Copyright (c) 2006-2013 The University of Colorado Denver. All rights
90
+ reserved.
91
+
92
+ $COPYRIGHT$
93
+
94
+ Additional copyrights may follow
95
+
96
+ $HEADER$
97
+
98
+ Redistribution and use in source and binary forms, with or without
99
+ modification, are permitted provided that the following conditions are
100
+ met:
101
+
102
+ - Redistributions of source code must retain the above copyright
103
+ notice, this list of conditions and the following disclaimer.
104
+
105
+ - Redistributions in binary form must reproduce the above copyright
106
+ notice, this list of conditions and the following disclaimer listed
107
+ in this license in the documentation and/or other materials
108
+ provided with the distribution.
109
+
110
+ - Neither the name of the copyright holders nor the names of its
111
+ contributors may be used to endorse or promote products derived from
112
+ this software without specific prior written permission.
113
+
114
+ The copyright holders provide no reassurances that the source code
115
+ provided does not infringe any patent, copyright, or any other
116
+ intellectual property rights of third parties. The copyright holders
117
+ disclaim any liability to any recipient for claims brought against
118
+ recipient by any third party for infringement of that parties
119
+ intellectual property rights.
120
+
121
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
122
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
123
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
124
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
125
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
126
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
127
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
128
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
129
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
130
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
131
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
132
+
133
+
134
+ Name: GCC runtime library
135
+ Files: scipy.libs/libgfortran*.so
136
+ Description: dynamically linked to files compiled with gcc
137
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran
138
+ License: GPL-3.0-with-GCC-exception
139
+ Copyright (C) 2002-2017 Free Software Foundation, Inc.
140
+
141
+ Libgfortran is free software; you can redistribute it and/or modify
142
+ it under the terms of the GNU General Public License as published by
143
+ the Free Software Foundation; either version 3, or (at your option)
144
+ any later version.
145
+
146
+ Libgfortran is distributed in the hope that it will be useful,
147
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
148
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
149
+ GNU General Public License for more details.
150
+
151
+ Under Section 7 of GPL version 3, you are granted additional
152
+ permissions described in the GCC Runtime Library Exception, version
153
+ 3.1, as published by the Free Software Foundation.
154
+
155
+ You should have received a copy of the GNU General Public License and
156
+ a copy of the GCC Runtime Library Exception along with this program;
157
+ see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
158
+ <http://www.gnu.org/licenses/>.
159
+
160
+ ----
161
+
162
+ Full text of license texts referred to above follows (that they are
163
+ listed below does not necessarily imply the conditions apply to the
164
+ present binary release):
165
+
166
+ ----
167
+
168
+ GCC RUNTIME LIBRARY EXCEPTION
169
+
170
+ Version 3.1, 31 March 2009
171
+
172
+ Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
173
+
174
+ Everyone is permitted to copy and distribute verbatim copies of this
175
+ license document, but changing it is not allowed.
176
+
177
+ This GCC Runtime Library Exception ("Exception") is an additional
178
+ permission under section 7 of the GNU General Public License, version
179
+ 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that
180
+ bears a notice placed by the copyright holder of the file stating that
181
+ the file is governed by GPLv3 along with this Exception.
182
+
183
+ When you use GCC to compile a program, GCC may combine portions of
184
+ certain GCC header files and runtime libraries with the compiled
185
+ program. The purpose of this Exception is to allow compilation of
186
+ non-GPL (including proprietary) programs to use, in this way, the
187
+ header files and runtime libraries covered by this Exception.
188
+
189
+ 0. Definitions.
190
+
191
+ A file is an "Independent Module" if it either requires the Runtime
192
+ Library for execution after a Compilation Process, or makes use of an
193
+ interface provided by the Runtime Library, but is not otherwise based
194
+ on the Runtime Library.
195
+
196
+ "GCC" means a version of the GNU Compiler Collection, with or without
197
+ modifications, governed by version 3 (or a specified later version) of
198
+ the GNU General Public License (GPL) with the option of using any
199
+ subsequent versions published by the FSF.
200
+
201
+ "GPL-compatible Software" is software whose conditions of propagation,
202
+ modification and use would permit combination with GCC in accord with
203
+ the license of GCC.
204
+
205
+ "Target Code" refers to output from any compiler for a real or virtual
206
+ target processor architecture, in executable form or suitable for
207
+ input to an assembler, loader, linker and/or execution
208
+ phase. Notwithstanding that, Target Code does not include data in any
209
+ format that is used as a compiler intermediate representation, or used
210
+ for producing a compiler intermediate representation.
211
+
212
+ The "Compilation Process" transforms code entirely represented in
213
+ non-intermediate languages designed for human-written code, and/or in
214
+ Java Virtual Machine byte code, into Target Code. Thus, for example,
215
+ use of source code generators and preprocessors need not be considered
216
+ part of the Compilation Process, since the Compilation Process can be
217
+ understood as starting with the output of the generators or
218
+ preprocessors.
219
+
220
+ A Compilation Process is "Eligible" if it is done using GCC, alone or
221
+ with other GPL-compatible software, or if it is done without using any
222
+ work based on GCC. For example, using non-GPL-compatible Software to
223
+ optimize any GCC intermediate representations would not qualify as an
224
+ Eligible Compilation Process.
225
+
226
+ 1. Grant of Additional Permission.
227
+
228
+ You have permission to propagate a work of Target Code formed by
229
+ combining the Runtime Library with Independent Modules, even if such
230
+ propagation would otherwise violate the terms of GPLv3, provided that
231
+ all Target Code was generated by Eligible Compilation Processes. You
232
+ may then convey such a combination under terms of your choice,
233
+ consistent with the licensing of the Independent Modules.
234
+
235
+ 2. No Weakening of GCC Copyleft.
236
+
237
+ The availability of this Exception does not imply any general
238
+ presumption that third-party software is unaffected by the copyleft
239
+ requirements of the license of GCC.
240
+
241
+ ----
242
+
243
+ GNU GENERAL PUBLIC LICENSE
244
+ Version 3, 29 June 2007
245
+
246
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
247
+ Everyone is permitted to copy and distribute verbatim copies
248
+ of this license document, but changing it is not allowed.
249
+
250
+ Preamble
251
+
252
+ The GNU General Public License is a free, copyleft license for
253
+ software and other kinds of works.
254
+
255
+ The licenses for most software and other practical works are designed
256
+ to take away your freedom to share and change the works. By contrast,
257
+ the GNU General Public License is intended to guarantee your freedom to
258
+ share and change all versions of a program--to make sure it remains free
259
+ software for all its users. We, the Free Software Foundation, use the
260
+ GNU General Public License for most of our software; it applies also to
261
+ any other work released this way by its authors. You can apply it to
262
+ your programs, too.
263
+
264
+ When we speak of free software, we are referring to freedom, not
265
+ price. Our General Public Licenses are designed to make sure that you
266
+ have the freedom to distribute copies of free software (and charge for
267
+ them if you wish), that you receive source code or can get it if you
268
+ want it, that you can change the software or use pieces of it in new
269
+ free programs, and that you know you can do these things.
270
+
271
+ To protect your rights, we need to prevent others from denying you
272
+ these rights or asking you to surrender the rights. Therefore, you have
273
+ certain responsibilities if you distribute copies of the software, or if
274
+ you modify it: responsibilities to respect the freedom of others.
275
+
276
+ For example, if you distribute copies of such a program, whether
277
+ gratis or for a fee, you must pass on to the recipients the same
278
+ freedoms that you received. You must make sure that they, too, receive
279
+ or can get the source code. And you must show them these terms so they
280
+ know their rights.
281
+
282
+ Developers that use the GNU GPL protect your rights with two steps:
283
+ (1) assert copyright on the software, and (2) offer you this License
284
+ giving you legal permission to copy, distribute and/or modify it.
285
+
286
+ For the developers' and authors' protection, the GPL clearly explains
287
+ that there is no warranty for this free software. For both users' and
288
+ authors' sake, the GPL requires that modified versions be marked as
289
+ changed, so that their problems will not be attributed erroneously to
290
+ authors of previous versions.
291
+
292
+ Some devices are designed to deny users access to install or run
293
+ modified versions of the software inside them, although the manufacturer
294
+ can do so. This is fundamentally incompatible with the aim of
295
+ protecting users' freedom to change the software. The systematic
296
+ pattern of such abuse occurs in the area of products for individuals to
297
+ use, which is precisely where it is most unacceptable. Therefore, we
298
+ have designed this version of the GPL to prohibit the practice for those
299
+ products. If such problems arise substantially in other domains, we
300
+ stand ready to extend this provision to those domains in future versions
301
+ of the GPL, as needed to protect the freedom of users.
302
+
303
+ Finally, every program is threatened constantly by software patents.
304
+ States should not allow patents to restrict development and use of
305
+ software on general-purpose computers, but in those that do, we wish to
306
+ avoid the special danger that patents applied to a free program could
307
+ make it effectively proprietary. To prevent this, the GPL assures that
308
+ patents cannot be used to render the program non-free.
309
+
310
+ The precise terms and conditions for copying, distribution and
311
+ modification follow.
312
+
313
+ TERMS AND CONDITIONS
314
+
315
+ 0. Definitions.
316
+
317
+ "This License" refers to version 3 of the GNU General Public License.
318
+
319
+ "Copyright" also means copyright-like laws that apply to other kinds of
320
+ works, such as semiconductor masks.
321
+
322
+ "The Program" refers to any copyrightable work licensed under this
323
+ License. Each licensee is addressed as "you". "Licensees" and
324
+ "recipients" may be individuals or organizations.
325
+
326
+ To "modify" a work means to copy from or adapt all or part of the work
327
+ in a fashion requiring copyright permission, other than the making of an
328
+ exact copy. The resulting work is called a "modified version" of the
329
+ earlier work or a work "based on" the earlier work.
330
+
331
+ A "covered work" means either the unmodified Program or a work based
332
+ on the Program.
333
+
334
+ To "propagate" a work means to do anything with it that, without
335
+ permission, would make you directly or secondarily liable for
336
+ infringement under applicable copyright law, except executing it on a
337
+ computer or modifying a private copy. Propagation includes copying,
338
+ distribution (with or without modification), making available to the
339
+ public, and in some countries other activities as well.
340
+
341
+ To "convey" a work means any kind of propagation that enables other
342
+ parties to make or receive copies. Mere interaction with a user through
343
+ a computer network, with no transfer of a copy, is not conveying.
344
+
345
+ An interactive user interface displays "Appropriate Legal Notices"
346
+ to the extent that it includes a convenient and prominently visible
347
+ feature that (1) displays an appropriate copyright notice, and (2)
348
+ tells the user that there is no warranty for the work (except to the
349
+ extent that warranties are provided), that licensees may convey the
350
+ work under this License, and how to view a copy of this License. If
351
+ the interface presents a list of user commands or options, such as a
352
+ menu, a prominent item in the list meets this criterion.
353
+
354
+ 1. Source Code.
355
+
356
+ The "source code" for a work means the preferred form of the work
357
+ for making modifications to it. "Object code" means any non-source
358
+ form of a work.
359
+
360
+ A "Standard Interface" means an interface that either is an official
361
+ standard defined by a recognized standards body, or, in the case of
362
+ interfaces specified for a particular programming language, one that
363
+ is widely used among developers working in that language.
364
+
365
+ The "System Libraries" of an executable work include anything, other
366
+ than the work as a whole, that (a) is included in the normal form of
367
+ packaging a Major Component, but which is not part of that Major
368
+ Component, and (b) serves only to enable use of the work with that
369
+ Major Component, or to implement a Standard Interface for which an
370
+ implementation is available to the public in source code form. A
371
+ "Major Component", in this context, means a major essential component
372
+ (kernel, window system, and so on) of the specific operating system
373
+ (if any) on which the executable work runs, or a compiler used to
374
+ produce the work, or an object code interpreter used to run it.
375
+
376
+ The "Corresponding Source" for a work in object code form means all
377
+ the source code needed to generate, install, and (for an executable
378
+ work) run the object code and to modify the work, including scripts to
379
+ control those activities. However, it does not include the work's
380
+ System Libraries, or general-purpose tools or generally available free
381
+ programs which are used unmodified in performing those activities but
382
+ which are not part of the work. For example, Corresponding Source
383
+ includes interface definition files associated with source files for
384
+ the work, and the source code for shared libraries and dynamically
385
+ linked subprograms that the work is specifically designed to require,
386
+ such as by intimate data communication or control flow between those
387
+ subprograms and other parts of the work.
388
+
389
+ The Corresponding Source need not include anything that users
390
+ can regenerate automatically from other parts of the Corresponding
391
+ Source.
392
+
393
+ The Corresponding Source for a work in source code form is that
394
+ same work.
395
+
396
+ 2. Basic Permissions.
397
+
398
+ All rights granted under this License are granted for the term of
399
+ copyright on the Program, and are irrevocable provided the stated
400
+ conditions are met. This License explicitly affirms your unlimited
401
+ permission to run the unmodified Program. The output from running a
402
+ covered work is covered by this License only if the output, given its
403
+ content, constitutes a covered work. This License acknowledges your
404
+ rights of fair use or other equivalent, as provided by copyright law.
405
+
406
+ You may make, run and propagate covered works that you do not
407
+ convey, without conditions so long as your license otherwise remains
408
+ in force. You may convey covered works to others for the sole purpose
409
+ of having them make modifications exclusively for you, or provide you
410
+ with facilities for running those works, provided that you comply with
411
+ the terms of this License in conveying all material for which you do
412
+ not control copyright. Those thus making or running the covered works
413
+ for you must do so exclusively on your behalf, under your direction
414
+ and control, on terms that prohibit them from making any copies of
415
+ your copyrighted material outside their relationship with you.
416
+
417
+ Conveying under any other circumstances is permitted solely under
418
+ the conditions stated below. Sublicensing is not allowed; section 10
419
+ makes it unnecessary.
420
+
421
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
422
+
423
+ No covered work shall be deemed part of an effective technological
424
+ measure under any applicable law fulfilling obligations under article
425
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
426
+ similar laws prohibiting or restricting circumvention of such
427
+ measures.
428
+
429
+ When you convey a covered work, you waive any legal power to forbid
430
+ circumvention of technological measures to the extent such circumvention
431
+ is effected by exercising rights under this License with respect to
432
+ the covered work, and you disclaim any intention to limit operation or
433
+ modification of the work as a means of enforcing, against the work's
434
+ users, your or third parties' legal rights to forbid circumvention of
435
+ technological measures.
436
+
437
+ 4. Conveying Verbatim Copies.
438
+
439
+ You may convey verbatim copies of the Program's source code as you
440
+ receive it, in any medium, provided that you conspicuously and
441
+ appropriately publish on each copy an appropriate copyright notice;
442
+ keep intact all notices stating that this License and any
443
+ non-permissive terms added in accord with section 7 apply to the code;
444
+ keep intact all notices of the absence of any warranty; and give all
445
+ recipients a copy of this License along with the Program.
446
+
447
+ You may charge any price or no price for each copy that you convey,
448
+ and you may offer support or warranty protection for a fee.
449
+
450
+ 5. Conveying Modified Source Versions.
451
+
452
+ You may convey a work based on the Program, or the modifications to
453
+ produce it from the Program, in the form of source code under the
454
+ terms of section 4, provided that you also meet all of these conditions:
455
+
456
+ a) The work must carry prominent notices stating that you modified
457
+ it, and giving a relevant date.
458
+
459
+ b) The work must carry prominent notices stating that it is
460
+ released under this License and any conditions added under section
461
+ 7. This requirement modifies the requirement in section 4 to
462
+ "keep intact all notices".
463
+
464
+ c) You must license the entire work, as a whole, under this
465
+ License to anyone who comes into possession of a copy. This
466
+ License will therefore apply, along with any applicable section 7
467
+ additional terms, to the whole of the work, and all its parts,
468
+ regardless of how they are packaged. This License gives no
469
+ permission to license the work in any other way, but it does not
470
+ invalidate such permission if you have separately received it.
471
+
472
+ d) If the work has interactive user interfaces, each must display
473
+ Appropriate Legal Notices; however, if the Program has interactive
474
+ interfaces that do not display Appropriate Legal Notices, your
475
+ work need not make them do so.
476
+
477
+ A compilation of a covered work with other separate and independent
478
+ works, which are not by their nature extensions of the covered work,
479
+ and which are not combined with it such as to form a larger program,
480
+ in or on a volume of a storage or distribution medium, is called an
481
+ "aggregate" if the compilation and its resulting copyright are not
482
+ used to limit the access or legal rights of the compilation's users
483
+ beyond what the individual works permit. Inclusion of a covered work
484
+ in an aggregate does not cause this License to apply to the other
485
+ parts of the aggregate.
486
+
487
+ 6. Conveying Non-Source Forms.
488
+
489
+ You may convey a covered work in object code form under the terms
490
+ of sections 4 and 5, provided that you also convey the
491
+ machine-readable Corresponding Source under the terms of this License,
492
+ in one of these ways:
493
+
494
+ a) Convey the object code in, or embodied in, a physical product
495
+ (including a physical distribution medium), accompanied by the
496
+ Corresponding Source fixed on a durable physical medium
497
+ customarily used for software interchange.
498
+
499
+ b) Convey the object code in, or embodied in, a physical product
500
+ (including a physical distribution medium), accompanied by a
501
+ written offer, valid for at least three years and valid for as
502
+ long as you offer spare parts or customer support for that product
503
+ model, to give anyone who possesses the object code either (1) a
504
+ copy of the Corresponding Source for all the software in the
505
+ product that is covered by this License, on a durable physical
506
+ medium customarily used for software interchange, for a price no
507
+ more than your reasonable cost of physically performing this
508
+ conveying of source, or (2) access to copy the
509
+ Corresponding Source from a network server at no charge.
510
+
511
+ c) Convey individual copies of the object code with a copy of the
512
+ written offer to provide the Corresponding Source. This
513
+ alternative is allowed only occasionally and noncommercially, and
514
+ only if you received the object code with such an offer, in accord
515
+ with subsection 6b.
516
+
517
+ d) Convey the object code by offering access from a designated
518
+ place (gratis or for a charge), and offer equivalent access to the
519
+ Corresponding Source in the same way through the same place at no
520
+ further charge. You need not require recipients to copy the
521
+ Corresponding Source along with the object code. If the place to
522
+ copy the object code is a network server, the Corresponding Source
523
+ may be on a different server (operated by you or a third party)
524
+ that supports equivalent copying facilities, provided you maintain
525
+ clear directions next to the object code saying where to find the
526
+ Corresponding Source. Regardless of what server hosts the
527
+ Corresponding Source, you remain obligated to ensure that it is
528
+ available for as long as needed to satisfy these requirements.
529
+
530
+ e) Convey the object code using peer-to-peer transmission, provided
531
+ you inform other peers where the object code and Corresponding
532
+ Source of the work are being offered to the general public at no
533
+ charge under subsection 6d.
534
+
535
+ A separable portion of the object code, whose source code is excluded
536
+ from the Corresponding Source as a System Library, need not be
537
+ included in conveying the object code work.
538
+
539
+ A "User Product" is either (1) a "consumer product", which means any
540
+ tangible personal property which is normally used for personal, family,
541
+ or household purposes, or (2) anything designed or sold for incorporation
542
+ into a dwelling. In determining whether a product is a consumer product,
543
+ doubtful cases shall be resolved in favor of coverage. For a particular
544
+ product received by a particular user, "normally used" refers to a
545
+ typical or common use of that class of product, regardless of the status
546
+ of the particular user or of the way in which the particular user
547
+ actually uses, or expects or is expected to use, the product. A product
548
+ is a consumer product regardless of whether the product has substantial
549
+ commercial, industrial or non-consumer uses, unless such uses represent
550
+ the only significant mode of use of the product.
551
+
552
+ "Installation Information" for a User Product means any methods,
553
+ procedures, authorization keys, or other information required to install
554
+ and execute modified versions of a covered work in that User Product from
555
+ a modified version of its Corresponding Source. The information must
556
+ suffice to ensure that the continued functioning of the modified object
557
+ code is in no case prevented or interfered with solely because
558
+ modification has been made.
559
+
560
+ If you convey an object code work under this section in, or with, or
561
+ specifically for use in, a User Product, and the conveying occurs as
562
+ part of a transaction in which the right of possession and use of the
563
+ User Product is transferred to the recipient in perpetuity or for a
564
+ fixed term (regardless of how the transaction is characterized), the
565
+ Corresponding Source conveyed under this section must be accompanied
566
+ by the Installation Information. But this requirement does not apply
567
+ if neither you nor any third party retains the ability to install
568
+ modified object code on the User Product (for example, the work has
569
+ been installed in ROM).
570
+
571
+ The requirement to provide Installation Information does not include a
572
+ requirement to continue to provide support service, warranty, or updates
573
+ for a work that has been modified or installed by the recipient, or for
574
+ the User Product in which it has been modified or installed. Access to a
575
+ network may be denied when the modification itself materially and
576
+ adversely affects the operation of the network or violates the rules and
577
+ protocols for communication across the network.
578
+
579
+ Corresponding Source conveyed, and Installation Information provided,
580
+ in accord with this section must be in a format that is publicly
581
+ documented (and with an implementation available to the public in
582
+ source code form), and must require no special password or key for
583
+ unpacking, reading or copying.
584
+
585
+ 7. Additional Terms.
586
+
587
+ "Additional permissions" are terms that supplement the terms of this
588
+ License by making exceptions from one or more of its conditions.
589
+ Additional permissions that are applicable to the entire Program shall
590
+ be treated as though they were included in this License, to the extent
591
+ that they are valid under applicable law. If additional permissions
592
+ apply only to part of the Program, that part may be used separately
593
+ under those permissions, but the entire Program remains governed by
594
+ this License without regard to the additional permissions.
595
+
596
+ When you convey a copy of a covered work, you may at your option
597
+ remove any additional permissions from that copy, or from any part of
598
+ it. (Additional permissions may be written to require their own
599
+ removal in certain cases when you modify the work.) You may place
600
+ additional permissions on material, added by you to a covered work,
601
+ for which you have or can give appropriate copyright permission.
602
+
603
+ Notwithstanding any other provision of this License, for material you
604
+ add to a covered work, you may (if authorized by the copyright holders of
605
+ that material) supplement the terms of this License with terms:
606
+
607
+ a) Disclaiming warranty or limiting liability differently from the
608
+ terms of sections 15 and 16 of this License; or
609
+
610
+ b) Requiring preservation of specified reasonable legal notices or
611
+ author attributions in that material or in the Appropriate Legal
612
+ Notices displayed by works containing it; or
613
+
614
+ c) Prohibiting misrepresentation of the origin of that material, or
615
+ requiring that modified versions of such material be marked in
616
+ reasonable ways as different from the original version; or
617
+
618
+ d) Limiting the use for publicity purposes of names of licensors or
619
+ authors of the material; or
620
+
621
+ e) Declining to grant rights under trademark law for use of some
622
+ trade names, trademarks, or service marks; or
623
+
624
+ f) Requiring indemnification of licensors and authors of that
625
+ material by anyone who conveys the material (or modified versions of
626
+ it) with contractual assumptions of liability to the recipient, for
627
+ any liability that these contractual assumptions directly impose on
628
+ those licensors and authors.
629
+
630
+ All other non-permissive additional terms are considered "further
631
+ restrictions" within the meaning of section 10. If the Program as you
632
+ received it, or any part of it, contains a notice stating that it is
633
+ governed by this License along with a term that is a further
634
+ restriction, you may remove that term. If a license document contains
635
+ a further restriction but permits relicensing or conveying under this
636
+ License, you may add to a covered work material governed by the terms
637
+ of that license document, provided that the further restriction does
638
+ not survive such relicensing or conveying.
639
+
640
+ If you add terms to a covered work in accord with this section, you
641
+ must place, in the relevant source files, a statement of the
642
+ additional terms that apply to those files, or a notice indicating
643
+ where to find the applicable terms.
644
+
645
+ Additional terms, permissive or non-permissive, may be stated in the
646
+ form of a separately written license, or stated as exceptions;
647
+ the above requirements apply either way.
648
+
649
+ 8. Termination.
650
+
651
+ You may not propagate or modify a covered work except as expressly
652
+ provided under this License. Any attempt otherwise to propagate or
653
+ modify it is void, and will automatically terminate your rights under
654
+ this License (including any patent licenses granted under the third
655
+ paragraph of section 11).
656
+
657
+ However, if you cease all violation of this License, then your
658
+ license from a particular copyright holder is reinstated (a)
659
+ provisionally, unless and until the copyright holder explicitly and
660
+ finally terminates your license, and (b) permanently, if the copyright
661
+ holder fails to notify you of the violation by some reasonable means
662
+ prior to 60 days after the cessation.
663
+
664
+ Moreover, your license from a particular copyright holder is
665
+ reinstated permanently if the copyright holder notifies you of the
666
+ violation by some reasonable means, this is the first time you have
667
+ received notice of violation of this License (for any work) from that
668
+ copyright holder, and you cure the violation prior to 30 days after
669
+ your receipt of the notice.
670
+
671
+ Termination of your rights under this section does not terminate the
672
+ licenses of parties who have received copies or rights from you under
673
+ this License. If your rights have been terminated and not permanently
674
+ reinstated, you do not qualify to receive new licenses for the same
675
+ material under section 10.
676
+
677
+ 9. Acceptance Not Required for Having Copies.
678
+
679
+ You are not required to accept this License in order to receive or
680
+ run a copy of the Program. Ancillary propagation of a covered work
681
+ occurring solely as a consequence of using peer-to-peer transmission
682
+ to receive a copy likewise does not require acceptance. However,
683
+ nothing other than this License grants you permission to propagate or
684
+ modify any covered work. These actions infringe copyright if you do
685
+ not accept this License. Therefore, by modifying or propagating a
686
+ covered work, you indicate your acceptance of this License to do so.
687
+
688
+ 10. Automatic Licensing of Downstream Recipients.
689
+
690
+ Each time you convey a covered work, the recipient automatically
691
+ receives a license from the original licensors, to run, modify and
692
+ propagate that work, subject to this License. You are not responsible
693
+ for enforcing compliance by third parties with this License.
694
+
695
+ An "entity transaction" is a transaction transferring control of an
696
+ organization, or substantially all assets of one, or subdividing an
697
+ organization, or merging organizations. If propagation of a covered
698
+ work results from an entity transaction, each party to that
699
+ transaction who receives a copy of the work also receives whatever
700
+ licenses to the work the party's predecessor in interest had or could
701
+ give under the previous paragraph, plus a right to possession of the
702
+ Corresponding Source of the work from the predecessor in interest, if
703
+ the predecessor has it or can get it with reasonable efforts.
704
+
705
+ You may not impose any further restrictions on the exercise of the
706
+ rights granted or affirmed under this License. For example, you may
707
+ not impose a license fee, royalty, or other charge for exercise of
708
+ rights granted under this License, and you may not initiate litigation
709
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
710
+ any patent claim is infringed by making, using, selling, offering for
711
+ sale, or importing the Program or any portion of it.
712
+
713
+ 11. Patents.
714
+
715
+ A "contributor" is a copyright holder who authorizes use under this
716
+ License of the Program or a work on which the Program is based. The
717
+ work thus licensed is called the contributor's "contributor version".
718
+
719
+ A contributor's "essential patent claims" are all patent claims
720
+ owned or controlled by the contributor, whether already acquired or
721
+ hereafter acquired, that would be infringed by some manner, permitted
722
+ by this License, of making, using, or selling its contributor version,
723
+ but do not include claims that would be infringed only as a
724
+ consequence of further modification of the contributor version. For
725
+ purposes of this definition, "control" includes the right to grant
726
+ patent sublicenses in a manner consistent with the requirements of
727
+ this License.
728
+
729
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
730
+ patent license under the contributor's essential patent claims, to
731
+ make, use, sell, offer for sale, import and otherwise run, modify and
732
+ propagate the contents of its contributor version.
733
+
734
+ In the following three paragraphs, a "patent license" is any express
735
+ agreement or commitment, however denominated, not to enforce a patent
736
+ (such as an express permission to practice a patent or covenant not to
737
+ sue for patent infringement). To "grant" such a patent license to a
738
+ party means to make such an agreement or commitment not to enforce a
739
+ patent against the party.
740
+
741
+ If you convey a covered work, knowingly relying on a patent license,
742
+ and the Corresponding Source of the work is not available for anyone
743
+ to copy, free of charge and under the terms of this License, through a
744
+ publicly available network server or other readily accessible means,
745
+ then you must either (1) cause the Corresponding Source to be so
746
+ available, or (2) arrange to deprive yourself of the benefit of the
747
+ patent license for this particular work, or (3) arrange, in a manner
748
+ consistent with the requirements of this License, to extend the patent
749
+ license to downstream recipients. "Knowingly relying" means you have
750
+ actual knowledge that, but for the patent license, your conveying the
751
+ covered work in a country, or your recipient's use of the covered work
752
+ in a country, would infringe one or more identifiable patents in that
753
+ country that you have reason to believe are valid.
754
+
755
+ If, pursuant to or in connection with a single transaction or
756
+ arrangement, you convey, or propagate by procuring conveyance of, a
757
+ covered work, and grant a patent license to some of the parties
758
+ receiving the covered work authorizing them to use, propagate, modify
759
+ or convey a specific copy of the covered work, then the patent license
760
+ you grant is automatically extended to all recipients of the covered
761
+ work and works based on it.
762
+
763
+ A patent license is "discriminatory" if it does not include within
764
+ the scope of its coverage, prohibits the exercise of, or is
765
+ conditioned on the non-exercise of one or more of the rights that are
766
+ specifically granted under this License. You may not convey a covered
767
+ work if you are a party to an arrangement with a third party that is
768
+ in the business of distributing software, under which you make payment
769
+ to the third party based on the extent of your activity of conveying
770
+ the work, and under which the third party grants, to any of the
771
+ parties who would receive the covered work from you, a discriminatory
772
+ patent license (a) in connection with copies of the covered work
773
+ conveyed by you (or copies made from those copies), or (b) primarily
774
+ for and in connection with specific products or compilations that
775
+ contain the covered work, unless you entered into that arrangement,
776
+ or that patent license was granted, prior to 28 March 2007.
777
+
778
+ Nothing in this License shall be construed as excluding or limiting
779
+ any implied license or other defenses to infringement that may
780
+ otherwise be available to you under applicable patent law.
781
+
782
+ 12. No Surrender of Others' Freedom.
783
+
784
+ If conditions are imposed on you (whether by court order, agreement or
785
+ otherwise) that contradict the conditions of this License, they do not
786
+ excuse you from the conditions of this License. If you cannot convey a
787
+ covered work so as to satisfy simultaneously your obligations under this
788
+ License and any other pertinent obligations, then as a consequence you may
789
+ not convey it at all. For example, if you agree to terms that obligate you
790
+ to collect a royalty for further conveying from those to whom you convey
791
+ the Program, the only way you could satisfy both those terms and this
792
+ License would be to refrain entirely from conveying the Program.
793
+
794
+ 13. Use with the GNU Affero General Public License.
795
+
796
+ Notwithstanding any other provision of this License, you have
797
+ permission to link or combine any covered work with a work licensed
798
+ under version 3 of the GNU Affero General Public License into a single
799
+ combined work, and to convey the resulting work. The terms of this
800
+ License will continue to apply to the part which is the covered work,
801
+ but the special requirements of the GNU Affero General Public License,
802
+ section 13, concerning interaction through a network will apply to the
803
+ combination as such.
804
+
805
+ 14. Revised Versions of this License.
806
+
807
+ The Free Software Foundation may publish revised and/or new versions of
808
+ the GNU General Public License from time to time. Such new versions will
809
+ be similar in spirit to the present version, but may differ in detail to
810
+ address new problems or concerns.
811
+
812
+ Each version is given a distinguishing version number. If the
813
+ Program specifies that a certain numbered version of the GNU General
814
+ Public License "or any later version" applies to it, you have the
815
+ option of following the terms and conditions either of that numbered
816
+ version or of any later version published by the Free Software
817
+ Foundation. If the Program does not specify a version number of the
818
+ GNU General Public License, you may choose any version ever published
819
+ by the Free Software Foundation.
820
+
821
+ If the Program specifies that a proxy can decide which future
822
+ versions of the GNU General Public License can be used, that proxy's
823
+ public statement of acceptance of a version permanently authorizes you
824
+ to choose that version for the Program.
825
+
826
+ Later license versions may give you additional or different
827
+ permissions. However, no additional obligations are imposed on any
828
+ author or copyright holder as a result of your choosing to follow a
829
+ later version.
830
+
831
+ 15. Disclaimer of Warranty.
832
+
833
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
834
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
835
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
836
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
837
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
838
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
839
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
840
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
841
+
842
+ 16. Limitation of Liability.
843
+
844
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
845
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
846
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
847
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
848
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
849
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
850
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
851
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
852
+ SUCH DAMAGES.
853
+
854
+ 17. Interpretation of Sections 15 and 16.
855
+
856
+ If the disclaimer of warranty and limitation of liability provided
857
+ above cannot be given local legal effect according to their terms,
858
+ reviewing courts shall apply local law that most closely approximates
859
+ an absolute waiver of all civil liability in connection with the
860
+ Program, unless a warranty or assumption of liability accompanies a
861
+ copy of the Program in return for a fee.
862
+
863
+ END OF TERMS AND CONDITIONS
864
+
865
+ How to Apply These Terms to Your New Programs
866
+
867
+ If you develop a new program, and you want it to be of the greatest
868
+ possible use to the public, the best way to achieve this is to make it
869
+ free software which everyone can redistribute and change under these terms.
870
+
871
+ To do so, attach the following notices to the program. It is safest
872
+ to attach them to the start of each source file to most effectively
873
+ state the exclusion of warranty; and each file should have at least
874
+ the "copyright" line and a pointer to where the full notice is found.
875
+
876
+ <one line to give the program's name and a brief idea of what it does.>
877
+ Copyright (C) <year> <name of author>
878
+
879
+ This program is free software: you can redistribute it and/or modify
880
+ it under the terms of the GNU General Public License as published by
881
+ the Free Software Foundation, either version 3 of the License, or
882
+ (at your option) any later version.
883
+
884
+ This program is distributed in the hope that it will be useful,
885
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
886
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
887
+ GNU General Public License for more details.
888
+
889
+ You should have received a copy of the GNU General Public License
890
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
891
+
892
+ Also add information on how to contact you by electronic and paper mail.
893
+
894
+ If the program does terminal interaction, make it output a short
895
+ notice like this when it starts in an interactive mode:
896
+
897
+ <program> Copyright (C) <year> <name of author>
898
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
899
+ This is free software, and you are welcome to redistribute it
900
+ under certain conditions; type `show c' for details.
901
+
902
+ The hypothetical commands `show w' and `show c' should show the appropriate
903
+ parts of the General Public License. Of course, your program's commands
904
+ might be different; for a GUI interface, you would use an "about box".
905
+
906
+ You should also get your employer (if you work as a programmer) or school,
907
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
908
+ For more information on this, and how to apply and follow the GNU GPL, see
909
+ <http://www.gnu.org/licenses/>.
910
+
911
+ The GNU General Public License does not permit incorporating your program
912
+ into proprietary programs. If your program is a subroutine library, you
913
+ may consider it more useful to permit linking proprietary applications with
914
+ the library. If this is what you want to do, use the GNU Lesser General
915
+ Public License instead of this License. But first, please read
916
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
917
+
918
+
919
+ Name: libquadmath
920
+ Files: scipy.libs/libquadmath*.so
921
+ Description: dynamically linked to files compiled with gcc
922
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath
923
+ License: LGPL-2.1-or-later
924
+
925
+ GCC Quad-Precision Math Library
926
+ Copyright (C) 2010-2019 Free Software Foundation, Inc.
927
+ Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org>
928
+
929
+ This file is part of the libquadmath library.
930
+ Libquadmath is free software; you can redistribute it and/or
931
+ modify it under the terms of the GNU Library General Public
932
+ License as published by the Free Software Foundation; either
933
+ version 2.1 of the License, or (at your option) any later version.
934
+
935
+ Libquadmath is distributed in the hope that it will be useful,
936
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
937
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
938
+ Lesser General Public License for more details.
939
+ https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
940
+
941
+ Classifier: Development Status :: 5 - Production/Stable
942
+ Classifier: Intended Audience :: Science/Research
943
+ Classifier: Intended Audience :: Developers
944
+ Classifier: License :: OSI Approved :: BSD License
945
+ Classifier: Programming Language :: C
946
+ Classifier: Programming Language :: Python
947
+ Classifier: Programming Language :: Python :: 3
948
+ Classifier: Programming Language :: Python :: 3.10
949
+ Classifier: Programming Language :: Python :: 3.11
950
+ Classifier: Programming Language :: Python :: 3.12
951
+ Classifier: Programming Language :: Python :: 3.13
952
+ Classifier: Topic :: Software Development :: Libraries
953
+ Classifier: Topic :: Scientific/Engineering
954
+ Classifier: Operating System :: Microsoft :: Windows
955
+ Classifier: Operating System :: POSIX :: Linux
956
+ Classifier: Operating System :: POSIX
957
+ Classifier: Operating System :: Unix
958
+ Classifier: Operating System :: MacOS
959
+ Project-URL: homepage, https://scipy.org/
960
+ Project-URL: documentation, https://docs.scipy.org/doc/scipy/
961
+ Project-URL: source, https://github.com/scipy/scipy
962
+ Project-URL: download, https://github.com/scipy/scipy/releases
963
+ Project-URL: tracker, https://github.com/scipy/scipy/issues
964
+ Requires-Python: >=3.10
965
+ Requires-Dist: numpy<2.5,>=1.23.5
966
+ Provides-Extra: test
967
+ Requires-Dist: pytest; extra == "test"
968
+ Requires-Dist: pytest-cov; extra == "test"
969
+ Requires-Dist: pytest-timeout; extra == "test"
970
+ Requires-Dist: pytest-xdist; extra == "test"
971
+ Requires-Dist: asv; extra == "test"
972
+ Requires-Dist: mpmath; extra == "test"
973
+ Requires-Dist: gmpy2; extra == "test"
974
+ Requires-Dist: threadpoolctl; extra == "test"
975
+ Requires-Dist: scikit-umfpack; extra == "test"
976
+ Requires-Dist: pooch; extra == "test"
977
+ Requires-Dist: hypothesis>=6.30; extra == "test"
978
+ Requires-Dist: array-api-strict<2.1.1,>=2.0; extra == "test"
979
+ Requires-Dist: Cython; extra == "test"
980
+ Requires-Dist: meson; extra == "test"
981
+ Requires-Dist: ninja; sys_platform != "emscripten" and extra == "test"
982
+ Provides-Extra: doc
983
+ Requires-Dist: sphinx<8.0.0,>=5.0.0; extra == "doc"
984
+ Requires-Dist: intersphinx_registry; extra == "doc"
985
+ Requires-Dist: pydata-sphinx-theme>=0.15.2; extra == "doc"
986
+ Requires-Dist: sphinx-copybutton; extra == "doc"
987
+ Requires-Dist: sphinx-design>=0.4.0; extra == "doc"
988
+ Requires-Dist: matplotlib>=3.5; extra == "doc"
989
+ Requires-Dist: numpydoc; extra == "doc"
990
+ Requires-Dist: jupytext; extra == "doc"
991
+ Requires-Dist: myst-nb; extra == "doc"
992
+ Requires-Dist: pooch; extra == "doc"
993
+ Requires-Dist: jupyterlite-sphinx>=0.19.1; extra == "doc"
994
+ Requires-Dist: jupyterlite-pyodide-kernel; extra == "doc"
995
+ Provides-Extra: dev
996
+ Requires-Dist: mypy==1.10.0; extra == "dev"
997
+ Requires-Dist: typing_extensions; extra == "dev"
998
+ Requires-Dist: types-psutil; extra == "dev"
999
+ Requires-Dist: pycodestyle; extra == "dev"
1000
+ Requires-Dist: ruff>=0.0.292; extra == "dev"
1001
+ Requires-Dist: cython-lint>=0.12.2; extra == "dev"
1002
+ Requires-Dist: rich-click; extra == "dev"
1003
+ Requires-Dist: doit>=0.36.0; extra == "dev"
1004
+ Requires-Dist: pydevtool; extra == "dev"
1005
+ Description-Content-Type: text/x-rst
1006
+
1007
+ .. image:: https://raw.githubusercontent.com/scipy/scipy/main/doc/source/_static/logo.svg
1008
+ :target: https://scipy.org
1009
+ :width: 110
1010
+ :height: 110
1011
+ :align: left
1012
+
1013
+ .. image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A
1014
+ :target: https://numfocus.org
1015
+
1016
+ .. image:: https://img.shields.io/pypi/dm/scipy.svg?label=Pypi%20downloads
1017
+ :target: https://pypi.org/project/scipy/
1018
+
1019
+ .. image:: https://img.shields.io/conda/dn/conda-forge/scipy.svg?label=Conda%20downloads
1020
+ :target: https://anaconda.org/conda-forge/scipy
1021
+
1022
+ .. image:: https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg
1023
+ :target: https://stackoverflow.com/questions/tagged/scipy
1024
+
1025
+ .. image:: https://img.shields.io/badge/DOI-10.1038%2Fs41592--019--0686--2-blue.svg
1026
+ :target: https://www.nature.com/articles/s41592-019-0686-2
1027
+
1028
+ SciPy (pronounced "Sigh Pie") is an open-source software for mathematics,
1029
+ science, and engineering. It includes modules for statistics, optimization,
1030
+ integration, linear algebra, Fourier transforms, signal and image processing,
1031
+ ODE solvers, and more.
1032
+
1033
+ - **Website:** https://scipy.org
1034
+ - **Documentation:** https://docs.scipy.org/doc/scipy/
1035
+ - **Development version of the documentation:** https://scipy.github.io/devdocs
1036
+ - **SciPy development forum:** https://discuss.scientific-python.org/c/contributor/scipy
1037
+ - **Stack Overflow:** https://stackoverflow.com/questions/tagged/scipy
1038
+ - **Source code:** https://github.com/scipy/scipy
1039
+ - **Contributing:** https://scipy.github.io/devdocs/dev/index.html
1040
+ - **Bug reports:** https://github.com/scipy/scipy/issues
1041
+ - **Code of Conduct:** https://docs.scipy.org/doc/scipy/dev/conduct/code_of_conduct.html
1042
+ - **Report a security vulnerability:** https://tidelift.com/docs/security
1043
+ - **Citing in your work:** https://www.scipy.org/citing-scipy/
1044
+
1045
+ SciPy is built to work with
1046
+ NumPy arrays, and provides many user-friendly and efficient numerical routines,
1047
+ such as routines for numerical integration and optimization. Together, they
1048
+ run on all popular operating systems, are quick to install, and are free of
1049
+ charge. NumPy and SciPy are easy to use, but powerful enough to be depended
1050
+ upon by some of the world's leading scientists and engineers. If you need to
1051
+ manipulate numbers on a computer and display or publish the results, give
1052
+ SciPy a try!
1053
+
1054
+ For the installation instructions, see `our install
1055
+ guide <https://scipy.org/install/>`__.
1056
+
1057
+
1058
+ Call for Contributions
1059
+ ----------------------
1060
+
1061
+ We appreciate and welcome contributions. Small improvements or fixes are always appreciated; issues labeled as "good
1062
+ first issue" may be a good starting point. Have a look at `our contributing
1063
+ guide <https://scipy.github.io/devdocs/dev/index.html>`__.
1064
+
1065
+ Writing code isn’t the only way to contribute to SciPy. You can also:
1066
+
1067
+ - review pull requests
1068
+ - triage issues
1069
+ - develop tutorials, presentations, and other educational materials
1070
+ - maintain and improve `our website <https://github.com/scipy/scipy.org>`__
1071
+ - develop graphic design for our brand assets and promotional materials
1072
+ - help with outreach and onboard new contributors
1073
+ - write grant proposals and help with other fundraising efforts
1074
+
1075
+ If you’re unsure where to start or how your skills fit in, reach out! You can
1076
+ ask on the `forum <https://discuss.scientific-python.org/c/contributor/scipy>`__
1077
+ or here, on GitHub, by leaving a comment on a relevant issue that is already
1078
+ open.
1079
+
1080
+ If you are new to contributing to open source, `this
1081
+ guide <https://opensource.guide/how-to-contribute/>`__ helps explain why, what,
1082
+ and how to get involved.
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy-1.15.3.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: meson
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-manylinux_2_17_x86_64
5
+ Tag: cp311-cp311-manylinux2014_x86_64
6
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6090048eccc763522c12ef016f81da6b627cb3a044f55cf0479a839c41c0980
3
+ size 2833617
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14afb3129b1a8b50bc40a3b0820c7f1152ea9bc10121aab152943f7057472886
3
+ size 2686065
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ed5137f412781ad7863439fb543613f620b43c32b63292a0029246162f5bbc6
3
+ size 250985
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:934c22ded0e7d169c4d4678876c96051adf3d94545da962f60b41659b075da3b
3
+ size 247609
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_mstats_extras.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Additional statistics functions with support for masked arrays.
3
+
4
+ """
5
+
6
+ # Original author (2007): Pierre GF Gerard-Marchant
7
+
8
+
9
+ __all__ = ['compare_medians_ms',
10
+ 'hdquantiles', 'hdmedian', 'hdquantiles_sd',
11
+ 'idealfourths',
12
+ 'median_cihs','mjci','mquantiles_cimj',
13
+ 'rsh',
14
+ 'trimmed_mean_ci',]
15
+
16
+
17
+ import numpy as np
18
+ from numpy import float64, ndarray
19
+
20
+ import numpy.ma as ma
21
+ from numpy.ma import MaskedArray
22
+
23
+ from . import _mstats_basic as mstats
24
+
25
+ from scipy.stats.distributions import norm, beta, t, binom
26
+
27
+
28
+ def hdquantiles(data, prob=(.25, .5, .75), axis=None, var=False,):
29
+ """
30
+ Computes quantile estimates with the Harrell-Davis method.
31
+
32
+ The quantile estimates are calculated as a weighted linear combination
33
+ of order statistics.
34
+
35
+ Parameters
36
+ ----------
37
+ data : array_like
38
+ Data array.
39
+ prob : sequence, optional
40
+ Sequence of probabilities at which to compute the quantiles.
41
+ axis : int or None, optional
42
+ Axis along which to compute the quantiles. If None, use a flattened
43
+ array.
44
+ var : bool, optional
45
+ Whether to return the variance of the estimate.
46
+
47
+ Returns
48
+ -------
49
+ hdquantiles : MaskedArray
50
+ A (p,) array of quantiles (if `var` is False), or a (2,p) array of
51
+ quantiles and variances (if `var` is True), where ``p`` is the
52
+ number of quantiles.
53
+
54
+ See Also
55
+ --------
56
+ hdquantiles_sd
57
+
58
+ Examples
59
+ --------
60
+ >>> import numpy as np
61
+ >>> from scipy.stats.mstats import hdquantiles
62
+ >>>
63
+ >>> # Sample data
64
+ >>> data = np.array([1.2, 2.5, 3.7, 4.0, 5.1, 6.3, 7.0, 8.2, 9.4])
65
+ >>>
66
+ >>> # Probabilities at which to compute quantiles
67
+ >>> probabilities = [0.25, 0.5, 0.75]
68
+ >>>
69
+ >>> # Compute Harrell-Davis quantile estimates
70
+ >>> quantile_estimates = hdquantiles(data, prob=probabilities)
71
+ >>>
72
+ >>> # Display the quantile estimates
73
+ >>> for i, quantile in enumerate(probabilities):
74
+ ... print(f"{int(quantile * 100)}th percentile: {quantile_estimates[i]}")
75
+ 25th percentile: 3.1505820231763066 # may vary
76
+ 50th percentile: 5.194344084883956
77
+ 75th percentile: 7.430626414674935
78
+
79
+ """
80
+ def _hd_1D(data,prob,var):
81
+ "Computes the HD quantiles for a 1D array. Returns nan for invalid data."
82
+ xsorted = np.squeeze(np.sort(data.compressed().view(ndarray)))
83
+ # Don't use length here, in case we have a numpy scalar
84
+ n = xsorted.size
85
+
86
+ hd = np.empty((2,len(prob)), float64)
87
+ if n < 2:
88
+ hd.flat = np.nan
89
+ if var:
90
+ return hd
91
+ return hd[0]
92
+
93
+ v = np.arange(n+1) / float(n)
94
+ betacdf = beta.cdf
95
+ for (i,p) in enumerate(prob):
96
+ _w = betacdf(v, (n+1)*p, (n+1)*(1-p))
97
+ w = _w[1:] - _w[:-1]
98
+ hd_mean = np.dot(w, xsorted)
99
+ hd[0,i] = hd_mean
100
+ #
101
+ hd[1,i] = np.dot(w, (xsorted-hd_mean)**2)
102
+ #
103
+ hd[0, prob == 0] = xsorted[0]
104
+ hd[0, prob == 1] = xsorted[-1]
105
+ if var:
106
+ hd[1, prob == 0] = hd[1, prob == 1] = np.nan
107
+ return hd
108
+ return hd[0]
109
+ # Initialization & checks
110
+ data = ma.array(data, copy=False, dtype=float64)
111
+ p = np.atleast_1d(np.asarray(prob))
112
+ # Computes quantiles along axis (or globally)
113
+ if (axis is None) or (data.ndim == 1):
114
+ result = _hd_1D(data, p, var)
115
+ else:
116
+ if data.ndim > 2:
117
+ raise ValueError("Array 'data' must be at most two dimensional, "
118
+ "but got data.ndim = %d" % data.ndim)
119
+ result = ma.apply_along_axis(_hd_1D, axis, data, p, var)
120
+
121
+ return ma.fix_invalid(result, copy=False)
122
+
123
+
124
+ def hdmedian(data, axis=-1, var=False):
125
+ """
126
+ Returns the Harrell-Davis estimate of the median along the given axis.
127
+
128
+ Parameters
129
+ ----------
130
+ data : ndarray
131
+ Data array.
132
+ axis : int, optional
133
+ Axis along which to compute the quantiles. If None, use a flattened
134
+ array.
135
+ var : bool, optional
136
+ Whether to return the variance of the estimate.
137
+
138
+ Returns
139
+ -------
140
+ hdmedian : MaskedArray
141
+ The median values. If ``var=True``, the variance is returned inside
142
+ the masked array. E.g. for a 1-D array the shape change from (1,) to
143
+ (2,).
144
+
145
+ """
146
+ result = hdquantiles(data,[0.5], axis=axis, var=var)
147
+ return result.squeeze()
148
+
149
+
150
+ def hdquantiles_sd(data, prob=(.25, .5, .75), axis=None):
151
+ """
152
+ The standard error of the Harrell-Davis quantile estimates by jackknife.
153
+
154
+ Parameters
155
+ ----------
156
+ data : array_like
157
+ Data array.
158
+ prob : sequence, optional
159
+ Sequence of quantiles to compute.
160
+ axis : int, optional
161
+ Axis along which to compute the quantiles. If None, use a flattened
162
+ array.
163
+
164
+ Returns
165
+ -------
166
+ hdquantiles_sd : MaskedArray
167
+ Standard error of the Harrell-Davis quantile estimates.
168
+
169
+ See Also
170
+ --------
171
+ hdquantiles
172
+
173
+ """
174
+ def _hdsd_1D(data, prob):
175
+ "Computes the std error for 1D arrays."
176
+ xsorted = np.sort(data.compressed())
177
+ n = len(xsorted)
178
+
179
+ hdsd = np.empty(len(prob), float64)
180
+ if n < 2:
181
+ hdsd.flat = np.nan
182
+
183
+ vv = np.arange(n) / float(n-1)
184
+ betacdf = beta.cdf
185
+
186
+ for (i,p) in enumerate(prob):
187
+ _w = betacdf(vv, n*p, n*(1-p))
188
+ w = _w[1:] - _w[:-1]
189
+ # cumulative sum of weights and data points if
190
+ # ith point is left out for jackknife
191
+ mx_ = np.zeros_like(xsorted)
192
+ mx_[1:] = np.cumsum(w * xsorted[:-1])
193
+ # similar but from the right
194
+ mx_[:-1] += np.cumsum(w[::-1] * xsorted[:0:-1])[::-1]
195
+ hdsd[i] = np.sqrt(mx_.var() * (n - 1))
196
+ return hdsd
197
+
198
+ # Initialization & checks
199
+ data = ma.array(data, copy=False, dtype=float64)
200
+ p = np.atleast_1d(np.asarray(prob))
201
+ # Computes quantiles along axis (or globally)
202
+ if (axis is None):
203
+ result = _hdsd_1D(data, p)
204
+ else:
205
+ if data.ndim > 2:
206
+ raise ValueError("Array 'data' must be at most two dimensional, "
207
+ "but got data.ndim = %d" % data.ndim)
208
+ result = ma.apply_along_axis(_hdsd_1D, axis, data, p)
209
+
210
+ return ma.fix_invalid(result, copy=False).ravel()
211
+
212
+
213
+ def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True),
214
+ alpha=0.05, axis=None):
215
+ """
216
+ Selected confidence interval of the trimmed mean along the given axis.
217
+
218
+ Parameters
219
+ ----------
220
+ data : array_like
221
+ Input data.
222
+ limits : {None, tuple}, optional
223
+ None or a two item tuple.
224
+ Tuple of the percentages to cut on each side of the array, with respect
225
+ to the number of unmasked data, as floats between 0. and 1. If ``n``
226
+ is the number of unmasked data before trimming, then
227
+ (``n * limits[0]``)th smallest data and (``n * limits[1]``)th
228
+ largest data are masked. The total number of unmasked data after
229
+ trimming is ``n * (1. - sum(limits))``.
230
+ The value of one limit can be set to None to indicate an open interval.
231
+
232
+ Defaults to (0.2, 0.2).
233
+ inclusive : (2,) tuple of boolean, optional
234
+ If relative==False, tuple indicating whether values exactly equal to
235
+ the absolute limits are allowed.
236
+ If relative==True, tuple indicating whether the number of data being
237
+ masked on each side should be rounded (True) or truncated (False).
238
+
239
+ Defaults to (True, True).
240
+ alpha : float, optional
241
+ Confidence level of the intervals.
242
+
243
+ Defaults to 0.05.
244
+ axis : int, optional
245
+ Axis along which to cut. If None, uses a flattened version of `data`.
246
+
247
+ Defaults to None.
248
+
249
+ Returns
250
+ -------
251
+ trimmed_mean_ci : (2,) ndarray
252
+ The lower and upper confidence intervals of the trimmed data.
253
+
254
+ """
255
+ data = ma.array(data, copy=False)
256
+ trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)
257
+ tmean = trimmed.mean(axis)
258
+ tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis)
259
+ df = trimmed.count(axis) - 1
260
+ tppf = t.ppf(1-alpha/2.,df)
261
+ return np.array((tmean - tppf*tstde, tmean+tppf*tstde))
262
+
263
+
264
+ def mjci(data, prob=(0.25, 0.5, 0.75), axis=None):
265
+ """
266
+ Returns the Maritz-Jarrett estimators of the standard error of selected
267
+ experimental quantiles of the data.
268
+
269
+ Parameters
270
+ ----------
271
+ data : ndarray
272
+ Data array.
273
+ prob : sequence, optional
274
+ Sequence of quantiles to compute.
275
+ axis : int or None, optional
276
+ Axis along which to compute the quantiles. If None, use a flattened
277
+ array.
278
+
279
+ """
280
+ def _mjci_1D(data, p):
281
+ data = np.sort(data.compressed())
282
+ n = data.size
283
+ prob = (np.array(p) * n + 0.5).astype(int)
284
+ betacdf = beta.cdf
285
+
286
+ mj = np.empty(len(prob), float64)
287
+ x = np.arange(1,n+1, dtype=float64) / n
288
+ y = x - 1./n
289
+ for (i,m) in enumerate(prob):
290
+ W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m)
291
+ C1 = np.dot(W,data)
292
+ C2 = np.dot(W,data**2)
293
+ mj[i] = np.sqrt(C2 - C1**2)
294
+ return mj
295
+
296
+ data = ma.array(data, copy=False)
297
+ if data.ndim > 2:
298
+ raise ValueError("Array 'data' must be at most two dimensional, "
299
+ "but got data.ndim = %d" % data.ndim)
300
+
301
+ p = np.atleast_1d(np.asarray(prob))
302
+ # Computes quantiles along axis (or globally)
303
+ if (axis is None):
304
+ return _mjci_1D(data, p)
305
+ else:
306
+ return ma.apply_along_axis(_mjci_1D, axis, data, p)
307
+
308
+
309
+ def mquantiles_cimj(data, prob=(0.25, 0.50, 0.75), alpha=0.05, axis=None):
310
+ """
311
+ Computes the alpha confidence interval for the selected quantiles of the
312
+ data, with Maritz-Jarrett estimators.
313
+
314
+ Parameters
315
+ ----------
316
+ data : ndarray
317
+ Data array.
318
+ prob : sequence, optional
319
+ Sequence of quantiles to compute.
320
+ alpha : float, optional
321
+ Confidence level of the intervals.
322
+ axis : int or None, optional
323
+ Axis along which to compute the quantiles.
324
+ If None, use a flattened array.
325
+
326
+ Returns
327
+ -------
328
+ ci_lower : ndarray
329
+ The lower boundaries of the confidence interval. Of the same length as
330
+ `prob`.
331
+ ci_upper : ndarray
332
+ The upper boundaries of the confidence interval. Of the same length as
333
+ `prob`.
334
+
335
+ """
336
+ alpha = min(alpha, 1 - alpha)
337
+ z = norm.ppf(1 - alpha/2.)
338
+ xq = mstats.mquantiles(data, prob, alphap=0, betap=0, axis=axis)
339
+ smj = mjci(data, prob, axis=axis)
340
+ return (xq - z * smj, xq + z * smj)
341
+
342
+
343
+ def median_cihs(data, alpha=0.05, axis=None):
344
+ """
345
+ Computes the alpha-level confidence interval for the median of the data.
346
+
347
+ Uses the Hettmasperger-Sheather method.
348
+
349
+ Parameters
350
+ ----------
351
+ data : array_like
352
+ Input data. Masked values are discarded. The input should be 1D only,
353
+ or `axis` should be set to None.
354
+ alpha : float, optional
355
+ Confidence level of the intervals.
356
+ axis : int or None, optional
357
+ Axis along which to compute the quantiles. If None, use a flattened
358
+ array.
359
+
360
+ Returns
361
+ -------
362
+ median_cihs
363
+ Alpha level confidence interval.
364
+
365
+ """
366
+ def _cihs_1D(data, alpha):
367
+ data = np.sort(data.compressed())
368
+ n = len(data)
369
+ alpha = min(alpha, 1-alpha)
370
+ k = int(binom._ppf(alpha/2., n, 0.5))
371
+ gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
372
+ if gk < 1-alpha:
373
+ k -= 1
374
+ gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
375
+ gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5)
376
+ I = (gk - 1 + alpha)/(gk - gkk)
377
+ lambd = (n-k) * I / float(k + (n-2*k)*I)
378
+ lims = (lambd*data[k] + (1-lambd)*data[k-1],
379
+ lambd*data[n-k-1] + (1-lambd)*data[n-k])
380
+ return lims
381
+ data = ma.array(data, copy=False)
382
+ # Computes quantiles along axis (or globally)
383
+ if (axis is None):
384
+ result = _cihs_1D(data, alpha)
385
+ else:
386
+ if data.ndim > 2:
387
+ raise ValueError("Array 'data' must be at most two dimensional, "
388
+ "but got data.ndim = %d" % data.ndim)
389
+ result = ma.apply_along_axis(_cihs_1D, axis, data, alpha)
390
+
391
+ return result
392
+
393
+
394
+ def compare_medians_ms(group_1, group_2, axis=None):
395
+ """
396
+ Compares the medians from two independent groups along the given axis.
397
+
398
+ The comparison is performed using the McKean-Schrader estimate of the
399
+ standard error of the medians.
400
+
401
+ Parameters
402
+ ----------
403
+ group_1 : array_like
404
+ First dataset. Has to be of size >=7.
405
+ group_2 : array_like
406
+ Second dataset. Has to be of size >=7.
407
+ axis : int, optional
408
+ Axis along which the medians are estimated. If None, the arrays are
409
+ flattened. If `axis` is not None, then `group_1` and `group_2`
410
+ should have the same shape.
411
+
412
+ Returns
413
+ -------
414
+ compare_medians_ms : {float, ndarray}
415
+ If `axis` is None, then returns a float, otherwise returns a 1-D
416
+ ndarray of floats with a length equal to the length of `group_1`
417
+ along `axis`.
418
+
419
+ Examples
420
+ --------
421
+
422
+ >>> from scipy import stats
423
+ >>> a = [1, 2, 3, 4, 5, 6, 7]
424
+ >>> b = [8, 9, 10, 11, 12, 13, 14]
425
+ >>> stats.mstats.compare_medians_ms(a, b, axis=None)
426
+ 1.0693225866553746e-05
427
+
428
+ The function is vectorized to compute along a given axis.
429
+
430
+ >>> import numpy as np
431
+ >>> rng = np.random.default_rng()
432
+ >>> x = rng.random(size=(3, 7))
433
+ >>> y = rng.random(size=(3, 8))
434
+ >>> stats.mstats.compare_medians_ms(x, y, axis=1)
435
+ array([0.36908985, 0.36092538, 0.2765313 ])
436
+
437
+ References
438
+ ----------
439
+ .. [1] McKean, Joseph W., and Ronald M. Schrader. "A comparison of methods
440
+ for studentizing the sample median." Communications in
441
+ Statistics-Simulation and Computation 13.6 (1984): 751-773.
442
+
443
+ """
444
+ (med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis))
445
+ (std_1, std_2) = (mstats.stde_median(group_1, axis=axis),
446
+ mstats.stde_median(group_2, axis=axis))
447
+ W = np.abs(med_1 - med_2) / ma.sqrt(std_1**2 + std_2**2)
448
+ return 1 - norm.cdf(W)
449
+
450
+
451
+ def idealfourths(data, axis=None):
452
+ """
453
+ Returns an estimate of the lower and upper quartiles.
454
+
455
+ Uses the ideal fourths algorithm.
456
+
457
+ Parameters
458
+ ----------
459
+ data : array_like
460
+ Input array.
461
+ axis : int, optional
462
+ Axis along which the quartiles are estimated. If None, the arrays are
463
+ flattened.
464
+
465
+ Returns
466
+ -------
467
+ idealfourths : {list of floats, masked array}
468
+ Returns the two internal values that divide `data` into four parts
469
+ using the ideal fourths algorithm either along the flattened array
470
+ (if `axis` is None) or along `axis` of `data`.
471
+
472
+ """
473
+ def _idf(data):
474
+ x = data.compressed()
475
+ n = len(x)
476
+ if n < 3:
477
+ return [np.nan,np.nan]
478
+ (j,h) = divmod(n/4. + 5/12.,1)
479
+ j = int(j)
480
+ qlo = (1-h)*x[j-1] + h*x[j]
481
+ k = n - j
482
+ qup = (1-h)*x[k] + h*x[k-1]
483
+ return [qlo, qup]
484
+ data = ma.sort(data, axis=axis).view(MaskedArray)
485
+ if (axis is None):
486
+ return _idf(data)
487
+ else:
488
+ return ma.apply_along_axis(_idf, axis, data)
489
+
490
+
491
+ def rsh(data, points=None):
492
+ """
493
+ Evaluates Rosenblatt's shifted histogram estimators for each data point.
494
+
495
+ Rosenblatt's estimator is a centered finite-difference approximation to the
496
+ derivative of the empirical cumulative distribution function.
497
+
498
+ Parameters
499
+ ----------
500
+ data : sequence
501
+ Input data, should be 1-D. Masked values are ignored.
502
+ points : sequence or None, optional
503
+ Sequence of points where to evaluate Rosenblatt shifted histogram.
504
+ If None, use the data.
505
+
506
+ """
507
+ data = ma.array(data, copy=False)
508
+ if points is None:
509
+ points = data
510
+ else:
511
+ points = np.atleast_1d(np.asarray(points))
512
+
513
+ if data.ndim != 1:
514
+ raise AttributeError("The input array should be 1D only !")
515
+
516
+ n = data.count()
517
+ r = idealfourths(data, axis=None)
518
+ h = 1.2 * (r[-1]-r[0]) / n**(1./5)
519
+ nhi = (data[:,None] <= points[None,:] + h).sum(0)
520
+ nlo = (data[:,None] < points[None,:] - h).sum(0)
521
+ return (nhi-nlo) / (2.*n*h)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_multicomp.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from collections.abc import Sequence
3
+ from dataclasses import dataclass, field
4
+ from typing import TYPE_CHECKING, Literal
5
+
6
+ import numpy as np
7
+
8
+ from scipy import stats
9
+ from scipy.optimize import minimize_scalar
10
+ from scipy.stats._common import ConfidenceInterval
11
+ from scipy.stats._qmc import check_random_state
12
+ from scipy.stats._stats_py import _var
13
+ from scipy._lib._util import _transition_to_rng, DecimalNumber, SeedType
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ import numpy.typing as npt
18
+
19
+
20
+ __all__ = [
21
+ 'dunnett'
22
+ ]
23
+
24
+
25
+ @dataclass
26
+ class DunnettResult:
27
+ """Result object returned by `scipy.stats.dunnett`.
28
+
29
+ Attributes
30
+ ----------
31
+ statistic : float ndarray
32
+ The computed statistic of the test for each comparison. The element
33
+ at index ``i`` is the statistic for the comparison between
34
+ groups ``i`` and the control.
35
+ pvalue : float ndarray
36
+ The computed p-value of the test for each comparison. The element
37
+ at index ``i`` is the p-value for the comparison between
38
+ group ``i`` and the control.
39
+ """
40
+ statistic: np.ndarray
41
+ pvalue: np.ndarray
42
+ _alternative: Literal['two-sided', 'less', 'greater'] = field(repr=False)
43
+ _rho: np.ndarray = field(repr=False)
44
+ _df: int = field(repr=False)
45
+ _std: float = field(repr=False)
46
+ _mean_samples: np.ndarray = field(repr=False)
47
+ _mean_control: np.ndarray = field(repr=False)
48
+ _n_samples: np.ndarray = field(repr=False)
49
+ _n_control: int = field(repr=False)
50
+ _rng: SeedType = field(repr=False)
51
+ _ci: ConfidenceInterval | None = field(default=None, repr=False)
52
+ _ci_cl: DecimalNumber | None = field(default=None, repr=False)
53
+
54
+ def __str__(self):
55
+ # Note: `__str__` prints the confidence intervals from the most
56
+ # recent call to `confidence_interval`. If it has not been called,
57
+ # it will be called with the default CL of .95.
58
+ if self._ci is None:
59
+ self.confidence_interval(confidence_level=.95)
60
+ s = (
61
+ "Dunnett's test"
62
+ f" ({self._ci_cl*100:.1f}% Confidence Interval)\n"
63
+ "Comparison Statistic p-value Lower CI Upper CI\n"
64
+ )
65
+ for i in range(self.pvalue.size):
66
+ s += (f" (Sample {i} - Control) {self.statistic[i]:>10.3f}"
67
+ f"{self.pvalue[i]:>10.3f}"
68
+ f"{self._ci.low[i]:>10.3f}"
69
+ f"{self._ci.high[i]:>10.3f}\n")
70
+
71
+ return s
72
+
73
+ def _allowance(
74
+ self, confidence_level: DecimalNumber = 0.95, tol: DecimalNumber = 1e-3
75
+ ) -> float:
76
+ """Allowance.
77
+
78
+ It is the quantity to add/subtract from the observed difference
79
+ between the means of observed groups and the mean of the control
80
+ group. The result gives confidence limits.
81
+
82
+ Parameters
83
+ ----------
84
+ confidence_level : float, optional
85
+ Confidence level for the computed confidence interval.
86
+ Default is .95.
87
+ tol : float, optional
88
+ A tolerance for numerical optimization: the allowance will produce
89
+ a confidence within ``10*tol*(1 - confidence_level)`` of the
90
+ specified level, or a warning will be emitted. Tight tolerances
91
+ may be impractical due to noisy evaluation of the objective.
92
+ Default is 1e-3.
93
+
94
+ Returns
95
+ -------
96
+ allowance : float
97
+ Allowance around the mean.
98
+ """
99
+ alpha = 1 - confidence_level
100
+
101
+ def pvalue_from_stat(statistic):
102
+ statistic = np.array(statistic)
103
+ sf = _pvalue_dunnett(
104
+ rho=self._rho, df=self._df,
105
+ statistic=statistic, alternative=self._alternative,
106
+ rng=self._rng
107
+ )
108
+ return abs(sf - alpha)/alpha
109
+
110
+ # Evaluation of `pvalue_from_stat` is noisy due to the use of RQMC to
111
+ # evaluate `multivariate_t.cdf`. `minimize_scalar` is not designed
112
+ # to tolerate a noisy objective function and may fail to find the
113
+ # minimum accurately. We mitigate this possibility with the validation
114
+ # step below, but implementation of a noise-tolerant root finder or
115
+ # minimizer would be a welcome enhancement. See gh-18150.
116
+ res = minimize_scalar(pvalue_from_stat, method='brent', tol=tol)
117
+ critical_value = res.x
118
+
119
+ # validation
120
+ # tol*10 because tol=1e-3 means we tolerate a 1% change at most
121
+ if res.success is False or res.fun >= tol*10:
122
+ warnings.warn(
123
+ "Computation of the confidence interval did not converge to "
124
+ "the desired level. The confidence level corresponding with "
125
+ f"the returned interval is approximately {alpha*(1+res.fun)}.",
126
+ stacklevel=3
127
+ )
128
+
129
+ # From [1] p. 1101 between (1) and (3)
130
+ allowance = critical_value*self._std*np.sqrt(
131
+ 1/self._n_samples + 1/self._n_control
132
+ )
133
+ return abs(allowance)
134
+
135
+ def confidence_interval(
136
+ self, confidence_level: DecimalNumber = 0.95
137
+ ) -> ConfidenceInterval:
138
+ """Compute the confidence interval for the specified confidence level.
139
+
140
+ Parameters
141
+ ----------
142
+ confidence_level : float, optional
143
+ Confidence level for the computed confidence interval.
144
+ Default is .95.
145
+
146
+ Returns
147
+ -------
148
+ ci : ``ConfidenceInterval`` object
149
+ The object has attributes ``low`` and ``high`` that hold the
150
+ lower and upper bounds of the confidence intervals for each
151
+ comparison. The high and low values are accessible for each
152
+ comparison at index ``i`` for each group ``i``.
153
+
154
+ """
155
+ # check to see if the supplied confidence level matches that of the
156
+ # previously computed CI.
157
+ if (self._ci is not None) and (confidence_level == self._ci_cl):
158
+ return self._ci
159
+
160
+ if not (0 < confidence_level < 1):
161
+ raise ValueError("Confidence level must be between 0 and 1.")
162
+
163
+ allowance = self._allowance(confidence_level=confidence_level)
164
+ diff_means = self._mean_samples - self._mean_control
165
+
166
+ low = diff_means-allowance
167
+ high = diff_means+allowance
168
+
169
+ if self._alternative == 'greater':
170
+ high = [np.inf] * len(diff_means)
171
+ elif self._alternative == 'less':
172
+ low = [-np.inf] * len(diff_means)
173
+
174
+ self._ci_cl = confidence_level
175
+ self._ci = ConfidenceInterval(
176
+ low=low,
177
+ high=high
178
+ )
179
+ return self._ci
180
+
181
+
182
+ @_transition_to_rng('random_state', replace_doc=False)
183
+ def dunnett(
184
+ *samples: "npt.ArrayLike", # noqa: D417
185
+ control: "npt.ArrayLike",
186
+ alternative: Literal['two-sided', 'less', 'greater'] = "two-sided",
187
+ rng: SeedType = None
188
+ ) -> DunnettResult:
189
+ """Dunnett's test: multiple comparisons of means against a control group.
190
+
191
+ This is an implementation of Dunnett's original, single-step test as
192
+ described in [1]_.
193
+
194
+ Parameters
195
+ ----------
196
+ sample1, sample2, ... : 1D array_like
197
+ The sample measurements for each experimental group.
198
+ control : 1D array_like
199
+ The sample measurements for the control group.
200
+ alternative : {'two-sided', 'less', 'greater'}, optional
201
+ Defines the alternative hypothesis.
202
+
203
+ The null hypothesis is that the means of the distributions underlying
204
+ the samples and control are equal. The following alternative
205
+ hypotheses are available (default is 'two-sided'):
206
+
207
+ * 'two-sided': the means of the distributions underlying the samples
208
+ and control are unequal.
209
+ * 'less': the means of the distributions underlying the samples
210
+ are less than the mean of the distribution underlying the control.
211
+ * 'greater': the means of the distributions underlying the
212
+ samples are greater than the mean of the distribution underlying
213
+ the control.
214
+ rng : `numpy.random.Generator`, optional
215
+ Pseudorandom number generator state. When `rng` is None, a new
216
+ `numpy.random.Generator` is created using entropy from the
217
+ operating system. Types other than `numpy.random.Generator` are
218
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
219
+
220
+ .. versionchanged:: 1.15.0
221
+
222
+ As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
223
+ transition from use of `numpy.random.RandomState` to
224
+ `numpy.random.Generator`, this keyword was changed from `random_state` to
225
+ `rng`. For an interim period, both keywords will continue to work, although
226
+ only one may be specified at a time. After the interim period, function
227
+ calls using the `random_state` keyword will emit warnings. Following a
228
+ deprecation period, the `random_state` keyword will be removed.
229
+
230
+ Returns
231
+ -------
232
+ res : `~scipy.stats._result_classes.DunnettResult`
233
+ An object containing attributes:
234
+
235
+ statistic : float ndarray
236
+ The computed statistic of the test for each comparison. The element
237
+ at index ``i`` is the statistic for the comparison between
238
+ groups ``i`` and the control.
239
+ pvalue : float ndarray
240
+ The computed p-value of the test for each comparison. The element
241
+ at index ``i`` is the p-value for the comparison between
242
+ group ``i`` and the control.
243
+
244
+ And the following method:
245
+
246
+ confidence_interval(confidence_level=0.95) :
247
+ Compute the difference in means of the groups
248
+ with the control +- the allowance.
249
+
250
+ See Also
251
+ --------
252
+ tukey_hsd : performs pairwise comparison of means.
253
+ :ref:`hypothesis_dunnett` : Extended example
254
+
255
+ Notes
256
+ -----
257
+ Like the independent-sample t-test, Dunnett's test [1]_ is used to make
258
+ inferences about the means of distributions from which samples were drawn.
259
+ However, when multiple t-tests are performed at a fixed significance level,
260
+ the "family-wise error rate" - the probability of incorrectly rejecting the
261
+ null hypothesis in at least one test - will exceed the significance level.
262
+ Dunnett's test is designed to perform multiple comparisons while
263
+ controlling the family-wise error rate.
264
+
265
+ Dunnett's test compares the means of multiple experimental groups
266
+ against a single control group. Tukey's Honestly Significant Difference Test
267
+ is another multiple-comparison test that controls the family-wise error
268
+ rate, but `tukey_hsd` performs *all* pairwise comparisons between groups.
269
+ When pairwise comparisons between experimental groups are not needed,
270
+ Dunnett's test is preferable due to its higher power.
271
+
272
+ The use of this test relies on several assumptions.
273
+
274
+ 1. The observations are independent within and among groups.
275
+ 2. The observations within each group are normally distributed.
276
+ 3. The distributions from which the samples are drawn have the same finite
277
+ variance.
278
+
279
+ References
280
+ ----------
281
+ .. [1] Dunnett, Charles W. (1955) "A Multiple Comparison Procedure for
282
+ Comparing Several Treatments with a Control." Journal of the American
283
+ Statistical Association, 50:272, 1096-1121,
284
+ :doi:`10.1080/01621459.1955.10501294`
285
+ .. [2] Thomson, M. L., & Short, M. D. (1969). Mucociliary function in
286
+ health, chronic obstructive airway disease, and asbestosis. Journal
287
+ of applied physiology, 26(5), 535-539.
288
+ :doi:`10.1152/jappl.1969.26.5.535`
289
+
290
+ Examples
291
+ --------
292
+ We'll use data from [2]_, Table 1. The null hypothesis is that the means of
293
+ the distributions underlying the samples and control are equal.
294
+
295
+ First, we test that the means of the distributions underlying the samples
296
+ and control are unequal (``alternative='two-sided'``, the default).
297
+
298
+ >>> import numpy as np
299
+ >>> from scipy.stats import dunnett
300
+ >>> samples = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]
301
+ >>> control = [2.9, 3.0, 2.5, 2.6, 3.2]
302
+ >>> res = dunnett(*samples, control=control)
303
+ >>> res.statistic
304
+ array([ 0.90874545, -0.05007117])
305
+ >>> res.pvalue
306
+ array([0.58325114, 0.99819341])
307
+
308
+ Now, we test that the means of the distributions underlying the samples are
309
+ greater than the mean of the distribution underlying the control.
310
+
311
+ >>> res = dunnett(*samples, control=control, alternative='greater')
312
+ >>> res.statistic
313
+ array([ 0.90874545, -0.05007117])
314
+ >>> res.pvalue
315
+ array([0.30230596, 0.69115597])
316
+
317
+ For a more detailed example, see :ref:`hypothesis_dunnett`.
318
+ """
319
+ samples_, control_, rng = _iv_dunnett(
320
+ samples=samples, control=control,
321
+ alternative=alternative, rng=rng
322
+ )
323
+
324
+ rho, df, n_group, n_samples, n_control = _params_dunnett(
325
+ samples=samples_, control=control_
326
+ )
327
+
328
+ statistic, std, mean_control, mean_samples = _statistic_dunnett(
329
+ samples_, control_, df, n_samples, n_control
330
+ )
331
+
332
+ pvalue = _pvalue_dunnett(
333
+ rho=rho, df=df, statistic=statistic, alternative=alternative, rng=rng
334
+ )
335
+
336
+ return DunnettResult(
337
+ statistic=statistic, pvalue=pvalue,
338
+ _alternative=alternative,
339
+ _rho=rho, _df=df, _std=std,
340
+ _mean_samples=mean_samples,
341
+ _mean_control=mean_control,
342
+ _n_samples=n_samples,
343
+ _n_control=n_control,
344
+ _rng=rng
345
+ )
346
+
347
+
348
+ def _iv_dunnett(
349
+ samples: Sequence["npt.ArrayLike"],
350
+ control: "npt.ArrayLike",
351
+ alternative: Literal['two-sided', 'less', 'greater'],
352
+ rng: SeedType
353
+ ) -> tuple[list[np.ndarray], np.ndarray, SeedType]:
354
+ """Input validation for Dunnett's test."""
355
+ rng = check_random_state(rng)
356
+
357
+ if alternative not in {'two-sided', 'less', 'greater'}:
358
+ raise ValueError(
359
+ "alternative must be 'less', 'greater' or 'two-sided'"
360
+ )
361
+
362
+ ndim_msg = "Control and samples groups must be 1D arrays"
363
+ n_obs_msg = "Control and samples groups must have at least 1 observation"
364
+
365
+ control = np.asarray(control)
366
+ samples_ = [np.asarray(sample) for sample in samples]
367
+
368
+ # samples checks
369
+ samples_control: list[np.ndarray] = samples_ + [control]
370
+ for sample in samples_control:
371
+ if sample.ndim > 1:
372
+ raise ValueError(ndim_msg)
373
+
374
+ if sample.size < 1:
375
+ raise ValueError(n_obs_msg)
376
+
377
+ return samples_, control, rng
378
+
379
+
380
+ def _params_dunnett(
381
+ samples: list[np.ndarray], control: np.ndarray
382
+ ) -> tuple[np.ndarray, int, int, np.ndarray, int]:
383
+ """Specific parameters for Dunnett's test.
384
+
385
+ Degree of freedom is the number of observations minus the number of groups
386
+ including the control.
387
+ """
388
+ n_samples = np.array([sample.size for sample in samples])
389
+
390
+ # From [1] p. 1100 d.f. = (sum N)-(p+1)
391
+ n_sample = n_samples.sum()
392
+ n_control = control.size
393
+ n = n_sample + n_control
394
+ n_groups = len(samples)
395
+ df = n - n_groups - 1
396
+
397
+ # From [1] p. 1103 rho_ij = 1/sqrt((N0/Ni+1)(N0/Nj+1))
398
+ rho = n_control/n_samples + 1
399
+ rho = 1/np.sqrt(rho[:, None] * rho[None, :])
400
+ np.fill_diagonal(rho, 1)
401
+
402
+ return rho, df, n_groups, n_samples, n_control
403
+
404
+
405
+ def _statistic_dunnett(
406
+ samples: list[np.ndarray], control: np.ndarray, df: int,
407
+ n_samples: np.ndarray, n_control: int
408
+ ) -> tuple[np.ndarray, float, np.ndarray, np.ndarray]:
409
+ """Statistic of Dunnett's test.
410
+
411
+ Computation based on the original single-step test from [1].
412
+ """
413
+ mean_control = np.mean(control)
414
+ mean_samples = np.array([np.mean(sample) for sample in samples])
415
+ all_samples = [control] + samples
416
+ all_means = np.concatenate([[mean_control], mean_samples])
417
+
418
+ # Variance estimate s^2 from [1] Eq. 1
419
+ s2 = np.sum([_var(sample, mean=mean)*sample.size
420
+ for sample, mean in zip(all_samples, all_means)]) / df
421
+ std = np.sqrt(s2)
422
+
423
+ # z score inferred from [1] unlabeled equation after Eq. 1
424
+ z = (mean_samples - mean_control) / np.sqrt(1/n_samples + 1/n_control)
425
+
426
+ return z / std, std, mean_control, mean_samples
427
+
428
+
429
+ def _pvalue_dunnett(
430
+ rho: np.ndarray, df: int, statistic: np.ndarray,
431
+ alternative: Literal['two-sided', 'less', 'greater'],
432
+ rng: SeedType = None
433
+ ) -> np.ndarray:
434
+ """pvalue from the multivariate t-distribution.
435
+
436
+ Critical values come from the multivariate student-t distribution.
437
+ """
438
+ statistic = statistic.reshape(-1, 1)
439
+
440
+ mvt = stats.multivariate_t(shape=rho, df=df, seed=rng)
441
+ if alternative == "two-sided":
442
+ statistic = abs(statistic)
443
+ pvalue = 1 - mvt.cdf(statistic, lower_limit=-statistic)
444
+ elif alternative == "greater":
445
+ pvalue = 1 - mvt.cdf(statistic, lower_limit=-np.inf)
446
+ else:
447
+ pvalue = 1 - mvt.cdf(np.inf, lower_limit=statistic)
448
+
449
+ return np.atleast_1d(pvalue)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_multivariate.py ADDED
The diff for this file is too large to render. See raw diff
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_mvn.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (85 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_new_distributions.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import numpy as np
4
+ from numpy import inf
5
+
6
+ from scipy import special
7
+ from scipy.stats._distribution_infrastructure import (
8
+ ContinuousDistribution, _RealDomain, _RealParameter, _Parameterization,
9
+ _combine_docs)
10
+
11
+ __all__ = ['Normal', 'Uniform']
12
+
13
+
14
+ class Normal(ContinuousDistribution):
15
+ r"""Normal distribution with prescribed mean and standard deviation.
16
+
17
+ The probability density function of the normal distribution is:
18
+
19
+ .. math::
20
+
21
+ f(x) = \frac{1}{\sigma \sqrt{2 \pi}} \exp {
22
+ \left( -\frac{1}{2}\left( \frac{x - \mu}{\sigma} \right)^2 \right)}
23
+
24
+ """
25
+ # `ShiftedScaledDistribution` allows this to be generated automatically from
26
+ # an instance of `StandardNormal`, but the normal distribution is so frequently
27
+ # used that it's worth a bit of code duplication to get better performance.
28
+ _mu_domain = _RealDomain(endpoints=(-inf, inf))
29
+ _sigma_domain = _RealDomain(endpoints=(0, inf))
30
+ _x_support = _RealDomain(endpoints=(-inf, inf))
31
+
32
+ _mu_param = _RealParameter('mu', symbol=r'\mu', domain=_mu_domain,
33
+ typical=(-1, 1))
34
+ _sigma_param = _RealParameter('sigma', symbol=r'\sigma', domain=_sigma_domain,
35
+ typical=(0.5, 1.5))
36
+ _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1))
37
+
38
+ _parameterizations = [_Parameterization(_mu_param, _sigma_param)]
39
+
40
+ _variable = _x_param
41
+ _normalization = 1/np.sqrt(2*np.pi)
42
+ _log_normalization = np.log(2*np.pi)/2
43
+
44
+ def __new__(cls, mu=None, sigma=None, **kwargs):
45
+ if mu is None and sigma is None:
46
+ return super().__new__(StandardNormal)
47
+ return super().__new__(cls)
48
+
49
+ def __init__(self, *, mu=0., sigma=1., **kwargs):
50
+ super().__init__(mu=mu, sigma=sigma, **kwargs)
51
+
52
+ def _logpdf_formula(self, x, *, mu, sigma, **kwargs):
53
+ return StandardNormal._logpdf_formula(self, (x - mu)/sigma) - np.log(sigma)
54
+
55
+ def _pdf_formula(self, x, *, mu, sigma, **kwargs):
56
+ return StandardNormal._pdf_formula(self, (x - mu)/sigma) / sigma
57
+
58
+ def _logcdf_formula(self, x, *, mu, sigma, **kwargs):
59
+ return StandardNormal._logcdf_formula(self, (x - mu)/sigma)
60
+
61
+ def _cdf_formula(self, x, *, mu, sigma, **kwargs):
62
+ return StandardNormal._cdf_formula(self, (x - mu)/sigma)
63
+
64
+ def _logccdf_formula(self, x, *, mu, sigma, **kwargs):
65
+ return StandardNormal._logccdf_formula(self, (x - mu)/sigma)
66
+
67
+ def _ccdf_formula(self, x, *, mu, sigma, **kwargs):
68
+ return StandardNormal._ccdf_formula(self, (x - mu)/sigma)
69
+
70
+ def _icdf_formula(self, x, *, mu, sigma, **kwargs):
71
+ return StandardNormal._icdf_formula(self, x) * sigma + mu
72
+
73
+ def _ilogcdf_formula(self, x, *, mu, sigma, **kwargs):
74
+ return StandardNormal._ilogcdf_formula(self, x) * sigma + mu
75
+
76
+ def _iccdf_formula(self, x, *, mu, sigma, **kwargs):
77
+ return StandardNormal._iccdf_formula(self, x) * sigma + mu
78
+
79
+ def _ilogccdf_formula(self, x, *, mu, sigma, **kwargs):
80
+ return StandardNormal._ilogccdf_formula(self, x) * sigma + mu
81
+
82
+ def _entropy_formula(self, *, mu, sigma, **kwargs):
83
+ return StandardNormal._entropy_formula(self) + np.log(abs(sigma))
84
+
85
+ def _logentropy_formula(self, *, mu, sigma, **kwargs):
86
+ lH0 = StandardNormal._logentropy_formula(self)
87
+ with np.errstate(divide='ignore'):
88
+ # sigma = 1 -> log(sigma) = 0 -> log(log(sigma)) = -inf
89
+ # Silence the unnecessary runtime warning
90
+ lls = np.log(np.log(abs(sigma))+0j)
91
+ return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0)
92
+
93
+ def _median_formula(self, *, mu, sigma, **kwargs):
94
+ return mu
95
+
96
+ def _mode_formula(self, *, mu, sigma, **kwargs):
97
+ return mu
98
+
99
+ def _moment_raw_formula(self, order, *, mu, sigma, **kwargs):
100
+ if order == 0:
101
+ return np.ones_like(mu)
102
+ elif order == 1:
103
+ return mu
104
+ else:
105
+ return None
106
+ _moment_raw_formula.orders = [0, 1] # type: ignore[attr-defined]
107
+
108
+ def _moment_central_formula(self, order, *, mu, sigma, **kwargs):
109
+ if order == 0:
110
+ return np.ones_like(mu)
111
+ elif order % 2:
112
+ return np.zeros_like(mu)
113
+ else:
114
+ # exact is faster (and obviously more accurate) for reasonable orders
115
+ return sigma**order * special.factorial2(int(order) - 1, exact=True)
116
+
117
+ def _sample_formula(self, sample_shape, full_shape, rng, *, mu, sigma, **kwargs):
118
+ return rng.normal(loc=mu, scale=sigma, size=full_shape)[()]
119
+
120
+
121
+ def _log_diff(log_p, log_q):
122
+ return special.logsumexp([log_p, log_q+np.pi*1j], axis=0)
123
+
124
+
125
+ class StandardNormal(Normal):
126
+ r"""Standard normal distribution.
127
+
128
+ The probability density function of the standard normal distribution is:
129
+
130
+ .. math::
131
+
132
+ f(x) = \frac{1}{\sqrt{2 \pi}} \exp \left( -\frac{1}{2} x^2 \right)
133
+
134
+ """
135
+ _x_support = _RealDomain(endpoints=(-inf, inf))
136
+ _x_param = _RealParameter('x', domain=_x_support, typical=(-5, 5))
137
+ _variable = _x_param
138
+ _parameterizations = []
139
+ _normalization = 1/np.sqrt(2*np.pi)
140
+ _log_normalization = np.log(2*np.pi)/2
141
+ mu = np.float64(0.)
142
+ sigma = np.float64(1.)
143
+
144
+ def __init__(self, **kwargs):
145
+ ContinuousDistribution.__init__(self, **kwargs)
146
+
147
+ def _logpdf_formula(self, x, **kwargs):
148
+ return -(self._log_normalization + x**2/2)
149
+
150
+ def _pdf_formula(self, x, **kwargs):
151
+ return self._normalization * np.exp(-x**2/2)
152
+
153
+ def _logcdf_formula(self, x, **kwargs):
154
+ return special.log_ndtr(x)
155
+
156
+ def _cdf_formula(self, x, **kwargs):
157
+ return special.ndtr(x)
158
+
159
+ def _logccdf_formula(self, x, **kwargs):
160
+ return special.log_ndtr(-x)
161
+
162
+ def _ccdf_formula(self, x, **kwargs):
163
+ return special.ndtr(-x)
164
+
165
+ def _icdf_formula(self, x, **kwargs):
166
+ return special.ndtri(x)
167
+
168
+ def _ilogcdf_formula(self, x, **kwargs):
169
+ return special.ndtri_exp(x)
170
+
171
+ def _iccdf_formula(self, x, **kwargs):
172
+ return -special.ndtri(x)
173
+
174
+ def _ilogccdf_formula(self, x, **kwargs):
175
+ return -special.ndtri_exp(x)
176
+
177
+ def _entropy_formula(self, **kwargs):
178
+ return (1 + np.log(2*np.pi))/2
179
+
180
+ def _logentropy_formula(self, **kwargs):
181
+ return np.log1p(np.log(2*np.pi)) - np.log(2)
182
+
183
+ def _median_formula(self, **kwargs):
184
+ return 0
185
+
186
+ def _mode_formula(self, **kwargs):
187
+ return 0
188
+
189
+ def _moment_raw_formula(self, order, **kwargs):
190
+ raw_moments = {0: 1, 1: 0, 2: 1, 3: 0, 4: 3, 5: 0}
191
+ return raw_moments.get(order, None)
192
+
193
+ def _moment_central_formula(self, order, **kwargs):
194
+ return self._moment_raw_formula(order, **kwargs)
195
+
196
+ def _moment_standardized_formula(self, order, **kwargs):
197
+ return self._moment_raw_formula(order, **kwargs)
198
+
199
+ def _sample_formula(self, sample_shape, full_shape, rng, **kwargs):
200
+ return rng.normal(size=full_shape)[()]
201
+
202
+
203
+ # currently for testing only
204
+ class _LogUniform(ContinuousDistribution):
205
+ r"""Log-uniform distribution.
206
+
207
+ The probability density function of the log-uniform distribution is:
208
+
209
+ .. math::
210
+
211
+ f(x; a, b) = \frac{1}
212
+ {x (\log(b) - \log(a))}
213
+
214
+ If :math:`\log(X)` is a random variable that follows a uniform distribution
215
+ between :math:`\log(a)` and :math:`\log(b)`, then :math:`X` is log-uniformly
216
+ distributed with shape parameters :math:`a` and :math:`b`.
217
+
218
+ """
219
+
220
+ _a_domain = _RealDomain(endpoints=(0, inf))
221
+ _b_domain = _RealDomain(endpoints=('a', inf))
222
+ _log_a_domain = _RealDomain(endpoints=(-inf, inf))
223
+ _log_b_domain = _RealDomain(endpoints=('log_a', inf))
224
+ _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
225
+
226
+ _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
227
+ _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
228
+ _log_a_param = _RealParameter('log_a', symbol=r'\log(a)',
229
+ domain=_log_a_domain, typical=(-3, -0.1))
230
+ _log_b_param = _RealParameter('log_b', symbol=r'\log(b)',
231
+ domain=_log_b_domain, typical=(0.1, 3))
232
+ _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
233
+
234
+ _b_domain.define_parameters(_a_param)
235
+ _log_b_domain.define_parameters(_log_a_param)
236
+ _x_support.define_parameters(_a_param, _b_param)
237
+
238
+ _parameterizations = [_Parameterization(_log_a_param, _log_b_param),
239
+ _Parameterization(_a_param, _b_param)]
240
+ _variable = _x_param
241
+
242
+ def __init__(self, *, a=None, b=None, log_a=None, log_b=None, **kwargs):
243
+ super().__init__(a=a, b=b, log_a=log_a, log_b=log_b, **kwargs)
244
+
245
+ def _process_parameters(self, a=None, b=None, log_a=None, log_b=None, **kwargs):
246
+ a = np.exp(log_a) if a is None else a
247
+ b = np.exp(log_b) if b is None else b
248
+ log_a = np.log(a) if log_a is None else log_a
249
+ log_b = np.log(b) if log_b is None else log_b
250
+ kwargs.update(dict(a=a, b=b, log_a=log_a, log_b=log_b))
251
+ return kwargs
252
+
253
+ # def _logpdf_formula(self, x, *, log_a, log_b, **kwargs):
254
+ # return -np.log(x) - np.log(log_b - log_a)
255
+
256
+ def _pdf_formula(self, x, *, log_a, log_b, **kwargs):
257
+ return ((log_b - log_a)*x)**-1
258
+
259
+ # def _cdf_formula(self, x, *, log_a, log_b, **kwargs):
260
+ # return (np.log(x) - log_a)/(log_b - log_a)
261
+
262
+ def _moment_raw_formula(self, order, log_a, log_b, **kwargs):
263
+ if order == 0:
264
+ return self._one
265
+ t1 = self._one / (log_b - log_a) / order
266
+ t2 = np.real(np.exp(_log_diff(order * log_b, order * log_a)))
267
+ return t1 * t2
268
+
269
+
270
+ class Uniform(ContinuousDistribution):
271
+ r"""Uniform distribution.
272
+
273
+ The probability density function of the uniform distribution is:
274
+
275
+ .. math::
276
+
277
+ f(x; a, b) = \frac{1}
278
+ {b - a}
279
+
280
+ """
281
+
282
+ _a_domain = _RealDomain(endpoints=(-inf, inf))
283
+ _b_domain = _RealDomain(endpoints=('a', inf))
284
+ _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
285
+
286
+ _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
287
+ _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
288
+ _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
289
+
290
+ _b_domain.define_parameters(_a_param)
291
+ _x_support.define_parameters(_a_param, _b_param)
292
+
293
+ _parameterizations = [_Parameterization(_a_param, _b_param)]
294
+ _variable = _x_param
295
+
296
+ def __init__(self, *, a=None, b=None, **kwargs):
297
+ super().__init__(a=a, b=b, **kwargs)
298
+
299
+ def _process_parameters(self, a=None, b=None, ab=None, **kwargs):
300
+ ab = b - a
301
+ kwargs.update(dict(a=a, b=b, ab=ab))
302
+ return kwargs
303
+
304
+ def _logpdf_formula(self, x, *, ab, **kwargs):
305
+ return np.where(np.isnan(x), np.nan, -np.log(ab))
306
+
307
+ def _pdf_formula(self, x, *, ab, **kwargs):
308
+ return np.where(np.isnan(x), np.nan, 1/ab)
309
+
310
+ def _logcdf_formula(self, x, *, a, ab, **kwargs):
311
+ with np.errstate(divide='ignore'):
312
+ return np.log(x - a) - np.log(ab)
313
+
314
+ def _cdf_formula(self, x, *, a, ab, **kwargs):
315
+ return (x - a) / ab
316
+
317
+ def _logccdf_formula(self, x, *, b, ab, **kwargs):
318
+ with np.errstate(divide='ignore'):
319
+ return np.log(b - x) - np.log(ab)
320
+
321
+ def _ccdf_formula(self, x, *, b, ab, **kwargs):
322
+ return (b - x) / ab
323
+
324
+ def _icdf_formula(self, p, *, a, ab, **kwargs):
325
+ return a + ab*p
326
+
327
+ def _iccdf_formula(self, p, *, b, ab, **kwargs):
328
+ return b - ab*p
329
+
330
+ def _entropy_formula(self, *, ab, **kwargs):
331
+ return np.log(ab)
332
+
333
+ def _mode_formula(self, *, a, b, ab, **kwargs):
334
+ return a + 0.5*ab
335
+
336
+ def _median_formula(self, *, a, b, ab, **kwargs):
337
+ return a + 0.5*ab
338
+
339
+ def _moment_raw_formula(self, order, a, b, ab, **kwargs):
340
+ np1 = order + 1
341
+ return (b**np1 - a**np1) / (np1 * ab)
342
+
343
+ def _moment_central_formula(self, order, ab, **kwargs):
344
+ return ab**2/12 if order == 2 else None
345
+
346
+ _moment_central_formula.orders = [2] # type: ignore[attr-defined]
347
+
348
+ def _sample_formula(self, sample_shape, full_shape, rng, a, b, ab, **kwargs):
349
+ try:
350
+ return rng.uniform(a, b, size=full_shape)[()]
351
+ except OverflowError: # happens when there are NaNs
352
+ return rng.uniform(0, 1, size=full_shape)*ab + a
353
+
354
+
355
+ class _Gamma(ContinuousDistribution):
356
+ # Gamma distribution for testing only
357
+ _a_domain = _RealDomain(endpoints=(0, inf))
358
+ _x_support = _RealDomain(endpoints=(0, inf), inclusive=(False, False))
359
+
360
+ _a_param = _RealParameter('a', domain=_a_domain, typical=(0.1, 10))
361
+ _x_param = _RealParameter('x', domain=_x_support, typical=(0.1, 10))
362
+
363
+ _parameterizations = [_Parameterization(_a_param)]
364
+ _variable = _x_param
365
+
366
+ def _pdf_formula(self, x, *, a, **kwargs):
367
+ return x ** (a - 1) * np.exp(-x) / special.gamma(a)
368
+
369
+
370
+ # Distribution classes need only define the summary and beginning of the extended
371
+ # summary portion of the class documentation. All other documentation, including
372
+ # examples, is generated automatically.
373
+ _module = sys.modules[__name__].__dict__
374
+ for dist_name in __all__:
375
+ _module[dist_name].__doc__ = _combine_docs(_module[dist_name])
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_odds_ratio.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from scipy.special import ndtri
4
+ from scipy.optimize import brentq
5
+ from ._discrete_distns import nchypergeom_fisher
6
+ from ._common import ConfidenceInterval
7
+
8
+
9
+ def _sample_odds_ratio(table):
10
+ """
11
+ Given a table [[a, b], [c, d]], compute a*d/(b*c).
12
+
13
+ Return nan if the numerator and denominator are 0.
14
+ Return inf if just the denominator is 0.
15
+ """
16
+ # table must be a 2x2 numpy array.
17
+ if table[1, 0] > 0 and table[0, 1] > 0:
18
+ oddsratio = table[0, 0] * table[1, 1] / (table[1, 0] * table[0, 1])
19
+ elif table[0, 0] == 0 or table[1, 1] == 0:
20
+ oddsratio = np.nan
21
+ else:
22
+ oddsratio = np.inf
23
+ return oddsratio
24
+
25
+
26
+ def _solve(func):
27
+ """
28
+ Solve func(nc) = 0. func must be an increasing function.
29
+ """
30
+ # We could just as well call the variable `x` instead of `nc`, but we
31
+ # always call this function with functions for which nc (the noncentrality
32
+ # parameter) is the variable for which we are solving.
33
+ nc = 1.0
34
+ value = func(nc)
35
+ if value == 0:
36
+ return nc
37
+
38
+ # Multiplicative factor by which to increase or decrease nc when
39
+ # searching for a bracketing interval.
40
+ factor = 2.0
41
+ # Find a bracketing interval.
42
+ if value > 0:
43
+ nc /= factor
44
+ while func(nc) > 0:
45
+ nc /= factor
46
+ lo = nc
47
+ hi = factor*nc
48
+ else:
49
+ nc *= factor
50
+ while func(nc) < 0:
51
+ nc *= factor
52
+ lo = nc/factor
53
+ hi = nc
54
+
55
+ # lo and hi bracket the solution for nc.
56
+ nc = brentq(func, lo, hi, xtol=1e-13)
57
+ return nc
58
+
59
+
60
+ def _nc_hypergeom_mean_inverse(x, M, n, N):
61
+ """
62
+ For the given noncentral hypergeometric parameters x, M, n,and N
63
+ (table[0,0], total, row 0 sum and column 0 sum, resp., of a 2x2
64
+ contingency table), find the noncentrality parameter of Fisher's
65
+ noncentral hypergeometric distribution whose mean is x.
66
+ """
67
+ nc = _solve(lambda nc: nchypergeom_fisher.mean(M, n, N, nc) - x)
68
+ return nc
69
+
70
+
71
+ def _hypergeom_params_from_table(table):
72
+ # The notation M, n and N is consistent with stats.hypergeom and
73
+ # stats.nchypergeom_fisher.
74
+ x = table[0, 0]
75
+ M = table.sum()
76
+ n = table[0].sum()
77
+ N = table[:, 0].sum()
78
+ return x, M, n, N
79
+
80
+
81
+ def _ci_upper(table, alpha):
82
+ """
83
+ Compute the upper end of the confidence interval.
84
+ """
85
+ if _sample_odds_ratio(table) == np.inf:
86
+ return np.inf
87
+
88
+ x, M, n, N = _hypergeom_params_from_table(table)
89
+
90
+ # nchypergeom_fisher.cdf is a decreasing function of nc, so we negate
91
+ # it in the lambda expression.
92
+ nc = _solve(lambda nc: -nchypergeom_fisher.cdf(x, M, n, N, nc) + alpha)
93
+ return nc
94
+
95
+
96
+ def _ci_lower(table, alpha):
97
+ """
98
+ Compute the lower end of the confidence interval.
99
+ """
100
+ if _sample_odds_ratio(table) == 0:
101
+ return 0
102
+
103
+ x, M, n, N = _hypergeom_params_from_table(table)
104
+
105
+ nc = _solve(lambda nc: nchypergeom_fisher.sf(x - 1, M, n, N, nc) - alpha)
106
+ return nc
107
+
108
+
109
+ def _conditional_oddsratio(table):
110
+ """
111
+ Conditional MLE of the odds ratio for the 2x2 contingency table.
112
+ """
113
+ x, M, n, N = _hypergeom_params_from_table(table)
114
+ # Get the bounds of the support. The support of the noncentral
115
+ # hypergeometric distribution with parameters M, n, and N is the same
116
+ # for all values of the noncentrality parameter, so we can use 1 here.
117
+ lo, hi = nchypergeom_fisher.support(M, n, N, 1)
118
+
119
+ # Check if x is at one of the extremes of the support. If so, we know
120
+ # the odds ratio is either 0 or inf.
121
+ if x == lo:
122
+ # x is at the low end of the support.
123
+ return 0
124
+ if x == hi:
125
+ # x is at the high end of the support.
126
+ return np.inf
127
+
128
+ nc = _nc_hypergeom_mean_inverse(x, M, n, N)
129
+ return nc
130
+
131
+
132
+ def _conditional_oddsratio_ci(table, confidence_level=0.95,
133
+ alternative='two-sided'):
134
+ """
135
+ Conditional exact confidence interval for the odds ratio.
136
+ """
137
+ if alternative == 'two-sided':
138
+ alpha = 0.5*(1 - confidence_level)
139
+ lower = _ci_lower(table, alpha)
140
+ upper = _ci_upper(table, alpha)
141
+ elif alternative == 'less':
142
+ lower = 0.0
143
+ upper = _ci_upper(table, 1 - confidence_level)
144
+ else:
145
+ # alternative == 'greater'
146
+ lower = _ci_lower(table, 1 - confidence_level)
147
+ upper = np.inf
148
+
149
+ return lower, upper
150
+
151
+
152
+ def _sample_odds_ratio_ci(table, confidence_level=0.95,
153
+ alternative='two-sided'):
154
+ oddsratio = _sample_odds_ratio(table)
155
+ log_or = np.log(oddsratio)
156
+ se = np.sqrt((1/table).sum())
157
+ if alternative == 'less':
158
+ z = ndtri(confidence_level)
159
+ loglow = -np.inf
160
+ loghigh = log_or + z*se
161
+ elif alternative == 'greater':
162
+ z = ndtri(confidence_level)
163
+ loglow = log_or - z*se
164
+ loghigh = np.inf
165
+ else:
166
+ # alternative is 'two-sided'
167
+ z = ndtri(0.5*confidence_level + 0.5)
168
+ loglow = log_or - z*se
169
+ loghigh = log_or + z*se
170
+
171
+ return np.exp(loglow), np.exp(loghigh)
172
+
173
+
174
+ class OddsRatioResult:
175
+ """
176
+ Result of `scipy.stats.contingency.odds_ratio`. See the
177
+ docstring for `odds_ratio` for more details.
178
+
179
+ Attributes
180
+ ----------
181
+ statistic : float
182
+ The computed odds ratio.
183
+
184
+ * If `kind` is ``'sample'``, this is sample (or unconditional)
185
+ estimate, given by
186
+ ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
187
+ * If `kind` is ``'conditional'``, this is the conditional
188
+ maximum likelihood estimate for the odds ratio. It is
189
+ the noncentrality parameter of Fisher's noncentral
190
+ hypergeometric distribution with the same hypergeometric
191
+ parameters as `table` and whose mean is ``table[0, 0]``.
192
+
193
+ Methods
194
+ -------
195
+ confidence_interval :
196
+ Confidence interval for the odds ratio.
197
+ """
198
+
199
+ def __init__(self, _table, _kind, statistic):
200
+ # for now, no need to make _table and _kind public, since this sort of
201
+ # information is returned in very few `scipy.stats` results
202
+ self._table = _table
203
+ self._kind = _kind
204
+ self.statistic = statistic
205
+
206
+ def __repr__(self):
207
+ return f"OddsRatioResult(statistic={self.statistic})"
208
+
209
+ def confidence_interval(self, confidence_level=0.95,
210
+ alternative='two-sided'):
211
+ """
212
+ Confidence interval for the odds ratio.
213
+
214
+ Parameters
215
+ ----------
216
+ confidence_level: float
217
+ Desired confidence level for the confidence interval.
218
+ The value must be given as a fraction between 0 and 1.
219
+ Default is 0.95 (meaning 95%).
220
+
221
+ alternative : {'two-sided', 'less', 'greater'}, optional
222
+ The alternative hypothesis of the hypothesis test to which the
223
+ confidence interval corresponds. That is, suppose the null
224
+ hypothesis is that the true odds ratio equals ``OR`` and the
225
+ confidence interval is ``(low, high)``. Then the following options
226
+ for `alternative` are available (default is 'two-sided'):
227
+
228
+ * 'two-sided': the true odds ratio is not equal to ``OR``. There
229
+ is evidence against the null hypothesis at the chosen
230
+ `confidence_level` if ``high < OR`` or ``low > OR``.
231
+ * 'less': the true odds ratio is less than ``OR``. The ``low`` end
232
+ of the confidence interval is 0, and there is evidence against
233
+ the null hypothesis at the chosen `confidence_level` if
234
+ ``high < OR``.
235
+ * 'greater': the true odds ratio is greater than ``OR``. The
236
+ ``high`` end of the confidence interval is ``np.inf``, and there
237
+ is evidence against the null hypothesis at the chosen
238
+ `confidence_level` if ``low > OR``.
239
+
240
+ Returns
241
+ -------
242
+ ci : ``ConfidenceInterval`` instance
243
+ The confidence interval, represented as an object with
244
+ attributes ``low`` and ``high``.
245
+
246
+ Notes
247
+ -----
248
+ When `kind` is ``'conditional'``, the limits of the confidence
249
+ interval are the conditional "exact confidence limits" as described
250
+ by Fisher [1]_. The conditional odds ratio and confidence interval are
251
+ also discussed in Section 4.1.2 of the text by Sahai and Khurshid [2]_.
252
+
253
+ When `kind` is ``'sample'``, the confidence interval is computed
254
+ under the assumption that the logarithm of the odds ratio is normally
255
+ distributed with standard error given by::
256
+
257
+ se = sqrt(1/a + 1/b + 1/c + 1/d)
258
+
259
+ where ``a``, ``b``, ``c`` and ``d`` are the elements of the
260
+ contingency table. (See, for example, [2]_, section 3.1.3.2,
261
+ or [3]_, section 2.3.3).
262
+
263
+ References
264
+ ----------
265
+ .. [1] R. A. Fisher (1935), The logic of inductive inference,
266
+ Journal of the Royal Statistical Society, Vol. 98, No. 1,
267
+ pp. 39-82.
268
+ .. [2] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
269
+ Methods, Techniques, and Applications, CRC Press LLC, Boca
270
+ Raton, Florida.
271
+ .. [3] Alan Agresti, An Introduction to Categorical Data Analysis
272
+ (second edition), Wiley, Hoboken, NJ, USA (2007).
273
+ """
274
+ if alternative not in ['two-sided', 'less', 'greater']:
275
+ raise ValueError("`alternative` must be 'two-sided', 'less' or "
276
+ "'greater'.")
277
+
278
+ if confidence_level < 0 or confidence_level > 1:
279
+ raise ValueError('confidence_level must be between 0 and 1')
280
+
281
+ if self._kind == 'conditional':
282
+ ci = self._conditional_odds_ratio_ci(confidence_level, alternative)
283
+ else:
284
+ ci = self._sample_odds_ratio_ci(confidence_level, alternative)
285
+ return ci
286
+
287
+ def _conditional_odds_ratio_ci(self, confidence_level=0.95,
288
+ alternative='two-sided'):
289
+ """
290
+ Confidence interval for the conditional odds ratio.
291
+ """
292
+
293
+ table = self._table
294
+ if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
295
+ # If both values in a row or column are zero, the p-value is 1,
296
+ # the odds ratio is NaN and the confidence interval is (0, inf).
297
+ ci = (0, np.inf)
298
+ else:
299
+ ci = _conditional_oddsratio_ci(table,
300
+ confidence_level=confidence_level,
301
+ alternative=alternative)
302
+ return ConfidenceInterval(low=ci[0], high=ci[1])
303
+
304
+ def _sample_odds_ratio_ci(self, confidence_level=0.95,
305
+ alternative='two-sided'):
306
+ """
307
+ Confidence interval for the sample odds ratio.
308
+ """
309
+ if confidence_level < 0 or confidence_level > 1:
310
+ raise ValueError('confidence_level must be between 0 and 1')
311
+
312
+ table = self._table
313
+ if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
314
+ # If both values in a row or column are zero, the p-value is 1,
315
+ # the odds ratio is NaN and the confidence interval is (0, inf).
316
+ ci = (0, np.inf)
317
+ else:
318
+ ci = _sample_odds_ratio_ci(table,
319
+ confidence_level=confidence_level,
320
+ alternative=alternative)
321
+ return ConfidenceInterval(low=ci[0], high=ci[1])
322
+
323
+
324
+ def odds_ratio(table, *, kind='conditional'):
325
+ r"""
326
+ Compute the odds ratio for a 2x2 contingency table.
327
+
328
+ Parameters
329
+ ----------
330
+ table : array_like of ints
331
+ A 2x2 contingency table. Elements must be non-negative integers.
332
+ kind : str, optional
333
+ Which kind of odds ratio to compute, either the sample
334
+ odds ratio (``kind='sample'``) or the conditional odds ratio
335
+ (``kind='conditional'``). Default is ``'conditional'``.
336
+
337
+ Returns
338
+ -------
339
+ result : `~scipy.stats._result_classes.OddsRatioResult` instance
340
+ The returned object has two computed attributes:
341
+
342
+ statistic : float
343
+ * If `kind` is ``'sample'``, this is sample (or unconditional)
344
+ estimate, given by
345
+ ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
346
+ * If `kind` is ``'conditional'``, this is the conditional
347
+ maximum likelihood estimate for the odds ratio. It is
348
+ the noncentrality parameter of Fisher's noncentral
349
+ hypergeometric distribution with the same hypergeometric
350
+ parameters as `table` and whose mean is ``table[0, 0]``.
351
+
352
+ The object has the method `confidence_interval` that computes
353
+ the confidence interval of the odds ratio.
354
+
355
+ See Also
356
+ --------
357
+ scipy.stats.fisher_exact
358
+ relative_risk
359
+ :ref:`hypothesis_odds_ratio` : Extended example
360
+
361
+ Notes
362
+ -----
363
+ The conditional odds ratio was discussed by Fisher (see "Example 1"
364
+ of [1]_). Texts that cover the odds ratio include [2]_ and [3]_.
365
+
366
+ .. versionadded:: 1.10.0
367
+
368
+ References
369
+ ----------
370
+ .. [1] R. A. Fisher (1935), The logic of inductive inference,
371
+ Journal of the Royal Statistical Society, Vol. 98, No. 1,
372
+ pp. 39-82.
373
+ .. [2] Breslow NE, Day NE (1980). Statistical methods in cancer research.
374
+ Volume I - The analysis of case-control studies. IARC Sci Publ.
375
+ (32):5-338. PMID: 7216345. (See section 4.2.)
376
+ .. [3] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
377
+ Methods, Techniques, and Applications, CRC Press LLC, Boca
378
+ Raton, Florida.
379
+
380
+ Examples
381
+ --------
382
+ In epidemiology, individuals are classified as "exposed" or
383
+ "unexposed" to some factor or treatment. If the occurrence of some
384
+ illness is under study, those who have the illness are often
385
+ classified as "cases", and those without it are "noncases". The
386
+ counts of the occurrences of these classes gives a contingency
387
+ table::
388
+
389
+ exposed unexposed
390
+ cases a b
391
+ noncases c d
392
+
393
+ The sample odds ratio may be written ``(a/c) / (b/d)``. ``a/c`` can
394
+ be interpreted as the odds of a case occurring in the exposed group,
395
+ and ``b/d`` as the odds of a case occurring in the unexposed group.
396
+ The sample odds ratio is the ratio of these odds. If the odds ratio
397
+ is greater than 1, it suggests that there is a positive association
398
+ between being exposed and being a case.
399
+
400
+ Interchanging the rows or columns of the contingency table inverts
401
+ the odds ratio, so it is important to understand the meaning of labels
402
+ given to the rows and columns of the table when interpreting the
403
+ odds ratio.
404
+
405
+ Consider a hypothetical example where it is hypothesized that exposure to a
406
+ certain chemical is associated with increased occurrence of a certain
407
+ disease. Suppose we have the following table for a collection of 410 people::
408
+
409
+ exposed unexposed
410
+ cases 7 15
411
+ noncases 58 472
412
+
413
+ The question we ask is "Is exposure to the chemical associated with
414
+ increased risk of the disease?"
415
+
416
+ Compute the odds ratio:
417
+
418
+ >>> from scipy.stats.contingency import odds_ratio
419
+ >>> res = odds_ratio([[7, 15], [58, 472]])
420
+ >>> res.statistic
421
+ 3.7836687705553493
422
+
423
+ For this sample, the odds of getting the disease for those who have been
424
+ exposed to the chemical are almost 3.8 times that of those who have not been
425
+ exposed.
426
+
427
+ We can compute the 95% confidence interval for the odds ratio:
428
+
429
+ >>> res.confidence_interval(confidence_level=0.95)
430
+ ConfidenceInterval(low=1.2514829132266785, high=10.363493716701269)
431
+
432
+ The 95% confidence interval for the conditional odds ratio is approximately
433
+ (1.25, 10.4).
434
+
435
+ For a more detailed example, see :ref:`hypothesis_odds_ratio`.
436
+ """
437
+ if kind not in ['conditional', 'sample']:
438
+ raise ValueError("`kind` must be 'conditional' or 'sample'.")
439
+
440
+ c = np.asarray(table)
441
+
442
+ if c.shape != (2, 2):
443
+ raise ValueError(f"Invalid shape {c.shape}. The input `table` must be "
444
+ "of shape (2, 2).")
445
+
446
+ if not np.issubdtype(c.dtype, np.integer):
447
+ raise ValueError("`table` must be an array of integers, but got "
448
+ f"type {c.dtype}")
449
+ c = c.astype(np.int64)
450
+
451
+ if np.any(c < 0):
452
+ raise ValueError("All values in `table` must be nonnegative.")
453
+
454
+ if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
455
+ # If both values in a row or column are zero, the p-value is NaN and
456
+ # the odds ratio is NaN.
457
+ result = OddsRatioResult(_table=c, _kind=kind, statistic=np.nan)
458
+ return result
459
+
460
+ if kind == 'sample':
461
+ oddsratio = _sample_odds_ratio(c)
462
+ else: # kind is 'conditional'
463
+ oddsratio = _conditional_oddsratio(c)
464
+
465
+ result = OddsRatioResult(_table=c, _kind=kind, statistic=oddsratio)
466
+ return result
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_page_trend_test.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclass
7
+
8
+
9
+ @dataclass
10
+ class PageTrendTestResult:
11
+ statistic: float
12
+ pvalue: float
13
+ method: str
14
+
15
+
16
+ def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'):
17
+ r"""
18
+ Perform Page's Test, a measure of trend in observations between treatments.
19
+
20
+ Page's Test (also known as Page's :math:`L` test) is useful when:
21
+
22
+ * there are :math:`n \geq 3` treatments,
23
+ * :math:`m \geq 2` subjects are observed for each treatment, and
24
+ * the observations are hypothesized to have a particular order.
25
+
26
+ Specifically, the test considers the null hypothesis that
27
+
28
+ .. math::
29
+
30
+ m_1 = m_2 = m_3 \cdots = m_n,
31
+
32
+ where :math:`m_j` is the mean of the observed quantity under treatment
33
+ :math:`j`, against the alternative hypothesis that
34
+
35
+ .. math::
36
+
37
+ m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n,
38
+
39
+ where at least one inequality is strict.
40
+
41
+ As noted by [4]_, Page's :math:`L` test has greater statistical power than
42
+ the Friedman test against the alternative that there is a difference in
43
+ trend, as Friedman's test only considers a difference in the means of the
44
+ observations without considering their order. Whereas Spearman :math:`\rho`
45
+ considers the correlation between the ranked observations of two variables
46
+ (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it
47
+ carries), Page's :math:`L` is concerned with a trend in an observation
48
+ (e.g. the airspeed velocity of a swallow) across several distinct
49
+ treatments (e.g. carrying each of five coconuts of different weight) even
50
+ as the observation is repeated with multiple subjects (e.g. one European
51
+ swallow and one African swallow).
52
+
53
+ Parameters
54
+ ----------
55
+ data : array-like
56
+ A :math:`m \times n` array; the element in row :math:`i` and
57
+ column :math:`j` is the observation corresponding with subject
58
+ :math:`i` and treatment :math:`j`. By default, the columns are
59
+ assumed to be arranged in order of increasing predicted mean.
60
+
61
+ ranked : boolean, optional
62
+ By default, `data` is assumed to be observations rather than ranks;
63
+ it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If
64
+ `data` is provided in the form of ranks, pass argument ``True``.
65
+
66
+ predicted_ranks : array-like, optional
67
+ The predicted ranks of the column means. If not specified,
68
+ the columns are assumed to be arranged in order of increasing
69
+ predicted mean, so the default `predicted_ranks` are
70
+ :math:`[1, 2, \dots, n-1, n]`.
71
+
72
+ method : {'auto', 'asymptotic', 'exact'}, optional
73
+ Selects the method used to calculate the *p*-value. The following
74
+ options are available.
75
+
76
+ * 'auto': selects between 'exact' and 'asymptotic' to
77
+ achieve reasonably accurate results in reasonable time (default)
78
+ * 'asymptotic': compares the standardized test statistic against
79
+ the normal distribution
80
+ * 'exact': computes the exact *p*-value by comparing the observed
81
+ :math:`L` statistic against those realized by all possible
82
+ permutations of ranks (under the null hypothesis that each
83
+ permutation is equally likely)
84
+
85
+ Returns
86
+ -------
87
+ res : PageTrendTestResult
88
+ An object containing attributes:
89
+
90
+ statistic : float
91
+ Page's :math:`L` test statistic.
92
+ pvalue : float
93
+ The associated *p*-value
94
+ method : {'asymptotic', 'exact'}
95
+ The method used to compute the *p*-value
96
+
97
+ See Also
98
+ --------
99
+ rankdata, friedmanchisquare, spearmanr
100
+
101
+ Notes
102
+ -----
103
+ As noted in [1]_, "the :math:`n` 'treatments' could just as well represent
104
+ :math:`n` objects or events or performances or persons or trials ranked."
105
+ Similarly, the :math:`m` 'subjects' could equally stand for :math:`m`
106
+ "groupings by ability or some other control variable, or judges doing
107
+ the ranking, or random replications of some other sort."
108
+
109
+ The procedure for calculating the :math:`L` statistic, adapted from
110
+ [1]_, is:
111
+
112
+ 1. "Predetermine with careful logic the appropriate hypotheses
113
+ concerning the predicted ordering of the experimental results.
114
+ If no reasonable basis for ordering any treatments is known, the
115
+ :math:`L` test is not appropriate."
116
+ 2. "As in other experiments, determine at what level of confidence
117
+ you will reject the null hypothesis that there is no agreement of
118
+ experimental results with the monotonic hypothesis."
119
+ 3. "Cast the experimental material into a two-way table of :math:`n`
120
+ columns (treatments, objects ranked, conditions) and :math:`m`
121
+ rows (subjects, replication groups, levels of control variables)."
122
+ 4. "When experimental observations are recorded, rank them across each
123
+ row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``.
124
+ 5. "Add the ranks in each column", e.g.
125
+ ``colsums = np.sum(ranks, axis=0)``.
126
+ 6. "Multiply each sum of ranks by the predicted rank for that same
127
+ column", e.g. ``products = predicted_ranks * colsums``.
128
+ 7. "Sum all such products", e.g. ``L = products.sum()``.
129
+
130
+ [1]_ continues by suggesting use of the standardized statistic
131
+
132
+ .. math::
133
+
134
+ \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)}
135
+
136
+ "which is distributed approximately as chi-square with 1 degree of
137
+ freedom. The ordinary use of :math:`\chi^2` tables would be
138
+ equivalent to a two-sided test of agreement. If a one-sided test
139
+ is desired, *as will almost always be the case*, the probability
140
+ discovered in the chi-square table should be *halved*."
141
+
142
+ However, this standardized statistic does not distinguish between the
143
+ observed values being well correlated with the predicted ranks and being
144
+ _anti_-correlated with the predicted ranks. Instead, we follow [2]_
145
+ and calculate the standardized statistic
146
+
147
+ .. math::
148
+
149
+ \Lambda = \frac{L - E_0}{\sqrt{V_0}},
150
+
151
+ where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and
152
+ :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically
153
+ normal under the null hypothesis".
154
+
155
+ The *p*-value for ``method='exact'`` is generated by comparing the observed
156
+ value of :math:`L` against the :math:`L` values generated for all
157
+ :math:`(n!)^m` possible permutations of ranks. The calculation is performed
158
+ using the recursive method of [5].
159
+
160
+ The *p*-values are not adjusted for the possibility of ties. When
161
+ ties are present, the reported ``'exact'`` *p*-values may be somewhat
162
+ larger (i.e. more conservative) than the true *p*-value [2]_. The
163
+ ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less
164
+ conservative) than the ``'exact'`` *p*-values.
165
+
166
+ References
167
+ ----------
168
+ .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments:
169
+ a significant test for linear ranks", *Journal of the American
170
+ Statistical Association* 58(301), p. 216--230, 1963.
171
+
172
+ .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational
173
+ approach*, CRC Press, p. 150--152, 2012.
174
+
175
+ .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext -
176
+ Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php,
177
+ Accessed July 12, 2020.
178
+
179
+ .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation,
180
+ https://en.wikipedia.org/wiki/Page%27s_trend_test,
181
+ Accessed July 12, 2020.
182
+
183
+ .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in
184
+ the two-way layout", *Communications in Statistics - Simulation and
185
+ Computation*, 6(1), p. 49--61, 1977.
186
+
187
+ Examples
188
+ --------
189
+ We use the example from [3]_: 10 students are asked to rate three
190
+ teaching methods - tutorial, lecture, and seminar - on a scale of 1-5,
191
+ with 1 being the lowest and 5 being the highest. We have decided that
192
+ a confidence level of 99% is required to reject the null hypothesis in
193
+ favor of our alternative: that the seminar will have the highest ratings
194
+ and the tutorial will have the lowest. Initially, the data have been
195
+ tabulated with each row representing an individual student's ratings of
196
+ the three methods in the following order: tutorial, lecture, seminar.
197
+
198
+ >>> table = [[3, 4, 3],
199
+ ... [2, 2, 4],
200
+ ... [3, 3, 5],
201
+ ... [1, 3, 2],
202
+ ... [2, 3, 2],
203
+ ... [2, 4, 5],
204
+ ... [1, 2, 4],
205
+ ... [3, 4, 4],
206
+ ... [2, 4, 5],
207
+ ... [1, 3, 4]]
208
+
209
+ Because the tutorial is hypothesized to have the lowest ratings, the
210
+ column corresponding with tutorial rankings should be first; the seminar
211
+ is hypothesized to have the highest ratings, so its column should be last.
212
+ Since the columns are already arranged in this order of increasing
213
+ predicted mean, we can pass the table directly into `page_trend_test`.
214
+
215
+ >>> from scipy.stats import page_trend_test
216
+ >>> res = page_trend_test(table)
217
+ >>> res
218
+ PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
219
+ method='exact')
220
+
221
+ This *p*-value indicates that there is a 0.1819% chance that
222
+ the :math:`L` statistic would reach such an extreme value under the null
223
+ hypothesis. Because 0.1819% is less than 1%, we have evidence to reject
224
+ the null hypothesis in favor of our alternative at a 99% confidence level.
225
+
226
+ The value of the :math:`L` statistic is 133.5. To check this manually,
227
+ we rank the data such that high scores correspond with high ranks, settling
228
+ ties with an average rank:
229
+
230
+ >>> from scipy.stats import rankdata
231
+ >>> ranks = rankdata(table, axis=1)
232
+ >>> ranks
233
+ array([[1.5, 3. , 1.5],
234
+ [1.5, 1.5, 3. ],
235
+ [1.5, 1.5, 3. ],
236
+ [1. , 3. , 2. ],
237
+ [1.5, 3. , 1.5],
238
+ [1. , 2. , 3. ],
239
+ [1. , 2. , 3. ],
240
+ [1. , 2.5, 2.5],
241
+ [1. , 2. , 3. ],
242
+ [1. , 2. , 3. ]])
243
+
244
+ We add the ranks within each column, multiply the sums by the
245
+ predicted ranks, and sum the products.
246
+
247
+ >>> import numpy as np
248
+ >>> m, n = ranks.shape
249
+ >>> predicted_ranks = np.arange(1, n+1)
250
+ >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum()
251
+ >>> res.statistic == L
252
+ True
253
+
254
+ As presented in [3]_, the asymptotic approximation of the *p*-value is the
255
+ survival function of the normal distribution evaluated at the standardized
256
+ test statistic:
257
+
258
+ >>> from scipy.stats import norm
259
+ >>> E0 = (m*n*(n+1)**2)/4
260
+ >>> V0 = (m*n**2*(n+1)*(n**2-1))/144
261
+ >>> Lambda = (L-E0)/np.sqrt(V0)
262
+ >>> p = norm.sf(Lambda)
263
+ >>> p
264
+ 0.0012693433690751756
265
+
266
+ This does not precisely match the *p*-value reported by `page_trend_test`
267
+ above. The asymptotic distribution is not very accurate, nor conservative,
268
+ for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to
269
+ use ``method='exact'`` based on the dimensions of the table and the
270
+ recommendations in Page's original paper [1]_. To override
271
+ `page_trend_test`'s choice, provide the `method` argument.
272
+
273
+ >>> res = page_trend_test(table, method="asymptotic")
274
+ >>> res
275
+ PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756,
276
+ method='asymptotic')
277
+
278
+ If the data are already ranked, we can pass in the ``ranks`` instead of
279
+ the ``table`` to save computation time.
280
+
281
+ >>> res = page_trend_test(ranks, # ranks of data
282
+ ... ranked=True, # data is already ranked
283
+ ... )
284
+ >>> res
285
+ PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
286
+ method='exact')
287
+
288
+ Suppose the raw data had been tabulated in an order different from the
289
+ order of predicted means, say lecture, seminar, tutorial.
290
+
291
+ >>> table = np.asarray(table)[:, [1, 2, 0]]
292
+
293
+ Since the arrangement of this table is not consistent with the assumed
294
+ ordering, we can either rearrange the table or provide the
295
+ `predicted_ranks`. Remembering that the lecture is predicted
296
+ to have the middle rank, the seminar the highest, and tutorial the lowest,
297
+ we pass:
298
+
299
+ >>> res = page_trend_test(table, # data as originally tabulated
300
+ ... predicted_ranks=[2, 3, 1], # our predicted order
301
+ ... )
302
+ >>> res
303
+ PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
304
+ method='exact')
305
+
306
+ """
307
+
308
+ # Possible values of the method parameter and the corresponding function
309
+ # used to evaluate the p value
310
+ methods = {"asymptotic": _l_p_asymptotic,
311
+ "exact": _l_p_exact,
312
+ "auto": None}
313
+ if method not in methods:
314
+ raise ValueError(f"`method` must be in {set(methods)}")
315
+
316
+ ranks = np.asarray(data)
317
+ if ranks.ndim != 2: # TODO: relax this to accept 3d arrays?
318
+ raise ValueError("`data` must be a 2d array.")
319
+
320
+ m, n = ranks.shape
321
+ if m < 2 or n < 3:
322
+ raise ValueError("Page's L is only appropriate for data with two "
323
+ "or more rows and three or more columns.")
324
+
325
+ if np.any(np.isnan(data)):
326
+ raise ValueError("`data` contains NaNs, which cannot be ranked "
327
+ "meaningfully")
328
+
329
+ # ensure NumPy array and rank the data if it's not already ranked
330
+ if ranked:
331
+ # Only a basic check on whether data is ranked. Checking that the data
332
+ # is properly ranked could take as much time as ranking it.
333
+ if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]):
334
+ raise ValueError("`data` is not properly ranked. Rank the data or "
335
+ "pass `ranked=False`.")
336
+ else:
337
+ ranks = scipy.stats.rankdata(data, axis=-1)
338
+
339
+ # generate predicted ranks if not provided, ensure valid NumPy array
340
+ if predicted_ranks is None:
341
+ predicted_ranks = np.arange(1, n+1)
342
+ else:
343
+ predicted_ranks = np.asarray(predicted_ranks)
344
+ if (predicted_ranks.ndim < 1 or
345
+ (set(predicted_ranks) != set(range(1, n+1)) or
346
+ len(predicted_ranks) != n)):
347
+ raise ValueError(f"`predicted_ranks` must include each integer "
348
+ f"from 1 to {n} (the number of columns in "
349
+ f"`data`) exactly once.")
350
+
351
+ if not isinstance(ranked, bool):
352
+ raise TypeError("`ranked` must be boolean.")
353
+
354
+ # Calculate the L statistic
355
+ L = _l_vectorized(ranks, predicted_ranks)
356
+
357
+ # Calculate the p-value
358
+ if method == "auto":
359
+ method = _choose_method(ranks)
360
+ p_fun = methods[method] # get the function corresponding with the method
361
+ p = p_fun(L, m, n)
362
+
363
+ page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method)
364
+ return page_result
365
+
366
+
367
+ def _choose_method(ranks):
368
+ '''Choose method for computing p-value automatically'''
369
+ m, n = ranks.shape
370
+ if n > 8 or (m > 12 and n > 3) or m > 20: # as in [1], [4]
371
+ method = "asymptotic"
372
+ else:
373
+ method = "exact"
374
+ return method
375
+
376
+
377
+ def _l_vectorized(ranks, predicted_ranks):
378
+ '''Calculate's Page's L statistic for each page of a 3d array'''
379
+ colsums = ranks.sum(axis=-2, keepdims=True)
380
+ products = predicted_ranks * colsums
381
+ Ls = products.sum(axis=-1)
382
+ Ls = Ls[0] if Ls.size == 1 else Ls.ravel()
383
+ return Ls
384
+
385
+
386
+ def _l_p_asymptotic(L, m, n):
387
+ '''Calculate the p-value of Page's L from the asymptotic distribution'''
388
+ # Using [1] as a reference, the asymptotic p-value would be calculated as:
389
+ # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1))
390
+ # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2
391
+ # but this is insensitive to the direction of the hypothesized ranking
392
+
393
+ # See [2] page 151
394
+ E0 = (m*n*(n+1)**2)/4
395
+ V0 = (m*n**2*(n+1)*(n**2-1))/144
396
+ Lambda = (L-E0)/np.sqrt(V0)
397
+ # This is a one-sided "greater" test - calculate the probability that the
398
+ # L statistic under H0 would be greater than the observed L statistic
399
+ p = norm.sf(Lambda)
400
+ return p
401
+
402
+
403
+ def _l_p_exact(L, m, n):
404
+ '''Calculate the p-value of Page's L exactly'''
405
+ # [1] uses m, n; [5] uses n, k.
406
+ # Switch convention here because exact calculation code references [5].
407
+ L, n, k = int(L), int(m), int(n)
408
+ _pagel_state.set_k(k)
409
+ return _pagel_state.sf(L, n)
410
+
411
+
412
+ class _PageL:
413
+ '''Maintains state between `page_trend_test` executions'''
414
+
415
+ def __init__(self):
416
+ '''Lightweight initialization'''
417
+ self.all_pmfs = {}
418
+
419
+ def set_k(self, k):
420
+ '''Calculate lower and upper limits of L for single row'''
421
+ self.k = k
422
+ # See [5] top of page 52
423
+ self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6
424
+
425
+ def sf(self, l, n):
426
+ '''Survival function of Page's L statistic'''
427
+ ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)]
428
+ return np.sum(ps)
429
+
430
+ def p_l_k_1(self):
431
+ '''Relative frequency of each L value over all possible single rows'''
432
+
433
+ # See [5] Equation (6)
434
+ ranks = range(1, self.k+1)
435
+ # generate all possible rows of length k
436
+ rank_perms = np.array(list(permutations(ranks)))
437
+ # compute Page's L for all possible rows
438
+ Ls = (ranks*rank_perms).sum(axis=1)
439
+ # count occurrences of each L value
440
+ counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0]
441
+ # factorial(k) is number of possible permutations
442
+ return counts/math.factorial(self.k)
443
+
444
+ def pmf(self, l, n):
445
+ '''Recursive function to evaluate p(l, k, n); see [5] Equation 1'''
446
+
447
+ if n not in self.all_pmfs:
448
+ self.all_pmfs[n] = {}
449
+ if self.k not in self.all_pmfs[n]:
450
+ self.all_pmfs[n][self.k] = {}
451
+
452
+ # Cache results to avoid repeating calculation. Initially this was
453
+ # written with lru_cache, but this seems faster? Also, we could add
454
+ # an option to save this for future lookup.
455
+ if l in self.all_pmfs[n][self.k]:
456
+ return self.all_pmfs[n][self.k][l]
457
+
458
+ if n == 1:
459
+ ps = self.p_l_k_1() # [5] Equation 6
460
+ ls = range(self.a, self.b+1)
461
+ # not fast, but we'll only be here once
462
+ self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)}
463
+ return self.all_pmfs[n][self.k][l]
464
+
465
+ p = 0
466
+ low = max(l-(n-1)*self.b, self.a) # [5] Equation 2
467
+ high = min(l-(n-1)*self.a, self.b)
468
+
469
+ # [5] Equation 1
470
+ for t in range(low, high+1):
471
+ p1 = self.pmf(l-t, n-1)
472
+ p2 = self.pmf(t, 1)
473
+ p += p1*p2
474
+ self.all_pmfs[n][self.k][l] = p
475
+ return p
476
+
477
+
478
+ # Maintain state for faster repeat calls to page_trend_test w/ method='exact'
479
+ _pagel_state = _PageL()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_probability_distribution.py ADDED
@@ -0,0 +1,1742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Temporary file separated from _distribution_infrastructure.py
2
+ # to simplify the diff during PR review.
3
+ from abc import ABC, abstractmethod
4
+
5
+ class _ProbabilityDistribution(ABC):
6
+ @abstractmethod
7
+ def support(self):
8
+ r"""Support of the random variable
9
+
10
+ The support of a random variable is set of all possible outcomes;
11
+ i.e., the subset of the domain of argument :math:`x` for which
12
+ the probability density function :math:`f(x)` is nonzero.
13
+
14
+ This function returns lower and upper bounds of the support.
15
+
16
+ Returns
17
+ -------
18
+ out : tuple of Array
19
+ The lower and upper bounds of the support.
20
+
21
+ See Also
22
+ --------
23
+ pdf
24
+
25
+ References
26
+ ----------
27
+ .. [1] Support (mathematics), *Wikipedia*,
28
+ https://en.wikipedia.org/wiki/Support_(mathematics)
29
+
30
+ Notes
31
+ -----
32
+ Suppose a continuous probability distribution has support ``(l, r)``.
33
+ The following table summarizes the value returned by methods
34
+ of ``ContinuousDistribution`` for arguments outside the support.
35
+
36
+ +----------------+---------------------+---------------------+
37
+ | Method | Value for ``x < l`` | Value for ``x > r`` |
38
+ +================+=====================+=====================+
39
+ | ``pdf(x)`` | 0 | 0 |
40
+ +----------------+---------------------+---------------------+
41
+ | ``logpdf(x)`` | -inf | -inf |
42
+ +----------------+---------------------+---------------------+
43
+ | ``cdf(x)`` | 0 | 1 |
44
+ +----------------+---------------------+---------------------+
45
+ | ``logcdf(x)`` | -inf | 0 |
46
+ +----------------+---------------------+---------------------+
47
+ | ``ccdf(x)`` | 1 | 0 |
48
+ +----------------+---------------------+---------------------+
49
+ | ``logccdf(x)`` | 0 | -inf |
50
+ +----------------+---------------------+---------------------+
51
+
52
+ For the ``cdf`` and related methods, the inequality need not be
53
+ strict; i.e. the tabulated value is returned when the method is
54
+ evaluated *at* the corresponding boundary.
55
+
56
+ The following table summarizes the value returned by the inverse
57
+ methods of ``ContinuousDistribution`` for arguments at the boundaries
58
+ of the domain ``0`` to ``1``.
59
+
60
+ +-------------+-----------+-----------+
61
+ | Method | ``x = 0`` | ``x = 1`` |
62
+ +=============+===========+===========+
63
+ | ``icdf(x)`` | ``l`` | ``r`` |
64
+ +-------------+-----------+-----------+
65
+ | ``icdf(x)`` | ``r`` | ``l`` |
66
+ +-------------+-----------+-----------+
67
+
68
+ For the inverse log-functions, the same values are returned for
69
+ for ``x = log(0)`` and ``x = log(1)``. All inverse functions return
70
+ ``nan`` when evaluated at an argument outside the domain ``0`` to ``1``.
71
+
72
+ Examples
73
+ --------
74
+ Instantiate a distribution with the desired parameters:
75
+
76
+ >>> from scipy import stats
77
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
78
+
79
+ Retrieve the support of the distribution:
80
+
81
+ >>> X.support()
82
+ (-0.5, 0.5)
83
+
84
+ For a distribution with infinite support,
85
+
86
+ >>> X = stats.Normal()
87
+ >>> X.support()
88
+ (-inf, inf)
89
+
90
+ Due to underflow, the numerical value returned by the PDF may be zero
91
+ even for arguments within the support, even if the true value is
92
+ nonzero. In such cases, the log-PDF may be useful.
93
+
94
+ >>> X.pdf([-100., 100.])
95
+ array([0., 0.])
96
+ >>> X.logpdf([-100., 100.])
97
+ array([-5000.91893853, -5000.91893853])
98
+
99
+ Use cases for the log-CDF and related methods are analogous.
100
+
101
+ """
102
+ raise NotImplementedError()
103
+
104
+ @abstractmethod
105
+ def sample(self, shape, *, method, rng):
106
+ r"""Random sample from the distribution.
107
+
108
+ Parameters
109
+ ----------
110
+ shape : tuple of ints, default: ()
111
+ The shape of the sample to draw. If the parameters of the distribution
112
+ underlying the random variable are arrays of shape ``param_shape``,
113
+ the output array will be of shape ``shape + param_shape``.
114
+ method : {None, 'formula', 'inverse_transform'}
115
+ The strategy used to produce the sample. By default (``None``),
116
+ the infrastructure chooses between the following options,
117
+ listed in order of precedence.
118
+
119
+ - ``'formula'``: an implementation specific to the distribution
120
+ - ``'inverse_transform'``: generate a uniformly distributed sample and
121
+ return the inverse CDF at these arguments.
122
+
123
+ Not all `method` options are available for all distributions.
124
+ If the selected `method` is not available, a `NotImplementedError``
125
+ will be raised.
126
+ rng : `numpy.random.Generator` or `scipy.stats.QMCEngine`, optional
127
+ Pseudo- or quasi-random number generator state. When `rng` is None,
128
+ a new `numpy.random.Generator` is created using entropy from the
129
+ operating system. Types other than `numpy.random.Generator` and
130
+ `scipy.stats.QMCEngine` are passed to `numpy.random.default_rng`
131
+ to instantiate a ``Generator``.
132
+
133
+ If `rng` is an instance of `scipy.stats.QMCEngine` configured to use
134
+ scrambling and `shape` is not empty, then each slice along the zeroth
135
+ axis of the result is a "quasi-independent", low-discrepancy sequence;
136
+ that is, they are distinct sequences that can be treated as statistically
137
+ independent for most practical purposes. Separate calls to `sample`
138
+ produce new quasi-independent, low-discrepancy sequences.
139
+
140
+ References
141
+ ----------
142
+ .. [1] Sampling (statistics), *Wikipedia*,
143
+ https://en.wikipedia.org/wiki/Sampling_(statistics)
144
+
145
+ Examples
146
+ --------
147
+ Instantiate a distribution with the desired parameters:
148
+
149
+ >>> import numpy as np
150
+ >>> from scipy import stats
151
+ >>> X = stats.Uniform(a=0., b=1.)
152
+
153
+ Generate a pseudorandom sample:
154
+
155
+ >>> x = X.sample((1000, 1))
156
+ >>> octiles = (np.arange(8) + 1) / 8
157
+ >>> np.count_nonzero(x <= octiles, axis=0)
158
+ array([ 148, 263, 387, 516, 636, 751, 865, 1000]) # may vary
159
+
160
+ >>> X = stats.Uniform(a=np.zeros((3, 1)), b=np.ones(2))
161
+ >>> X.a.shape,
162
+ (3, 2)
163
+ >>> x = X.sample(shape=(5, 4))
164
+ >>> x.shape
165
+ (5, 4, 3, 2)
166
+
167
+ """
168
+ raise NotImplementedError()
169
+
170
+ @abstractmethod
171
+ def moment(self, order, kind, *, method):
172
+ r"""Raw, central, or standard moment of positive integer order.
173
+
174
+ In terms of probability density function :math:`f(x)` and support
175
+ :math:`\chi`, the "raw" moment (about the origin) of order :math:`n` of
176
+ a random variable :math:`X` is:
177
+
178
+ .. math::
179
+
180
+ \mu'_n(X) = \int_{\chi} x^n f(x) dx
181
+
182
+ The "central" moment is the raw moment taken about the mean,
183
+ :math:`\mu = \mu'_1`:
184
+
185
+ .. math::
186
+
187
+ \mu_n(X) = \int_{\chi} (x - \mu) ^n f(x) dx
188
+
189
+ The "standardized" moment is the central moment normalized by the
190
+ :math:`n^\text{th}` power of the standard deviation
191
+ :math:`\sigma = \sqrt{\mu_2}` to produce a scale invariant quantity:
192
+
193
+ .. math::
194
+
195
+ \tilde{\mu}_n(X) = \frac{\mu_n(X)}
196
+ {\sigma^n}
197
+
198
+ Parameters
199
+ ----------
200
+ order : int
201
+ The integer order of the moment; i.e. :math:`n` in the formulae above.
202
+ kind : {'raw', 'central', 'standardized'}
203
+ Whether to return the raw (default), central, or standardized moment
204
+ defined above.
205
+ method : {None, 'formula', 'general', 'transform', 'normalize', 'quadrature', 'cache'}
206
+ The strategy used to evaluate the moment. By default (``None``),
207
+ the infrastructure chooses between the following options,
208
+ listed in order of precedence.
209
+
210
+ - ``'cache'``: use the value of the moment most recently calculated
211
+ via another method
212
+ - ``'formula'``: use a formula for the moment itself
213
+ - ``'general'``: use a general result that is true for all distributions
214
+ with finite moments; for instance, the zeroth raw moment is
215
+ identically 1
216
+ - ``'transform'``: transform a raw moment to a central moment or
217
+ vice versa (see Notes)
218
+ - ``'normalize'``: normalize a central moment to get a standardized
219
+ or vice versa
220
+ - ``'quadrature'``: numerically integrate according to the definition
221
+
222
+ Not all `method` options are available for all orders, kinds, and
223
+ distributions. If the selected `method` is not available, a
224
+ ``NotImplementedError`` will be raised.
225
+
226
+ Returns
227
+ -------
228
+ out : array
229
+ The moment of the random variable of the specified order and kind.
230
+
231
+ See Also
232
+ --------
233
+ pdf
234
+ mean
235
+ variance
236
+ standard_deviation
237
+ skewness
238
+ kurtosis
239
+
240
+ Notes
241
+ -----
242
+ Not all distributions have finite moments of all orders; moments of some
243
+ orders may be undefined or infinite. If a formula for the moment is not
244
+ specifically implemented for the chosen distribution, SciPy will attempt
245
+ to compute the moment via a generic method, which may yield a finite
246
+ result where none exists. This is not a critical bug, but an opportunity
247
+ for an enhancement.
248
+
249
+ The definition of a raw moment in the summary is specific to the raw moment
250
+ about the origin. The raw moment about any point :math:`a` is:
251
+
252
+ .. math::
253
+
254
+ E[(X-a)^n] = \int_{\chi} (x-a)^n f(x) dx
255
+
256
+ In this notation, a raw moment about the origin is :math:`\mu'_n = E[x^n]`,
257
+ and a central moment is :math:`\mu_n = E[(x-\mu)^n]`, where :math:`\mu`
258
+ is the first raw moment; i.e. the mean.
259
+
260
+ The ``'transform'`` method takes advantage of the following relationships
261
+ between moments taken about different points :math:`a` and :math:`b`.
262
+
263
+ .. math::
264
+
265
+ E[(X-b)^n] = \sum_{i=0}^n E[(X-a)^i] {n \choose i} (a - b)^{n-i}
266
+
267
+ For instance, to transform the raw moment to the central moment, we let
268
+ :math:`b = \mu` and :math:`a = 0`.
269
+
270
+ The distribution infrastructure provides flexibility for distribution
271
+ authors to implement separate formulas for raw moments, central moments,
272
+ and standardized moments of any order. By default, the moment of the
273
+ desired order and kind is evaluated from the formula if such a formula
274
+ is available; if not, the infrastructure uses any formulas that are
275
+ available rather than resorting directly to numerical integration.
276
+ For instance, if formulas for the first three raw moments are
277
+ available and the third standardized moments is desired, the
278
+ infrastructure will evaluate the raw moments and perform the transforms
279
+ and standardization required. The decision tree is somewhat complex,
280
+ but the strategy for obtaining a moment of a given order and kind
281
+ (possibly as an intermediate step due to the recursive nature of the
282
+ transform formula above) roughly follows this order of priority:
283
+
284
+ #. Use cache (if order of same moment and kind has been calculated)
285
+ #. Use formula (if available)
286
+ #. Transform between raw and central moment and/or normalize to convert
287
+ between central and standardized moments (if efficient)
288
+ #. Use a generic result true for most distributions (if available)
289
+ #. Use quadrature
290
+
291
+ References
292
+ ----------
293
+ .. [1] Moment, *Wikipedia*,
294
+ https://en.wikipedia.org/wiki/Moment_(mathematics)
295
+
296
+ Examples
297
+ --------
298
+ Instantiate a distribution with the desired parameters:
299
+
300
+ >>> from scipy import stats
301
+ >>> X = stats.Normal(mu=1., sigma=2.)
302
+
303
+ Evaluate the first raw moment:
304
+
305
+ >>> X.moment(order=1, kind='raw')
306
+ 1.0
307
+ >>> X.moment(order=1, kind='raw') == X.mean() == X.mu
308
+ True
309
+
310
+ Evaluate the second central moment:
311
+
312
+ >>> X.moment(order=2, kind='central')
313
+ 4.0
314
+ >>> X.moment(order=2, kind='central') == X.variance() == X.sigma**2
315
+ True
316
+
317
+ Evaluate the fourth standardized moment:
318
+
319
+ >>> X.moment(order=4, kind='standardized')
320
+ 3.0
321
+ >>> X.moment(order=4, kind='standardized') == X.kurtosis(convention='non-excess')
322
+ True
323
+
324
+ """ # noqa:E501
325
+ raise NotImplementedError()
326
+
327
+ @abstractmethod
328
+ def mean(self, *, method):
329
+ r"""Mean (raw first moment about the origin)
330
+
331
+ Parameters
332
+ ----------
333
+ method : {None, 'formula', 'transform', 'quadrature', 'cache'}
334
+ Method used to calculate the raw first moment. Not
335
+ all methods are available for all distributions. See
336
+ `moment` for details.
337
+
338
+ See Also
339
+ --------
340
+ moment
341
+ median
342
+ mode
343
+
344
+ References
345
+ ----------
346
+ .. [1] Mean, *Wikipedia*,
347
+ https://en.wikipedia.org/wiki/Mean#Mean_of_a_probability_distribution
348
+
349
+ Examples
350
+ --------
351
+ Instantiate a distribution with the desired parameters:
352
+
353
+ >>> from scipy import stats
354
+ >>> X = stats.Normal(mu=1., sigma=2.)
355
+
356
+ Evaluate the variance:
357
+
358
+ >>> X.mean()
359
+ 1.0
360
+ >>> X.mean() == X.moment(order=1, kind='raw') == X.mu
361
+ True
362
+
363
+ """
364
+ raise NotImplementedError()
365
+
366
+ @abstractmethod
367
+ def median(self, *, method):
368
+ r"""Median (50th percentil)
369
+
370
+ If a continuous random variable :math:`X` has probability :math:`0.5` of
371
+ taking on a value less than :math:`m`, then :math:`m` is the median.
372
+ That is, the median is the value :math:`m` for which:
373
+
374
+ .. math::
375
+
376
+ P(X ≤ m) = 0.5 = P(X ≥ m)
377
+
378
+ Parameters
379
+ ----------
380
+ method : {None, 'formula', 'icdf'}
381
+ The strategy used to evaluate the median.
382
+ By default (``None``), the infrastructure chooses between the
383
+ following options, listed in order of precedence.
384
+
385
+ - ``'formula'``: use a formula for the median
386
+ - ``'icdf'``: evaluate the inverse CDF of 0.5
387
+
388
+ Not all `method` options are available for all distributions.
389
+ If the selected `method` is not available, a ``NotImplementedError``
390
+ will be raised.
391
+
392
+ Returns
393
+ -------
394
+ out : array
395
+ The median
396
+
397
+ See Also
398
+ --------
399
+ mean
400
+ mode
401
+ icdf
402
+
403
+ References
404
+ ----------
405
+ .. [1] Median, *Wikipedia*,
406
+ https://en.wikipedia.org/wiki/Median#Probability_distributions
407
+
408
+ Examples
409
+ --------
410
+ Instantiate a distribution with the desired parameters:
411
+
412
+ >>> from scipy import stats
413
+ >>> X = stats.Uniform(a=0., b=10.)
414
+
415
+ Compute the median:
416
+
417
+ >>> X.median()
418
+ np.float64(5.0)
419
+ >>> X.median() == X.icdf(0.5) == X.iccdf(0.5)
420
+ True
421
+
422
+ """
423
+ raise NotImplementedError()
424
+
425
+ @abstractmethod
426
+ def mode(self, *, method):
427
+ r"""Mode (most likely value)
428
+
429
+ Informally, the mode is a value that a random variable has the highest
430
+ probability (density) of assuming. That is, the mode is the element of
431
+ the support :math:`\chi` that maximizes the probability density
432
+ function :math:`f(x)`:
433
+
434
+ .. math::
435
+
436
+ \text{mode} = \arg\max_{x \in \chi} f(x)
437
+
438
+ Parameters
439
+ ----------
440
+ method : {None, 'formula', 'optimization'}
441
+ The strategy used to evaluate the mode.
442
+ By default (``None``), the infrastructure chooses between the
443
+ following options, listed in order of precedence.
444
+
445
+ - ``'formula'``: use a formula for the median
446
+ - ``'optimization'``: numerically maximize the PDF
447
+
448
+ Not all `method` options are available for all distributions.
449
+ If the selected `method` is not available, a ``NotImplementedError``
450
+ will be raised.
451
+
452
+ Returns
453
+ -------
454
+ out : array
455
+ The mode
456
+
457
+ See Also
458
+ --------
459
+ mean
460
+ median
461
+ pdf
462
+
463
+ Notes
464
+ -----
465
+ For some distributions
466
+
467
+ #. the mode is not unique (e.g. the uniform distribution);
468
+ #. the PDF has one or more singularities, and it is debateable whether
469
+ a singularity is considered to be in the domain and called the mode
470
+ (e.g. the gamma distribution with shape parameter less than 1); and/or
471
+ #. the probability density function may have one or more local maxima
472
+ that are not a global maximum (e.g. mixture distributions).
473
+
474
+ In such cases, `mode` will
475
+
476
+ #. return a single value,
477
+ #. consider the mode to occur at a singularity, and/or
478
+ #. return a local maximum which may or may not be a global maximum.
479
+
480
+ If a formula for the mode is not specifically implemented for the
481
+ chosen distribution, SciPy will attempt to compute the mode
482
+ numerically, which may not meet the user's preferred definition of a
483
+ mode. In such cases, the user is encouraged to subclass the
484
+ distribution and override ``mode``.
485
+
486
+ References
487
+ ----------
488
+ .. [1] Mode (statistics), *Wikipedia*,
489
+ https://en.wikipedia.org/wiki/Mode_(statistics)
490
+
491
+ Examples
492
+ --------
493
+ Instantiate a distribution with the desired parameters:
494
+
495
+ >>> from scipy import stats
496
+ >>> X = stats.Normal(mu=1., sigma=2.)
497
+
498
+ Evaluate the mode:
499
+
500
+ >>> X.mode()
501
+ 1.0
502
+
503
+ If the mode is not uniquely defined, ``mode`` nonetheless returns a
504
+ single value.
505
+
506
+ >>> X = stats.Uniform(a=0., b=1.)
507
+ >>> X.mode()
508
+ 0.5
509
+
510
+ If this choice does not satisfy your requirements, subclass the
511
+ distribution and override ``mode``:
512
+
513
+ >>> class BetterUniform(stats.Uniform):
514
+ ... def mode(self):
515
+ ... return self.b
516
+ >>> X = BetterUniform(a=0., b=1.)
517
+ >>> X.mode()
518
+ 1.0
519
+
520
+ """
521
+ raise NotImplementedError()
522
+
523
+ @abstractmethod
524
+ def variance(self, *, method):
525
+ r"""Variance (central second moment)
526
+
527
+ Parameters
528
+ ----------
529
+ method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
530
+ Method used to calculate the central second moment. Not
531
+ all methods are available for all distributions. See
532
+ `moment` for details.
533
+
534
+ See Also
535
+ --------
536
+ moment
537
+ standard_deviation
538
+ mean
539
+
540
+ References
541
+ ----------
542
+ .. [1] Variance, *Wikipedia*,
543
+ https://en.wikipedia.org/wiki/Variance#Absolutely_continuous_random_variable
544
+
545
+ Examples
546
+ --------
547
+ Instantiate a distribution with the desired parameters:
548
+
549
+ >>> from scipy import stats
550
+ >>> X = stats.Normal(mu=1., sigma=2.)
551
+
552
+ Evaluate the variance:
553
+
554
+ >>> X.variance()
555
+ 4.0
556
+ >>> X.variance() == X.moment(order=2, kind='central') == X.sigma**2
557
+ True
558
+
559
+ """
560
+ raise NotImplementedError()
561
+
562
+ @abstractmethod
563
+ def standard_deviation(self, *, method):
564
+ r"""Standard deviation (square root of the second central moment)
565
+
566
+ Parameters
567
+ ----------
568
+ method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
569
+ Method used to calculate the central second moment. Not
570
+ all methods are available for all distributions. See
571
+ `moment` for details.
572
+
573
+ See Also
574
+ --------
575
+ variance
576
+ mean
577
+ moment
578
+
579
+ References
580
+ ----------
581
+ .. [1] Standard deviation, *Wikipedia*,
582
+ https://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values
583
+
584
+ Examples
585
+ --------
586
+ Instantiate a distribution with the desired parameters:
587
+
588
+ >>> from scipy import stats
589
+ >>> X = stats.Normal(mu=1., sigma=2.)
590
+
591
+ Evaluate the standard deviation:
592
+
593
+ >>> X.standard_deviation()
594
+ 2.0
595
+ >>> X.standard_deviation() == X.moment(order=2, kind='central')**0.5 == X.sigma
596
+ True
597
+
598
+ """
599
+ raise NotImplementedError()
600
+
601
+ @abstractmethod
602
+ def skewness(self, *, method):
603
+ r"""Skewness (standardized third moment)
604
+
605
+ Parameters
606
+ ----------
607
+ method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
608
+ Method used to calculate the standardized third moment. Not
609
+ all methods are available for all distributions. See
610
+ `moment` for details.
611
+
612
+ See Also
613
+ --------
614
+ moment
615
+ mean
616
+ variance
617
+
618
+ References
619
+ ----------
620
+ .. [1] Skewness, *Wikipedia*,
621
+ https://en.wikipedia.org/wiki/Skewness
622
+
623
+ Examples
624
+ --------
625
+ Instantiate a distribution with the desired parameters:
626
+
627
+ >>> from scipy import stats
628
+ >>> X = stats.Normal(mu=1., sigma=2.)
629
+
630
+ Evaluate the skewness:
631
+
632
+ >>> X.skewness()
633
+ 0.0
634
+ >>> X.skewness() == X.moment(order=3, kind='standardized')
635
+ True
636
+
637
+ """
638
+ raise NotImplementedError()
639
+
640
+ @abstractmethod
641
+ def kurtosis(self, *, method):
642
+ r"""Kurtosis (standardized fourth moment)
643
+
644
+ By default, this is the standardized fourth moment, also known as the
645
+ "non-excess" or "Pearson" kurtosis (e.g. the kurtosis of the normal
646
+ distribution is 3). The "excess" or "Fisher" kurtosis (the standardized
647
+ fourth moment minus 3) is available via the `convention` parameter.
648
+
649
+ Parameters
650
+ ----------
651
+ method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
652
+ Method used to calculate the standardized fourth moment. Not
653
+ all methods are available for all distributions. See
654
+ `moment` for details.
655
+ convention : {'non-excess', 'excess'}
656
+ Two distinct conventions are available:
657
+
658
+ - ``'non-excess'``: the standardized fourth moment (Pearson's kurtosis)
659
+ - ``'excess'``: the standardized fourth moment minus 3 (Fisher's kurtosis)
660
+
661
+ The default is ``'non-excess'``.
662
+
663
+ See Also
664
+ --------
665
+ moment
666
+ mean
667
+ variance
668
+
669
+ References
670
+ ----------
671
+ .. [1] Kurtosis, *Wikipedia*,
672
+ https://en.wikipedia.org/wiki/Kurtosis
673
+
674
+ Examples
675
+ --------
676
+ Instantiate a distribution with the desired parameters:
677
+
678
+ >>> from scipy import stats
679
+ >>> X = stats.Normal(mu=1., sigma=2.)
680
+
681
+ Evaluate the kurtosis:
682
+
683
+ >>> X.kurtosis()
684
+ 3.0
685
+ >>> (X.kurtosis()
686
+ ... == X.kurtosis(convention='excess') + 3.
687
+ ... == X.moment(order=4, kind='standardized'))
688
+ True
689
+
690
+ """
691
+ raise NotImplementedError()
692
+
693
+ @abstractmethod
694
+ def pdf(self, x, /, *, method):
695
+ r"""Probability density function
696
+
697
+ The probability density function ("PDF"), denoted :math:`f(x)`, is the
698
+ probability *per unit length* that the random variable will assume the
699
+ value :math:`x`. Mathematically, it can be defined as the derivative
700
+ of the cumulative distribution function :math:`F(x)`:
701
+
702
+ .. math::
703
+
704
+ f(x) = \frac{d}{dx} F(x)
705
+
706
+ `pdf` accepts `x` for :math:`x`.
707
+
708
+ Parameters
709
+ ----------
710
+ x : array_like
711
+ The argument of the PDF.
712
+ method : {None, 'formula', 'logexp'}
713
+ The strategy used to evaluate the PDF. By default (``None``), the
714
+ infrastructure chooses between the following options, listed in
715
+ order of precedence.
716
+
717
+ - ``'formula'``: use a formula for the PDF itself
718
+ - ``'logexp'``: evaluate the log-PDF and exponentiate
719
+
720
+ Not all `method` options are available for all distributions.
721
+ If the selected `method` is not available, a ``NotImplementedError``
722
+ will be raised.
723
+
724
+ Returns
725
+ -------
726
+ out : array
727
+ The PDF evaluated at the argument `x`.
728
+
729
+ See Also
730
+ --------
731
+ cdf
732
+ logpdf
733
+
734
+ Notes
735
+ -----
736
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
737
+ By definition of the support, the PDF evaluates to its minimum value
738
+ of :math:`0` outside the support; i.e. for :math:`x < l` or
739
+ :math:`x > r`. The maximum of the PDF may be less than or greater than
740
+ :math:`1`; since the valus is a probability *density*, only its integral
741
+ over the support must equal :math:`1`.
742
+
743
+ References
744
+ ----------
745
+ .. [1] Probability density function, *Wikipedia*,
746
+ https://en.wikipedia.org/wiki/Probability_density_function
747
+
748
+ Examples
749
+ --------
750
+ Instantiate a distribution with the desired parameters:
751
+
752
+ >>> from scipy import stats
753
+ >>> X = stats.Uniform(a=-1., b=1.)
754
+
755
+ Evaluate the PDF at the desired argument:
756
+
757
+ >>> X.pdf(0.25)
758
+ 0.5
759
+
760
+ """
761
+ raise NotImplementedError()
762
+
763
+ @abstractmethod
764
+ def logpdf(self, x, /, *, method):
765
+ r"""Log of the probability density function
766
+
767
+ The probability density function ("PDF"), denoted :math:`f(x)`, is the
768
+ probability *per unit length* that the random variable will assume the
769
+ value :math:`x`. Mathematically, it can be defined as the derivative
770
+ of the cumulative distribution function :math:`F(x)`:
771
+
772
+ .. math::
773
+
774
+ f(x) = \frac{d}{dx} F(x)
775
+
776
+ `logpdf` computes the logarithm of the probability density function
777
+ ("log-PDF"), :math:`\log(f(x))`, but it may be numerically favorable
778
+ compared to the naive implementation (computing :math:`f(x)` and
779
+ taking the logarithm).
780
+
781
+ `logpdf` accepts `x` for :math:`x`.
782
+
783
+ Parameters
784
+ ----------
785
+ x : array_like
786
+ The argument of the log-PDF.
787
+ method : {None, 'formula', 'logexp'}
788
+ The strategy used to evaluate the log-PDF. By default (``None``), the
789
+ infrastructure chooses between the following options, listed in order
790
+ of precedence.
791
+
792
+ - ``'formula'``: use a formula for the log-PDF itself
793
+ - ``'logexp'``: evaluate the PDF and takes its logarithm
794
+
795
+ Not all `method` options are available for all distributions.
796
+ If the selected `method` is not available, a ``NotImplementedError``
797
+ will be raised.
798
+
799
+ Returns
800
+ -------
801
+ out : array
802
+ The log-PDF evaluated at the argument `x`.
803
+
804
+ See Also
805
+ --------
806
+ pdf
807
+ logcdf
808
+
809
+ Notes
810
+ -----
811
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
812
+ By definition of the support, the log-PDF evaluates to its minimum value
813
+ of :math:`-\infty` (i.e. :math:`\log(0)`) outside the support; i.e. for
814
+ :math:`x < l` or :math:`x > r`. The maximum of the log-PDF may be less
815
+ than or greater than :math:`\log(1) = 0` because the maximum of the PDF
816
+ can be any positive real.
817
+
818
+ For distributions with infinite support, it is common for `pdf` to return
819
+ a value of ``0`` when the argument is theoretically within the support;
820
+ this can occur because the true value of the PDF is too small to be
821
+ represented by the chosen dtype. The log-PDF, however, will often be finite
822
+ (not ``-inf``) over a much larger domain. Consequently, it may be preferred
823
+ to work with the logarithms of probabilities and probability densities to
824
+ avoid underflow.
825
+
826
+ References
827
+ ----------
828
+ .. [1] Probability density function, *Wikipedia*,
829
+ https://en.wikipedia.org/wiki/Probability_density_function
830
+
831
+ Examples
832
+ --------
833
+ Instantiate a distribution with the desired parameters:
834
+
835
+ >>> import numpy as np
836
+ >>> from scipy import stats
837
+ >>> X = stats.Uniform(a=-1.0, b=1.0)
838
+
839
+ Evaluate the log-PDF at the desired argument:
840
+
841
+ >>> X.logpdf(0.5)
842
+ -0.6931471805599453
843
+ >>> np.allclose(X.logpdf(0.5), np.log(X.pdf(0.5)))
844
+ True
845
+
846
+ """
847
+ raise NotImplementedError()
848
+
849
+ @abstractmethod
850
+ def cdf(self, x, y, /, *, method):
851
+ r"""Cumulative distribution function
852
+
853
+ The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
854
+ the probability the random variable :math:`X` will assume a value
855
+ less than or equal to :math:`x`:
856
+
857
+ .. math::
858
+
859
+ F(x) = P(X ≤ x)
860
+
861
+ A two-argument variant of this function is also defined as the
862
+ probability the random variable :math:`X` will assume a value between
863
+ :math:`x` and :math:`y`.
864
+
865
+ .. math::
866
+
867
+ F(x, y) = P(x ≤ X ≤ y)
868
+
869
+ `cdf` accepts `x` for :math:`x` and `y` for :math:`y`.
870
+
871
+ Parameters
872
+ ----------
873
+ x, y : array_like
874
+ The arguments of the CDF. `x` is required; `y` is optional.
875
+ method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
876
+ The strategy used to evaluate the CDF.
877
+ By default (``None``), the one-argument form of the function
878
+ chooses between the following options, listed in order of precedence.
879
+
880
+ - ``'formula'``: use a formula for the CDF itself
881
+ - ``'logexp'``: evaluate the log-CDF and exponentiate
882
+ - ``'complement'``: evaluate the CCDF and take the complement
883
+ - ``'quadrature'``: numerically integrate the PDF
884
+
885
+ In place of ``'complement'``, the two-argument form accepts:
886
+
887
+ - ``'subtraction'``: compute the CDF at each argument and take
888
+ the difference.
889
+
890
+ Not all `method` options are available for all distributions.
891
+ If the selected `method` is not available, a ``NotImplementedError``
892
+ will be raised.
893
+
894
+ Returns
895
+ -------
896
+ out : array
897
+ The CDF evaluated at the provided argument(s).
898
+
899
+ See Also
900
+ --------
901
+ logcdf
902
+ ccdf
903
+
904
+ Notes
905
+ -----
906
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
907
+ The CDF :math:`F(x)` is related to the probability density function
908
+ :math:`f(x)` by:
909
+
910
+ .. math::
911
+
912
+ F(x) = \int_l^x f(u) du
913
+
914
+ The two argument version is:
915
+
916
+ .. math::
917
+
918
+ F(x, y) = \int_x^y f(u) du = F(y) - F(x)
919
+
920
+ The CDF evaluates to its minimum value of :math:`0` for :math:`x ≤ l`
921
+ and its maximum value of :math:`1` for :math:`x ≥ r`.
922
+
923
+ The CDF is also known simply as the "distribution function".
924
+
925
+ References
926
+ ----------
927
+ .. [1] Cumulative distribution function, *Wikipedia*,
928
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
929
+
930
+ Examples
931
+ --------
932
+ Instantiate a distribution with the desired parameters:
933
+
934
+ >>> from scipy import stats
935
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
936
+
937
+ Evaluate the CDF at the desired argument:
938
+
939
+ >>> X.cdf(0.25)
940
+ 0.75
941
+
942
+ Evaluate the cumulative probability between two arguments:
943
+
944
+ >>> X.cdf(-0.25, 0.25) == X.cdf(0.25) - X.cdf(-0.25)
945
+ True
946
+
947
+ """ # noqa: E501
948
+ raise NotImplementedError()
949
+
950
+ @abstractmethod
951
+ def icdf(self, p, /, *, method):
952
+ r"""Inverse of the cumulative distribution function.
953
+
954
+ The inverse of the cumulative distribution function ("inverse CDF"),
955
+ denoted :math:`F^{-1}(p)`, is the argument :math:`x` for which the
956
+ cumulative distribution function :math:`F(x)` evaluates to :math:`p`.
957
+
958
+ .. math::
959
+
960
+ F^{-1}(p) = x \quad \text{s.t.} \quad F(x) = p
961
+
962
+ `icdf` accepts `p` for :math:`p \in [0, 1]`.
963
+
964
+ Parameters
965
+ ----------
966
+ p : array_like
967
+ The argument of the inverse CDF.
968
+ method : {None, 'formula', 'complement', 'inversion'}
969
+ The strategy used to evaluate the inverse CDF.
970
+ By default (``None``), the infrastructure chooses between the
971
+ following options, listed in order of precedence.
972
+
973
+ - ``'formula'``: use a formula for the inverse CDF itself
974
+ - ``'complement'``: evaluate the inverse CCDF at the
975
+ complement of `p`
976
+ - ``'inversion'``: solve numerically for the argument at which the
977
+ CDF is equal to `p`
978
+
979
+ Not all `method` options are available for all distributions.
980
+ If the selected `method` is not available, a ``NotImplementedError``
981
+ will be raised.
982
+
983
+ Returns
984
+ -------
985
+ out : array
986
+ The inverse CDF evaluated at the provided argument.
987
+
988
+ See Also
989
+ --------
990
+ cdf
991
+ ilogcdf
992
+
993
+ Notes
994
+ -----
995
+ Suppose a continuous probability distribution has support :math:`[l, r]`. The
996
+ inverse CDF returns its minimum value of :math:`l` at :math:`p = 0`
997
+ and its maximum value of :math:`r` at :math:`p = 1`. Because the CDF
998
+ has range :math:`[0, 1]`, the inverse CDF is only defined on the
999
+ domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, `icdf`
1000
+ returns ``nan``.
1001
+
1002
+ The inverse CDF is also known as the quantile function, percentile function,
1003
+ and percent-point function.
1004
+
1005
+ References
1006
+ ----------
1007
+ .. [1] Quantile function, *Wikipedia*,
1008
+ https://en.wikipedia.org/wiki/Quantile_function
1009
+
1010
+ Examples
1011
+ --------
1012
+ Instantiate a distribution with the desired parameters:
1013
+
1014
+ >>> import numpy as np
1015
+ >>> from scipy import stats
1016
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1017
+
1018
+ Evaluate the inverse CDF at the desired argument:
1019
+
1020
+ >>> X.icdf(0.25)
1021
+ -0.25
1022
+ >>> np.allclose(X.cdf(X.icdf(0.25)), 0.25)
1023
+ True
1024
+
1025
+ This function returns NaN when the argument is outside the domain.
1026
+
1027
+ >>> X.icdf([-0.1, 0, 1, 1.1])
1028
+ array([ nan, -0.5, 0.5, nan])
1029
+
1030
+ """
1031
+ raise NotImplementedError()
1032
+
1033
+ @abstractmethod
1034
+ def ccdf(self, x, y, /, *, method):
1035
+ r"""Complementary cumulative distribution function
1036
+
1037
+ The complementary cumulative distribution function ("CCDF"), denoted
1038
+ :math:`G(x)`, is the complement of the cumulative distribution function
1039
+ :math:`F(x)`; i.e., probability the random variable :math:`X` will
1040
+ assume a value greater than :math:`x`:
1041
+
1042
+ .. math::
1043
+
1044
+ G(x) = 1 - F(x) = P(X > x)
1045
+
1046
+ A two-argument variant of this function is:
1047
+
1048
+ .. math::
1049
+
1050
+ G(x, y) = 1 - F(x, y) = P(X < x \text{ or } X > y)
1051
+
1052
+ `ccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
1053
+
1054
+ Parameters
1055
+ ----------
1056
+ x, y : array_like
1057
+ The arguments of the CCDF. `x` is required; `y` is optional.
1058
+ method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
1059
+ The strategy used to evaluate the CCDF.
1060
+ By default (``None``), the infrastructure chooses between the
1061
+ following options, listed in order of precedence.
1062
+
1063
+ - ``'formula'``: use a formula for the CCDF itself
1064
+ - ``'logexp'``: evaluate the log-CCDF and exponentiate
1065
+ - ``'complement'``: evaluate the CDF and take the complement
1066
+ - ``'quadrature'``: numerically integrate the PDF
1067
+
1068
+ The two-argument form chooses between:
1069
+
1070
+ - ``'formula'``: use a formula for the CCDF itself
1071
+ - ``'addition'``: compute the CDF at `x` and the CCDF at `y`, then add
1072
+
1073
+ Not all `method` options are available for all distributions.
1074
+ If the selected `method` is not available, a ``NotImplementedError``
1075
+ will be raised.
1076
+
1077
+ Returns
1078
+ -------
1079
+ out : array
1080
+ The CCDF evaluated at the provided argument(s).
1081
+
1082
+ See Also
1083
+ --------
1084
+ cdf
1085
+ logccdf
1086
+
1087
+ Notes
1088
+ -----
1089
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
1090
+ The CCDF :math:`G(x)` is related to the probability density function
1091
+ :math:`f(x)` by:
1092
+
1093
+ .. math::
1094
+
1095
+ G(x) = \int_x^r f(u) du
1096
+
1097
+ The two argument version is:
1098
+
1099
+ .. math::
1100
+
1101
+ G(x, y) = \int_l^x f(u) du + \int_y^r f(u) du
1102
+
1103
+ The CCDF returns its minimum value of :math:`0` for :math:`x ≥ r`
1104
+ and its maximum value of :math:`1` for :math:`x ≤ l`.
1105
+
1106
+ The CCDF is also known as the "survival function".
1107
+
1108
+ References
1109
+ ----------
1110
+ .. [1] Cumulative distribution function, *Wikipedia*,
1111
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
1112
+
1113
+ Examples
1114
+ --------
1115
+ Instantiate a distribution with the desired parameters:
1116
+
1117
+ >>> import numpy as np
1118
+ >>> from scipy import stats
1119
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1120
+
1121
+ Evaluate the CCDF at the desired argument:
1122
+
1123
+ >>> X.ccdf(0.25)
1124
+ 0.25
1125
+ >>> np.allclose(X.ccdf(0.25), 1-X.cdf(0.25))
1126
+ True
1127
+
1128
+ Evaluate the complement of the cumulative probability between two arguments:
1129
+
1130
+ >>> X.ccdf(-0.25, 0.25) == X.cdf(-0.25) + X.ccdf(0.25)
1131
+ True
1132
+
1133
+ """ # noqa: E501
1134
+ raise NotImplementedError()
1135
+
1136
+ @abstractmethod
1137
+ def iccdf(self, p, /, *, method):
1138
+ r"""Inverse complementary cumulative distribution function.
1139
+
1140
+ The inverse complementary cumulative distribution function ("inverse CCDF"),
1141
+ denoted :math:`G^{-1}(p)`, is the argument :math:`x` for which the
1142
+ complementary cumulative distribution function :math:`G(x)` evaluates to
1143
+ :math:`p`.
1144
+
1145
+ .. math::
1146
+
1147
+ G^{-1}(p) = x \quad \text{s.t.} \quad G(x) = p
1148
+
1149
+ `iccdf` accepts `p` for :math:`p \in [0, 1]`.
1150
+
1151
+ Parameters
1152
+ ----------
1153
+ p : array_like
1154
+ The argument of the inverse CCDF.
1155
+ method : {None, 'formula', 'complement', 'inversion'}
1156
+ The strategy used to evaluate the inverse CCDF.
1157
+ By default (``None``), the infrastructure chooses between the
1158
+ following options, listed in order of precedence.
1159
+
1160
+ - ``'formula'``: use a formula for the inverse CCDF itself
1161
+ - ``'complement'``: evaluate the inverse CDF at the
1162
+ complement of `p`
1163
+ - ``'inversion'``: solve numerically for the argument at which the
1164
+ CCDF is equal to `p`
1165
+
1166
+ Not all `method` options are available for all distributions.
1167
+ If the selected `method` is not available, a ``NotImplementedError``
1168
+ will be raised.
1169
+
1170
+ Returns
1171
+ -------
1172
+ out : array
1173
+ The inverse CCDF evaluated at the provided argument.
1174
+
1175
+ Notes
1176
+ -----
1177
+ Suppose a continuous probability distribution has support :math:`[l, r]`. The
1178
+ inverse CCDF returns its minimum value of :math:`l` at :math:`p = 1`
1179
+ and its maximum value of :math:`r` at :math:`p = 0`. Because the CCDF
1180
+ has range :math:`[0, 1]`, the inverse CCDF is only defined on the
1181
+ domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, ``iccdf``
1182
+ returns ``nan``.
1183
+
1184
+ See Also
1185
+ --------
1186
+ icdf
1187
+ ilogccdf
1188
+
1189
+ Examples
1190
+ --------
1191
+ Instantiate a distribution with the desired parameters:
1192
+
1193
+ >>> import numpy as np
1194
+ >>> from scipy import stats
1195
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1196
+
1197
+ Evaluate the inverse CCDF at the desired argument:
1198
+
1199
+ >>> X.iccdf(0.25)
1200
+ 0.25
1201
+ >>> np.allclose(X.iccdf(0.25), X.icdf(1-0.25))
1202
+ True
1203
+
1204
+ This function returns NaN when the argument is outside the domain.
1205
+
1206
+ >>> X.iccdf([-0.1, 0, 1, 1.1])
1207
+ array([ nan, 0.5, -0.5, nan])
1208
+
1209
+ """
1210
+ raise NotImplementedError()
1211
+
1212
+ @abstractmethod
1213
+ def logcdf(self, x, y, /, *, method):
1214
+ r"""Log of the cumulative distribution function
1215
+
1216
+ The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
1217
+ the probability the random variable :math:`X` will assume a value
1218
+ less than or equal to :math:`x`:
1219
+
1220
+ .. math::
1221
+
1222
+ F(x) = P(X ≤ x)
1223
+
1224
+ A two-argument variant of this function is also defined as the
1225
+ probability the random variable :math:`X` will assume a value between
1226
+ :math:`x` and :math:`y`.
1227
+
1228
+ .. math::
1229
+
1230
+ F(x, y) = P(x ≤ X ≤ y)
1231
+
1232
+ `logcdf` computes the logarithm of the cumulative distribution function
1233
+ ("log-CDF"), :math:`\log(F(x))`/:math:`\log(F(x, y))`, but it may be
1234
+ numerically favorable compared to the naive implementation (computing
1235
+ the CDF and taking the logarithm).
1236
+
1237
+ `logcdf` accepts `x` for :math:`x` and `y` for :math:`y`.
1238
+
1239
+ Parameters
1240
+ ----------
1241
+ x, y : array_like
1242
+ The arguments of the log-CDF. `x` is required; `y` is optional.
1243
+ method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
1244
+ The strategy used to evaluate the log-CDF.
1245
+ By default (``None``), the one-argument form of the function
1246
+ chooses between the following options, listed in order of precedence.
1247
+
1248
+ - ``'formula'``: use a formula for the log-CDF itself
1249
+ - ``'logexp'``: evaluate the CDF and take the logarithm
1250
+ - ``'complement'``: evaluate the log-CCDF and take the
1251
+ logarithmic complement (see Notes)
1252
+ - ``'quadrature'``: numerically log-integrate the log-PDF
1253
+
1254
+ In place of ``'complement'``, the two-argument form accepts:
1255
+
1256
+ - ``'subtraction'``: compute the log-CDF at each argument and take
1257
+ the logarithmic difference (see Notes)
1258
+
1259
+ Not all `method` options are available for all distributions.
1260
+ If the selected `method` is not available, a ``NotImplementedError``
1261
+ will be raised.
1262
+
1263
+ Returns
1264
+ -------
1265
+ out : array
1266
+ The log-CDF evaluated at the provided argument(s).
1267
+
1268
+ See Also
1269
+ --------
1270
+ cdf
1271
+ logccdf
1272
+
1273
+ Notes
1274
+ -----
1275
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
1276
+ The log-CDF evaluates to its minimum value of :math:`\log(0) = -\infty`
1277
+ for :math:`x ≤ l` and its maximum value of :math:`\log(1) = 0` for
1278
+ :math:`x ≥ r`.
1279
+
1280
+ For distributions with infinite support, it is common for
1281
+ `cdf` to return a value of ``0`` when the argument
1282
+ is theoretically within the support; this can occur because the true value
1283
+ of the CDF is too small to be represented by the chosen dtype. `logcdf`,
1284
+ however, will often return a finite (not ``-inf``) result over a much larger
1285
+ domain. Similarly, `logcdf` may provided a strictly negative result with
1286
+ arguments for which `cdf` would return ``1.0``. Consequently, it may be
1287
+ preferred to work with the logarithms of probabilities to avoid underflow
1288
+ and related limitations of floating point numbers.
1289
+
1290
+ The "logarithmic complement" of a number :math:`z` is mathematically
1291
+ equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
1292
+ of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
1293
+ Similarly, the term "logarithmic difference" of :math:`w` and :math:`z`
1294
+ is used here to mean :math:`\log(\exp(w)-\exp(z))`.
1295
+
1296
+ If ``y < x``, the CDF is negative, and therefore the log-CCDF
1297
+ is complex with imaginary part :math:`\pi`. For
1298
+ consistency, the result of this function always has complex dtype
1299
+ when `y` is provided, regardless of the value of the imaginary part.
1300
+
1301
+ References
1302
+ ----------
1303
+ .. [1] Cumulative distribution function, *Wikipedia*,
1304
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
1305
+
1306
+ Examples
1307
+ --------
1308
+ Instantiate a distribution with the desired parameters:
1309
+
1310
+ >>> import numpy as np
1311
+ >>> from scipy import stats
1312
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1313
+
1314
+ Evaluate the log-CDF at the desired argument:
1315
+
1316
+ >>> X.logcdf(0.25)
1317
+ -0.287682072451781
1318
+ >>> np.allclose(X.logcdf(0.), np.log(X.cdf(0.)))
1319
+ True
1320
+
1321
+ """ # noqa: E501
1322
+ raise NotImplementedError()
1323
+
1324
+ @abstractmethod
1325
+ def ilogcdf(self, logp, /, *, method):
1326
+ r"""Inverse of the logarithm of the cumulative distribution function.
1327
+
1328
+ The inverse of the logarithm of the cumulative distribution function
1329
+ ("inverse log-CDF") is the argument :math:`x` for which the logarithm
1330
+ of the cumulative distribution function :math:`\log(F(x))` evaluates
1331
+ to :math:`\log(p)`.
1332
+
1333
+ Mathematically, it is equivalent to :math:`F^{-1}(\exp(y))`, where
1334
+ :math:`y = \log(p)`, but it may be numerically favorable compared to
1335
+ the naive implementation (computing :math:`p = \exp(y)`, then
1336
+ :math:`F^{-1}(p)`).
1337
+
1338
+ `ilogcdf` accepts `logp` for :math:`\log(p) ≤ 0`.
1339
+
1340
+ Parameters
1341
+ ----------
1342
+ logp : array_like
1343
+ The argument of the inverse log-CDF.
1344
+ method : {None, 'formula', 'complement', 'inversion'}
1345
+ The strategy used to evaluate the inverse log-CDF.
1346
+ By default (``None``), the infrastructure chooses between the
1347
+ following options, listed in order of precedence.
1348
+
1349
+ - ``'formula'``: use a formula for the inverse log-CDF itself
1350
+ - ``'complement'``: evaluate the inverse log-CCDF at the
1351
+ logarithmic complement of `logp` (see Notes)
1352
+ - ``'inversion'``: solve numerically for the argument at which the
1353
+ log-CDF is equal to `logp`
1354
+
1355
+ Not all `method` options are available for all distributions.
1356
+ If the selected `method` is not available, a ``NotImplementedError``
1357
+ will be raised.
1358
+
1359
+ Returns
1360
+ -------
1361
+ out : array
1362
+ The inverse log-CDF evaluated at the provided argument.
1363
+
1364
+ See Also
1365
+ --------
1366
+ icdf
1367
+ logcdf
1368
+
1369
+ Notes
1370
+ -----
1371
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
1372
+ The inverse log-CDF returns its minimum value of :math:`l` at
1373
+ :math:`\log(p) = \log(0) = -\infty` and its maximum value of :math:`r` at
1374
+ :math:`\log(p) = \log(1) = 0`. Because the log-CDF has range
1375
+ :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
1376
+ negative reals; for :math:`\log(p) > 0`, `ilogcdf` returns ``nan``.
1377
+
1378
+ Occasionally, it is needed to find the argument of the CDF for which
1379
+ the resulting probability is very close to ``0`` or ``1`` - too close to
1380
+ represent accurately with floating point arithmetic. In many cases,
1381
+ however, the *logarithm* of this resulting probability may be
1382
+ represented in floating point arithmetic, in which case this function
1383
+ may be used to find the argument of the CDF for which the *logarithm*
1384
+ of the resulting probability is :math:`y = \log(p)`.
1385
+
1386
+ The "logarithmic complement" of a number :math:`z` is mathematically
1387
+ equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
1388
+ of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
1389
+
1390
+ Examples
1391
+ --------
1392
+ Instantiate a distribution with the desired parameters:
1393
+
1394
+ >>> import numpy as np
1395
+ >>> from scipy import stats
1396
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1397
+
1398
+ Evaluate the inverse log-CDF at the desired argument:
1399
+
1400
+ >>> X.ilogcdf(-0.25)
1401
+ 0.2788007830714034
1402
+ >>> np.allclose(X.ilogcdf(-0.25), X.icdf(np.exp(-0.25)))
1403
+ True
1404
+
1405
+ """
1406
+ raise NotImplementedError()
1407
+
1408
+ @abstractmethod
1409
+ def logccdf(self, x, y, /, *, method):
1410
+ r"""Log of the complementary cumulative distribution function
1411
+
1412
+ The complementary cumulative distribution function ("CCDF"), denoted
1413
+ :math:`G(x)` is the complement of the cumulative distribution function
1414
+ :math:`F(x)`; i.e., probability the random variable :math:`X` will
1415
+ assume a value greater than :math:`x`:
1416
+
1417
+ .. math::
1418
+
1419
+ G(x) = 1 - F(x) = P(X > x)
1420
+
1421
+ A two-argument variant of this function is:
1422
+
1423
+ .. math::
1424
+
1425
+ G(x, y) = 1 - F(x, y) = P(X < x \quad \text{or} \quad X > y)
1426
+
1427
+ `logccdf` computes the logarithm of the complementary cumulative
1428
+ distribution function ("log-CCDF"), :math:`\log(G(x))`/:math:`\log(G(x, y))`,
1429
+ but it may be numerically favorable compared to the naive implementation
1430
+ (computing the CDF and taking the logarithm).
1431
+
1432
+ `logccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
1433
+
1434
+ Parameters
1435
+ ----------
1436
+ x, y : array_like
1437
+ The arguments of the log-CCDF. `x` is required; `y` is optional.
1438
+ method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
1439
+ The strategy used to evaluate the log-CCDF.
1440
+ By default (``None``), the one-argument form of the function
1441
+ chooses between the following options, listed in order of precedence.
1442
+
1443
+ - ``'formula'``: use a formula for the log CCDF itself
1444
+ - ``'logexp'``: evaluate the CCDF and take the logarithm
1445
+ - ``'complement'``: evaluate the log-CDF and take the
1446
+ logarithmic complement (see Notes)
1447
+ - ``'quadrature'``: numerically log-integrate the log-PDF
1448
+
1449
+ The two-argument form chooses between:
1450
+
1451
+ - ``'formula'``: use a formula for the log CCDF itself
1452
+ - ``'addition'``: compute the log-CDF at `x` and the log-CCDF at `y`,
1453
+ then take the logarithmic sum (see Notes)
1454
+
1455
+ Not all `method` options are available for all distributions.
1456
+ If the selected `method` is not available, a ``NotImplementedError``
1457
+ will be raised.
1458
+
1459
+ Returns
1460
+ -------
1461
+ out : array
1462
+ The log-CCDF evaluated at the provided argument(s).
1463
+
1464
+ See Also
1465
+ --------
1466
+ ccdf
1467
+ logcdf
1468
+
1469
+ Notes
1470
+ -----
1471
+ Suppose a continuous probability distribution has support :math:`[l, r]`.
1472
+ The log-CCDF returns its minimum value of :math:`\log(0)=-\infty` for
1473
+ :math:`x ≥ r` and its maximum value of :math:`\log(1) = 0` for
1474
+ :math:`x ≤ l`.
1475
+
1476
+ For distributions with infinite support, it is common for
1477
+ `ccdf` to return a value of ``0`` when the argument
1478
+ is theoretically within the support; this can occur because the true value
1479
+ of the CCDF is too small to be represented by the chosen dtype. The log
1480
+ of the CCDF, however, will often be finite (not ``-inf``) over a much larger
1481
+ domain. Similarly, `logccdf` may provided a strictly negative result with
1482
+ arguments for which `ccdf` would return ``1.0``. Consequently, it may be
1483
+ preferred to work with the logarithms of probabilities to avoid underflow
1484
+ and related limitations of floating point numbers.
1485
+
1486
+ The "logarithmic complement" of a number :math:`z` is mathematically
1487
+ equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
1488
+ of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
1489
+ Similarly, the term "logarithmic sum" of :math:`w` and :math:`z`
1490
+ is used here to mean the :math:`\log(\exp(w)+\exp(z))`, AKA
1491
+ :math:`\text{LogSumExp}(w, z)`.
1492
+
1493
+ References
1494
+ ----------
1495
+ .. [1] Cumulative distribution function, *Wikipedia*,
1496
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
1497
+
1498
+ Examples
1499
+ --------
1500
+ Instantiate a distribution with the desired parameters:
1501
+
1502
+ >>> import numpy as np
1503
+ >>> from scipy import stats
1504
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1505
+
1506
+ Evaluate the log-CCDF at the desired argument:
1507
+
1508
+ >>> X.logccdf(0.25)
1509
+ -1.3862943611198906
1510
+ >>> np.allclose(X.logccdf(0.), np.log(X.ccdf(0.)))
1511
+ True
1512
+
1513
+ """ # noqa: E501
1514
+ raise NotImplementedError()
1515
+
1516
+ @abstractmethod
1517
+ def ilogccdf(self, logp, /, *, method):
1518
+ r"""Inverse of the log of the complementary cumulative distribution function.
1519
+
1520
+ The inverse of the logarithm of the complementary cumulative distribution
1521
+ function ("inverse log-CCDF") is the argument :math:`x` for which the logarithm
1522
+ of the complementary cumulative distribution function :math:`\log(G(x))`
1523
+ evaluates to :math:`\log(p)`.
1524
+
1525
+ Mathematically, it is equivalent to :math:`G^{-1}(\exp(y))`, where
1526
+ :math:`y = \log(p)`, but it may be numerically favorable compared to the naive
1527
+ implementation (computing :math:`p = \exp(y)`, then :math:`G^{-1}(p)`).
1528
+
1529
+ `ilogccdf` accepts `logp` for :math:`\log(p) ≤ 0`.
1530
+
1531
+ Parameters
1532
+ ----------
1533
+ x : array_like
1534
+ The argument of the inverse log-CCDF.
1535
+ method : {None, 'formula', 'complement', 'inversion'}
1536
+ The strategy used to evaluate the inverse log-CCDF.
1537
+ By default (``None``), the infrastructure chooses between the
1538
+ following options, listed in order of precedence.
1539
+
1540
+ - ``'formula'``: use a formula for the inverse log-CCDF itself
1541
+ - ``'complement'``: evaluate the inverse log-CDF at the
1542
+ logarithmic complement of `x` (see Notes)
1543
+ - ``'inversion'``: solve numerically for the argument at which the
1544
+ log-CCDF is equal to `x`
1545
+
1546
+ Not all `method` options are available for all distributions.
1547
+ If the selected `method` is not available, a ``NotImplementedError``
1548
+ will be raised.
1549
+
1550
+ Returns
1551
+ -------
1552
+ out : array
1553
+ The inverse log-CCDF evaluated at the provided argument.
1554
+
1555
+ Notes
1556
+ -----
1557
+ Suppose a continuous probability distribution has support :math:`[l, r]`. The
1558
+ inverse log-CCDF returns its minimum value of :math:`l` at
1559
+ :math:`\log(p) = \log(1) = 0` and its maximum value of :math:`r` at
1560
+ :math:`\log(p) = \log(0) = -\infty`. Because the log-CCDF has range
1561
+ :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
1562
+ negative reals; for :math:`\log(p) > 0`, `ilogccdf` returns ``nan``.
1563
+
1564
+ Occasionally, it is needed to find the argument of the CCDF for which
1565
+ the resulting probability is very close to ``0`` or ``1`` - too close to
1566
+ represent accurately with floating point arithmetic. In many cases,
1567
+ however, the *logarithm* of this resulting probability may be
1568
+ represented in floating point arithmetic, in which case this function
1569
+ may be used to find the argument of the CCDF for which the *logarithm*
1570
+ of the resulting probability is `y = \log(p)`.
1571
+
1572
+ The "logarithmic complement" of a number :math:`z` is mathematically
1573
+ equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
1574
+ of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
1575
+
1576
+ See Also
1577
+ --------
1578
+ iccdf
1579
+ ilogccdf
1580
+
1581
+ Examples
1582
+ --------
1583
+ Instantiate a distribution with the desired parameters:
1584
+
1585
+ >>> import numpy as np
1586
+ >>> from scipy import stats
1587
+ >>> X = stats.Uniform(a=-0.5, b=0.5)
1588
+
1589
+ Evaluate the inverse log-CCDF at the desired argument:
1590
+
1591
+ >>> X.ilogccdf(-0.25)
1592
+ -0.2788007830714034
1593
+ >>> np.allclose(X.ilogccdf(-0.25), X.iccdf(np.exp(-0.25)))
1594
+ True
1595
+
1596
+ """
1597
+ raise NotImplementedError()
1598
+
1599
+ @abstractmethod
1600
+ def logentropy(self, *, method):
1601
+ r"""Logarithm of the differential entropy
1602
+
1603
+ In terms of probability density function :math:`f(x)` and support
1604
+ :math:`\chi`, the differential entropy (or simply "entropy") of a random
1605
+ variable :math:`X` is:
1606
+
1607
+ .. math::
1608
+
1609
+ h(X) = - \int_{\chi} f(x) \log f(x) dx
1610
+
1611
+ `logentropy` computes the logarithm of the differential entropy
1612
+ ("log-entropy"), :math:`log(h(X))`, but it may be numerically favorable
1613
+ compared to the naive implementation (computing :math:`h(X)` then
1614
+ taking the logarithm).
1615
+
1616
+ Parameters
1617
+ ----------
1618
+ method : {None, 'formula', 'logexp', 'quadrature}
1619
+ The strategy used to evaluate the log-entropy. By default
1620
+ (``None``), the infrastructure chooses between the following options,
1621
+ listed in order of precedence.
1622
+
1623
+ - ``'formula'``: use a formula for the log-entropy itself
1624
+ - ``'logexp'``: evaluate the entropy and take the logarithm
1625
+ - ``'quadrature'``: numerically log-integrate the logarithm of the
1626
+ entropy integrand
1627
+
1628
+ Not all `method` options are available for all distributions.
1629
+ If the selected `method` is not available, a ``NotImplementedError``
1630
+ will be raised.
1631
+
1632
+ Returns
1633
+ -------
1634
+ out : array
1635
+ The log-entropy.
1636
+
1637
+ See Also
1638
+ --------
1639
+ entropy
1640
+ logpdf
1641
+
1642
+ Notes
1643
+ -----
1644
+ If the entropy of a distribution is negative, then the log-entropy
1645
+ is complex with imaginary part :math:`\pi`. For
1646
+ consistency, the result of this function always has complex dtype,
1647
+ regardless of the value of the imaginary part.
1648
+
1649
+ References
1650
+ ----------
1651
+ .. [1] Differential entropy, *Wikipedia*,
1652
+ https://en.wikipedia.org/wiki/Differential_entropy
1653
+
1654
+ Examples
1655
+ --------
1656
+ Instantiate a distribution with the desired parameters:
1657
+
1658
+ >>> import numpy as np
1659
+ >>> from scipy import stats
1660
+ >>> X = stats.Uniform(a=-1., b=1.)
1661
+
1662
+ Evaluate the log-entropy:
1663
+
1664
+ >>> X.logentropy()
1665
+ (-0.3665129205816642+0j)
1666
+ >>> np.allclose(np.exp(X.logentropy()), X.entropy())
1667
+ True
1668
+
1669
+ For a random variable with negative entropy, the log-entropy has an
1670
+ imaginary part equal to `np.pi`.
1671
+
1672
+ >>> X = stats.Uniform(a=-.1, b=.1)
1673
+ >>> X.entropy(), X.logentropy()
1674
+ (-1.6094379124341007, (0.4758849953271105+3.141592653589793j))
1675
+
1676
+ """
1677
+ raise NotImplementedError()
1678
+
1679
+ @abstractmethod
1680
+ def entropy(self, *, method):
1681
+ r"""Differential entropy
1682
+
1683
+ In terms of probability density function :math:`f(x)` and support
1684
+ :math:`\chi`, the differential entropy (or simply "entropy") of a
1685
+ continuous random variable :math:`X` is:
1686
+
1687
+ .. math::
1688
+
1689
+ h(X) = - \int_{\chi} f(x) \log f(x) dx
1690
+
1691
+ Parameters
1692
+ ----------
1693
+ method : {None, 'formula', 'logexp', 'quadrature'}
1694
+ The strategy used to evaluate the entropy. By default (``None``),
1695
+ the infrastructure chooses between the following options, listed
1696
+ in order of precedence.
1697
+
1698
+ - ``'formula'``: use a formula for the entropy itself
1699
+ - ``'logexp'``: evaluate the log-entropy and exponentiate
1700
+ - ``'quadrature'``: use numerical integration
1701
+
1702
+ Not all `method` options are available for all distributions.
1703
+ If the selected `method` is not available, a ``NotImplementedError``
1704
+ will be raised.
1705
+
1706
+ Returns
1707
+ -------
1708
+ out : array
1709
+ The entropy of the random variable.
1710
+
1711
+ See Also
1712
+ --------
1713
+ logentropy
1714
+ pdf
1715
+
1716
+ Notes
1717
+ -----
1718
+ This function calculates the entropy using the natural logarithm; i.e.
1719
+ the logarithm with base :math:`e`. Consequently, the value is expressed
1720
+ in (dimensionless) "units" of nats. To convert the entropy to different
1721
+ units (i.e. corresponding with a different base), divide the result by
1722
+ the natural logarithm of the desired base.
1723
+
1724
+ References
1725
+ ----------
1726
+ .. [1] Differential entropy, *Wikipedia*,
1727
+ https://en.wikipedia.org/wiki/Differential_entropy
1728
+
1729
+ Examples
1730
+ --------
1731
+ Instantiate a distribution with the desired parameters:
1732
+
1733
+ >>> from scipy import stats
1734
+ >>> X = stats.Uniform(a=-1., b=1.)
1735
+
1736
+ Evaluate the entropy:
1737
+
1738
+ >>> X.entropy()
1739
+ 0.6931471805599454
1740
+
1741
+ """
1742
+ raise NotImplementedError()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc.py ADDED
The diff for this file is too large to render. See raw diff
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc_cy.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ef4ada87fbe243b9102c23d6f70c6a6c823937fa0189b4dc5ae9dca97fe3d7d
3
+ size 291392
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmc_cy.pyi ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._util import DecimalNumber, IntNumber
3
+
4
+
5
+ def _cy_wrapper_centered_discrepancy(
6
+ sample: np.ndarray,
7
+ iterative: bool,
8
+ workers: IntNumber,
9
+ ) -> float: ...
10
+
11
+
12
+ def _cy_wrapper_wrap_around_discrepancy(
13
+ sample: np.ndarray,
14
+ iterative: bool,
15
+ workers: IntNumber,
16
+ ) -> float: ...
17
+
18
+
19
+ def _cy_wrapper_mixture_discrepancy(
20
+ sample: np.ndarray,
21
+ iterative: bool,
22
+ workers: IntNumber,
23
+ ) -> float: ...
24
+
25
+
26
+ def _cy_wrapper_l2_star_discrepancy(
27
+ sample: np.ndarray,
28
+ iterative: bool,
29
+ workers: IntNumber,
30
+ ) -> float: ...
31
+
32
+
33
+ def _cy_wrapper_update_discrepancy(
34
+ x_new_view: np.ndarray,
35
+ sample_view: np.ndarray,
36
+ initial_disc: DecimalNumber,
37
+ ) -> float: ...
38
+
39
+
40
+ def _cy_van_der_corput(
41
+ n: IntNumber,
42
+ base: IntNumber,
43
+ start_index: IntNumber,
44
+ workers: IntNumber,
45
+ ) -> np.ndarray: ...
46
+
47
+
48
+ def _cy_van_der_corput_scrambled(
49
+ n: IntNumber,
50
+ base: IntNumber,
51
+ start_index: IntNumber,
52
+ permutations: np.ndarray,
53
+ workers: IntNumber,
54
+ ) -> np.ndarray: ...
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_qmvnt.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Integration of multivariate normal and t distributions.
2
+
3
+ # Adapted from the MATLAB original implementations by Dr. Alan Genz.
4
+
5
+ # http://www.math.wsu.edu/faculty/genz/software/software.html
6
+
7
+ # Copyright (C) 2013, Alan Genz, All rights reserved.
8
+ # Python implementation is copyright (C) 2022, Robert Kern, All rights
9
+ # reserved.
10
+
11
+ # Redistribution and use in source and binary forms, with or without
12
+ # modification, are permitted provided the following conditions are met:
13
+ # 1. Redistributions of source code must retain the above copyright
14
+ # notice, this list of conditions and the following disclaimer.
15
+ # 2. Redistributions in binary form must reproduce the above copyright
16
+ # notice, this list of conditions and the following disclaimer in
17
+ # the documentation and/or other materials provided with the
18
+ # distribution.
19
+ # 3. The contributor name(s) may not be used to endorse or promote
20
+ # products derived from this software without specific prior
21
+ # written permission.
22
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
+ # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
29
+ # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30
+ # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
31
+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE
32
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+
35
+ import numpy as np
36
+
37
+ from scipy.fft import fft, ifft
38
+ from scipy.special import gammaincinv, ndtr, ndtri
39
+ from scipy.stats._qmc import primes_from_2_to
40
+
41
+
42
+ phi = ndtr
43
+ phinv = ndtri
44
+
45
+
46
+ def _factorize_int(n):
47
+ """Return a sorted list of the unique prime factors of a positive integer.
48
+ """
49
+ # NOTE: There are lots faster ways to do this, but this isn't terrible.
50
+ factors = set()
51
+ for p in primes_from_2_to(int(np.sqrt(n)) + 1):
52
+ while not (n % p):
53
+ factors.add(p)
54
+ n //= p
55
+ if n == 1:
56
+ break
57
+ if n != 1:
58
+ factors.add(n)
59
+ return sorted(factors)
60
+
61
+
62
+ def _primitive_root(p):
63
+ """Compute a primitive root of the prime number `p`.
64
+
65
+ Used in the CBC lattice construction.
66
+
67
+ References
68
+ ----------
69
+ .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n
70
+ """
71
+ # p is prime
72
+ pm = p - 1
73
+ factors = _factorize_int(pm)
74
+ n = len(factors)
75
+ r = 2
76
+ k = 0
77
+ while k < n:
78
+ d = pm // factors[k]
79
+ # pow() doesn't like numpy scalar types.
80
+ rd = pow(int(r), int(d), int(p))
81
+ if rd == 1:
82
+ r += 1
83
+ k = 0
84
+ else:
85
+ k += 1
86
+ return r
87
+
88
+
89
+ def _cbc_lattice(n_dim, n_qmc_samples):
90
+ """Compute a QMC lattice generator using a Fast CBC construction.
91
+
92
+ Parameters
93
+ ----------
94
+ n_dim : int > 0
95
+ The number of dimensions for the lattice.
96
+ n_qmc_samples : int > 0
97
+ The desired number of QMC samples. This will be rounded down to the
98
+ nearest prime to enable the CBC construction.
99
+
100
+ Returns
101
+ -------
102
+ q : float array : shape=(n_dim,)
103
+ The lattice generator vector. All values are in the open interval
104
+ ``(0, 1)``.
105
+ actual_n_qmc_samples : int
106
+ The prime number of QMC samples that must be used with this lattice,
107
+ no more, no less.
108
+
109
+ References
110
+ ----------
111
+ .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction,
112
+ a Reprise for Different Kernels", In H. Niederreiter and D. Talay,
113
+ editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004,
114
+ Springer-Verlag, 2006, 371-385.
115
+ """
116
+ # Round down to the nearest prime number.
117
+ primes = primes_from_2_to(n_qmc_samples + 1)
118
+ n_qmc_samples = primes[-1]
119
+
120
+ bt = np.ones(n_dim)
121
+ gm = np.hstack([1.0, 0.8 ** np.arange(n_dim - 1)])
122
+ q = 1
123
+ w = 0
124
+ z = np.arange(1, n_dim + 1)
125
+ m = (n_qmc_samples - 1) // 2
126
+ g = _primitive_root(n_qmc_samples)
127
+ # Slightly faster way to compute perm[j] = pow(g, j, n_qmc_samples)
128
+ # Shame that we don't have modulo pow() implemented as a ufunc.
129
+ perm = np.ones(m, dtype=int)
130
+ for j in range(m - 1):
131
+ perm[j + 1] = (g * perm[j]) % n_qmc_samples
132
+ perm = np.minimum(n_qmc_samples - perm, perm)
133
+ pn = perm / n_qmc_samples
134
+ c = pn * pn - pn + 1.0 / 6
135
+ fc = fft(c)
136
+ for s in range(1, n_dim):
137
+ reordered = np.hstack([
138
+ c[:w+1][::-1],
139
+ c[w+1:m][::-1],
140
+ ])
141
+ q = q * (bt[s-1] + gm[s-1] * reordered)
142
+ w = ifft(fc * fft(q)).real.argmin()
143
+ z[s] = perm[w]
144
+ q = z / n_qmc_samples
145
+ return q, n_qmc_samples
146
+
147
+
148
+ # Note: this function is not currently used or tested by any SciPy code. It is
149
+ # included in this file to facilitate the development of a parameter for users
150
+ # to set the desired CDF accuracy, but must be reviewed and tested before use.
151
+ def _qauto(func, covar, low, high, rng, error=1e-3, limit=10_000, **kwds):
152
+ """Automatically rerun the integration to get the required error bound.
153
+
154
+ Parameters
155
+ ----------
156
+ func : callable
157
+ Either :func:`_qmvn` or :func:`_qmvt`.
158
+ covar, low, high : array
159
+ As specified in :func:`_qmvn` and :func:`_qmvt`.
160
+ rng : Generator, optional
161
+ default_rng(), yada, yada
162
+ error : float > 0
163
+ The desired error bound.
164
+ limit : int > 0:
165
+ The rough limit of the number of integration points to consider. The
166
+ integration will stop looping once this limit has been *exceeded*.
167
+ **kwds :
168
+ Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be
169
+ sure to include ``nu=`` as one of these.
170
+
171
+ Returns
172
+ -------
173
+ prob : float
174
+ The estimated probability mass within the bounds.
175
+ est_error : float
176
+ 3 times the standard error of the batch estimates.
177
+ n_samples : int
178
+ The number of integration points actually used.
179
+ """
180
+ n = len(covar)
181
+ n_samples = 0
182
+ if n == 1:
183
+ prob = phi(high) - phi(low)
184
+ # More or less
185
+ est_error = 1e-15
186
+ else:
187
+ mi = min(limit, n * 1000)
188
+ prob = 0.0
189
+ est_error = 1.0
190
+ ei = 0.0
191
+ while est_error > error and n_samples < limit:
192
+ mi = round(np.sqrt(2) * mi)
193
+ pi, ei, ni = func(mi, covar, low, high, rng=rng, **kwds)
194
+ n_samples += ni
195
+ wt = 1.0 / (1 + (ei / est_error)**2)
196
+ prob += wt * (pi - prob)
197
+ est_error = np.sqrt(wt) * ei
198
+ return prob, est_error, n_samples
199
+
200
+
201
+ # Note: this function is not currently used or tested by any SciPy code. It is
202
+ # included in this file to facilitate the resolution of gh-8367, gh-16142, and
203
+ # possibly gh-14286, but must be reviewed and tested before use.
204
+ def _qmvn(m, covar, low, high, rng, lattice='cbc', n_batches=10):
205
+ """Multivariate normal integration over box bounds.
206
+
207
+ Parameters
208
+ ----------
209
+ m : int > n_batches
210
+ The number of points to sample. This number will be divided into
211
+ `n_batches` batches that apply random offsets of the sampling lattice
212
+ for each batch in order to estimate the error.
213
+ covar : (n, n) float array
214
+ Possibly singular, positive semidefinite symmetric covariance matrix.
215
+ low, high : (n,) float array
216
+ The low and high integration bounds.
217
+ rng : Generator, optional
218
+ default_rng(), yada, yada
219
+ lattice : 'cbc' or callable
220
+ The type of lattice rule to use to construct the integration points.
221
+ n_batches : int > 0, optional
222
+ The number of QMC batches to apply.
223
+
224
+ Returns
225
+ -------
226
+ prob : float
227
+ The estimated probability mass within the bounds.
228
+ est_error : float
229
+ 3 times the standard error of the batch estimates.
230
+ """
231
+ cho, lo, hi = _permuted_cholesky(covar, low, high)
232
+ n = cho.shape[0]
233
+ ct = cho[0, 0]
234
+ c = phi(lo[0] / ct)
235
+ d = phi(hi[0] / ct)
236
+ ci = c
237
+ dci = d - ci
238
+ prob = 0.0
239
+ error_var = 0.0
240
+ q, n_qmc_samples = _cbc_lattice(n - 1, max(m // n_batches, 1))
241
+ y = np.zeros((n - 1, n_qmc_samples))
242
+ i_samples = np.arange(n_qmc_samples) + 1
243
+ for j in range(n_batches):
244
+ c = np.full(n_qmc_samples, ci)
245
+ dc = np.full(n_qmc_samples, dci)
246
+ pv = dc.copy()
247
+ for i in range(1, n):
248
+ # Pseudorandomly-shifted lattice coordinate.
249
+ z = q[i - 1] * i_samples + rng.random()
250
+ # Fast remainder(z, 1.0)
251
+ z -= z.astype(int)
252
+ # Tent periodization transform.
253
+ x = abs(2 * z - 1)
254
+ y[i - 1, :] = phinv(c + x * dc)
255
+ s = cho[i, :i] @ y[:i, :]
256
+ ct = cho[i, i]
257
+ c = phi((lo[i] - s) / ct)
258
+ d = phi((hi[i] - s) / ct)
259
+ dc = d - c
260
+ pv = pv * dc
261
+ # Accumulate the mean and error variances with online formulations.
262
+ d = (pv.mean() - prob) / (j + 1)
263
+ prob += d
264
+ error_var = (j - 1) * error_var / (j + 1) + d * d
265
+ # Error bounds are 3 times the standard error of the estimates.
266
+ est_error = 3 * np.sqrt(error_var)
267
+ n_samples = n_qmc_samples * n_batches
268
+ return prob, est_error, n_samples
269
+
270
+
271
+ # Note: this function is not currently used or tested by any SciPy code. It is
272
+ # included in this file to facilitate the resolution of gh-8367, gh-16142, and
273
+ # possibly gh-14286, but must be reviewed and tested before use.
274
+ def _mvn_qmc_integrand(covar, low, high, use_tent=False):
275
+ """Transform the multivariate normal integration into a QMC integrand over
276
+ a unit hypercube.
277
+
278
+ The dimensionality of the resulting hypercube integration domain is one
279
+ less than the dimensionality of the original integrand. Note that this
280
+ transformation subsumes the integration bounds in order to account for
281
+ infinite bounds. The QMC integration one does with the returned integrand
282
+ should be on the unit hypercube.
283
+
284
+ Parameters
285
+ ----------
286
+ covar : (n, n) float array
287
+ Possibly singular, positive semidefinite symmetric covariance matrix.
288
+ low, high : (n,) float array
289
+ The low and high integration bounds.
290
+ use_tent : bool, optional
291
+ If True, then use tent periodization. Only helpful for lattice rules.
292
+
293
+ Returns
294
+ -------
295
+ integrand : Callable[[NDArray], NDArray]
296
+ The QMC-integrable integrand. It takes an
297
+ ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit
298
+ hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these
299
+ QMC points.
300
+ ndim_integrand : int
301
+ The dimensionality of the integrand. Equal to ``n-1``.
302
+ """
303
+ cho, lo, hi = _permuted_cholesky(covar, low, high)
304
+ n = cho.shape[0]
305
+ ndim_integrand = n - 1
306
+ ct = cho[0, 0]
307
+ c = phi(lo[0] / ct)
308
+ d = phi(hi[0] / ct)
309
+ ci = c
310
+ dci = d - ci
311
+
312
+ def integrand(*zs):
313
+ ndim_qmc = len(zs)
314
+ n_qmc_samples = len(np.atleast_1d(zs[0]))
315
+ assert ndim_qmc == ndim_integrand
316
+ y = np.zeros((ndim_qmc, n_qmc_samples))
317
+ c = np.full(n_qmc_samples, ci)
318
+ dc = np.full(n_qmc_samples, dci)
319
+ pv = dc.copy()
320
+ for i in range(1, n):
321
+ if use_tent:
322
+ # Tent periodization transform.
323
+ x = abs(2 * zs[i-1] - 1)
324
+ else:
325
+ x = zs[i-1]
326
+ y[i - 1, :] = phinv(c + x * dc)
327
+ s = cho[i, :i] @ y[:i, :]
328
+ ct = cho[i, i]
329
+ c = phi((lo[i] - s) / ct)
330
+ d = phi((hi[i] - s) / ct)
331
+ dc = d - c
332
+ pv = pv * dc
333
+ return pv
334
+
335
+ return integrand, ndim_integrand
336
+
337
+
338
+ def _qmvt(m, nu, covar, low, high, rng, lattice='cbc', n_batches=10):
339
+ """Multivariate t integration over box bounds.
340
+
341
+ Parameters
342
+ ----------
343
+ m : int > n_batches
344
+ The number of points to sample. This number will be divided into
345
+ `n_batches` batches that apply random offsets of the sampling lattice
346
+ for each batch in order to estimate the error.
347
+ nu : float >= 0
348
+ The shape parameter of the multivariate t distribution.
349
+ covar : (n, n) float array
350
+ Possibly singular, positive semidefinite symmetric covariance matrix.
351
+ low, high : (n,) float array
352
+ The low and high integration bounds.
353
+ rng : Generator, optional
354
+ default_rng(), yada, yada
355
+ lattice : 'cbc' or callable
356
+ The type of lattice rule to use to construct the integration points.
357
+ n_batches : int > 0, optional
358
+ The number of QMC batches to apply.
359
+
360
+ Returns
361
+ -------
362
+ prob : float
363
+ The estimated probability mass within the bounds.
364
+ est_error : float
365
+ 3 times the standard error of the batch estimates.
366
+ n_samples : int
367
+ The number of samples actually used.
368
+ """
369
+ sn = max(1.0, np.sqrt(nu))
370
+ low = np.asarray(low, dtype=np.float64)
371
+ high = np.asarray(high, dtype=np.float64)
372
+ cho, lo, hi = _permuted_cholesky(covar, low / sn, high / sn)
373
+ n = cho.shape[0]
374
+ prob = 0.0
375
+ error_var = 0.0
376
+ q, n_qmc_samples = _cbc_lattice(n, max(m // n_batches, 1))
377
+ i_samples = np.arange(n_qmc_samples) + 1
378
+ for j in range(n_batches):
379
+ pv = np.ones(n_qmc_samples)
380
+ s = np.zeros((n, n_qmc_samples))
381
+ for i in range(n):
382
+ # Pseudorandomly-shifted lattice coordinate.
383
+ z = q[i] * i_samples + rng.random()
384
+ # Fast remainder(z, 1.0)
385
+ z -= z.astype(int)
386
+ # Tent periodization transform.
387
+ x = abs(2 * z - 1)
388
+ # FIXME: Lift the i==0 case out of the loop to make the logic
389
+ # easier to follow.
390
+ if i == 0:
391
+ # We'll use one of the QR variates to pull out the
392
+ # t-distribution scaling.
393
+ if nu > 0:
394
+ r = np.sqrt(2 * gammaincinv(nu / 2, x))
395
+ else:
396
+ r = np.ones_like(x)
397
+ else:
398
+ y = phinv(c + x * dc) # noqa: F821
399
+ with np.errstate(invalid='ignore'):
400
+ s[i:, :] += cho[i:, i - 1][:, np.newaxis] * y
401
+ si = s[i, :]
402
+
403
+ c = np.ones(n_qmc_samples)
404
+ d = np.ones(n_qmc_samples)
405
+ with np.errstate(invalid='ignore'):
406
+ lois = lo[i] * r - si
407
+ hiis = hi[i] * r - si
408
+ c[lois < -9] = 0.0
409
+ d[hiis < -9] = 0.0
410
+ lo_mask = abs(lois) < 9
411
+ hi_mask = abs(hiis) < 9
412
+ c[lo_mask] = phi(lois[lo_mask])
413
+ d[hi_mask] = phi(hiis[hi_mask])
414
+
415
+ dc = d - c
416
+ pv *= dc
417
+
418
+ # Accumulate the mean and error variances with online formulations.
419
+ d = (pv.mean() - prob) / (j + 1)
420
+ prob += d
421
+ error_var = (j - 1) * error_var / (j + 1) + d * d
422
+ # Error bounds are 3 times the standard error of the estimates.
423
+ est_error = 3 * np.sqrt(error_var)
424
+ n_samples = n_qmc_samples * n_batches
425
+ return prob, est_error, n_samples
426
+
427
+
428
+ def _permuted_cholesky(covar, low, high, tol=1e-10):
429
+ """Compute a scaled, permuted Cholesky factor, with integration bounds.
430
+
431
+ The scaling and permuting of the dimensions accomplishes part of the
432
+ transformation of the original integration problem into a more numerically
433
+ tractable form. The lower-triangular Cholesky factor will then be used in
434
+ the subsequent integration. The integration bounds will be scaled and
435
+ permuted as well.
436
+
437
+ Parameters
438
+ ----------
439
+ covar : (n, n) float array
440
+ Possibly singular, positive semidefinite symmetric covariance matrix.
441
+ low, high : (n,) float array
442
+ The low and high integration bounds.
443
+ tol : float, optional
444
+ The singularity tolerance.
445
+
446
+ Returns
447
+ -------
448
+ cho : (n, n) float array
449
+ Lower Cholesky factor, scaled and permuted.
450
+ new_low, new_high : (n,) float array
451
+ The scaled and permuted low and high integration bounds.
452
+ """
453
+ # Make copies for outputting.
454
+ cho = np.array(covar, dtype=np.float64)
455
+ new_lo = np.array(low, dtype=np.float64)
456
+ new_hi = np.array(high, dtype=np.float64)
457
+ n = cho.shape[0]
458
+ if cho.shape != (n, n):
459
+ raise ValueError("expected a square symmetric array")
460
+ if new_lo.shape != (n,) or new_hi.shape != (n,):
461
+ raise ValueError(
462
+ "expected integration boundaries the same dimensions "
463
+ "as the covariance matrix"
464
+ )
465
+ # Scale by the sqrt of the diagonal.
466
+ dc = np.sqrt(np.maximum(np.diag(cho), 0.0))
467
+ # But don't divide by 0.
468
+ dc[dc == 0.0] = 1.0
469
+ new_lo /= dc
470
+ new_hi /= dc
471
+ cho /= dc
472
+ cho /= dc[:, np.newaxis]
473
+
474
+ y = np.zeros(n)
475
+ sqtp = np.sqrt(2 * np.pi)
476
+ for k in range(n):
477
+ epk = (k + 1) * tol
478
+ im = k
479
+ ck = 0.0
480
+ dem = 1.0
481
+ s = 0.0
482
+ lo_m = 0.0
483
+ hi_m = 0.0
484
+ for i in range(k, n):
485
+ if cho[i, i] > tol:
486
+ ci = np.sqrt(cho[i, i])
487
+ if i > 0:
488
+ s = cho[i, :k] @ y[:k]
489
+ lo_i = (new_lo[i] - s) / ci
490
+ hi_i = (new_hi[i] - s) / ci
491
+ de = phi(hi_i) - phi(lo_i)
492
+ if de <= dem:
493
+ ck = ci
494
+ dem = de
495
+ lo_m = lo_i
496
+ hi_m = hi_i
497
+ im = i
498
+ if im > k:
499
+ # Swap im and k
500
+ cho[im, im] = cho[k, k]
501
+ _swap_slices(cho, np.s_[im, :k], np.s_[k, :k])
502
+ _swap_slices(cho, np.s_[im + 1:, im], np.s_[im + 1:, k])
503
+ _swap_slices(cho, np.s_[k + 1:im, k], np.s_[im, k + 1:im])
504
+ _swap_slices(new_lo, k, im)
505
+ _swap_slices(new_hi, k, im)
506
+ if ck > epk:
507
+ cho[k, k] = ck
508
+ cho[k, k + 1:] = 0.0
509
+ for i in range(k + 1, n):
510
+ cho[i, k] /= ck
511
+ cho[i, k + 1:i + 1] -= cho[i, k] * cho[k + 1:i + 1, k]
512
+ if abs(dem) > tol:
513
+ y[k] = ((np.exp(-lo_m * lo_m / 2) - np.exp(-hi_m * hi_m / 2)) /
514
+ (sqtp * dem))
515
+ else:
516
+ y[k] = (lo_m + hi_m) / 2
517
+ if lo_m < -10:
518
+ y[k] = hi_m
519
+ elif hi_m > 10:
520
+ y[k] = lo_m
521
+ cho[k, :k + 1] /= ck
522
+ new_lo[k] /= ck
523
+ new_hi[k] /= ck
524
+ else:
525
+ cho[k:, k] = 0.0
526
+ y[k] = (new_lo[k] + new_hi[k]) / 2
527
+ return cho, new_lo, new_hi
528
+
529
+
530
+ def _swap_slices(x, slc1, slc2):
531
+ t = x[slc1].copy()
532
+ x[slc1] = x[slc2].copy()
533
+ x[slc2] = t
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #
2
+ from .rcont import rvs_rcont1, rvs_rcont2
3
+
4
+ __all__ = ["rvs_rcont1", "rvs_rcont2"]
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (317 Bytes). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_rcont/rcont.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e610110fb0cc6c9450a9777a92e701edf6747606372423dad28c004c78b2c2df
3
+ size 259200
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_relative_risk.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from dataclasses import dataclass
3
+ import numpy as np
4
+ from scipy.special import ndtri
5
+ from ._common import ConfidenceInterval
6
+
7
+
8
+ def _validate_int(n, bound, name):
9
+ msg = f'{name} must be an integer not less than {bound}, but got {n!r}'
10
+ try:
11
+ n = operator.index(n)
12
+ except TypeError:
13
+ raise TypeError(msg) from None
14
+ if n < bound:
15
+ raise ValueError(msg)
16
+ return n
17
+
18
+
19
+ @dataclass
20
+ class RelativeRiskResult:
21
+ """
22
+ Result of `scipy.stats.contingency.relative_risk`.
23
+
24
+ Attributes
25
+ ----------
26
+ relative_risk : float
27
+ This is::
28
+
29
+ (exposed_cases/exposed_total) / (control_cases/control_total)
30
+
31
+ exposed_cases : int
32
+ The number of "cases" (i.e. occurrence of disease or other event
33
+ of interest) among the sample of "exposed" individuals.
34
+ exposed_total : int
35
+ The total number of "exposed" individuals in the sample.
36
+ control_cases : int
37
+ The number of "cases" among the sample of "control" or non-exposed
38
+ individuals.
39
+ control_total : int
40
+ The total number of "control" individuals in the sample.
41
+
42
+ Methods
43
+ -------
44
+ confidence_interval :
45
+ Compute the confidence interval for the relative risk estimate.
46
+ """
47
+
48
+ relative_risk: float
49
+ exposed_cases: int
50
+ exposed_total: int
51
+ control_cases: int
52
+ control_total: int
53
+
54
+ def confidence_interval(self, confidence_level=0.95):
55
+ """
56
+ Compute the confidence interval for the relative risk.
57
+
58
+ The confidence interval is computed using the Katz method
59
+ (i.e. "Method C" of [1]_; see also [2]_, section 3.1.2).
60
+
61
+ Parameters
62
+ ----------
63
+ confidence_level : float, optional
64
+ The confidence level to use for the confidence interval.
65
+ Default is 0.95.
66
+
67
+ Returns
68
+ -------
69
+ ci : ConfidenceInterval instance
70
+ The return value is an object with attributes ``low`` and
71
+ ``high`` that hold the confidence interval.
72
+
73
+ References
74
+ ----------
75
+ .. [1] D. Katz, J. Baptista, S. P. Azen and M. C. Pike, "Obtaining
76
+ confidence intervals for the risk ratio in cohort studies",
77
+ Biometrics, 34, 469-474 (1978).
78
+ .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
79
+ CRC Press LLC, Boca Raton, FL, USA (1996).
80
+
81
+
82
+ Examples
83
+ --------
84
+ >>> from scipy.stats.contingency import relative_risk
85
+ >>> result = relative_risk(exposed_cases=10, exposed_total=75,
86
+ ... control_cases=12, control_total=225)
87
+ >>> result.relative_risk
88
+ 2.5
89
+ >>> result.confidence_interval()
90
+ ConfidenceInterval(low=1.1261564003469628, high=5.549850800541033)
91
+ """
92
+ if not 0 <= confidence_level <= 1:
93
+ raise ValueError('confidence_level must be in the interval '
94
+ '[0, 1].')
95
+
96
+ # Handle edge cases where either exposed_cases or control_cases
97
+ # is zero. We follow the convention of the R function riskratio
98
+ # from the epitools library.
99
+ if self.exposed_cases == 0 and self.control_cases == 0:
100
+ # relative risk is nan.
101
+ return ConfidenceInterval(low=np.nan, high=np.nan)
102
+ elif self.exposed_cases == 0:
103
+ # relative risk is 0.
104
+ return ConfidenceInterval(low=0.0, high=np.nan)
105
+ elif self.control_cases == 0:
106
+ # relative risk is inf
107
+ return ConfidenceInterval(low=np.nan, high=np.inf)
108
+
109
+ alpha = 1 - confidence_level
110
+ z = ndtri(1 - alpha/2)
111
+ rr = self.relative_risk
112
+
113
+ # Estimate of the variance of log(rr) is
114
+ # var(log(rr)) = 1/exposed_cases - 1/exposed_total +
115
+ # 1/control_cases - 1/control_total
116
+ # and the standard error is the square root of that.
117
+ se = np.sqrt(1/self.exposed_cases - 1/self.exposed_total +
118
+ 1/self.control_cases - 1/self.control_total)
119
+ delta = z*se
120
+ katz_lo = rr*np.exp(-delta)
121
+ katz_hi = rr*np.exp(delta)
122
+ return ConfidenceInterval(low=katz_lo, high=katz_hi)
123
+
124
+
125
+ def relative_risk(exposed_cases, exposed_total, control_cases, control_total):
126
+ """
127
+ Compute the relative risk (also known as the risk ratio).
128
+
129
+ This function computes the relative risk associated with a 2x2
130
+ contingency table ([1]_, section 2.2.3; [2]_, section 3.1.2). Instead
131
+ of accepting a table as an argument, the individual numbers that are
132
+ used to compute the relative risk are given as separate parameters.
133
+ This is to avoid the ambiguity of which row or column of the contingency
134
+ table corresponds to the "exposed" cases and which corresponds to the
135
+ "control" cases. Unlike, say, the odds ratio, the relative risk is not
136
+ invariant under an interchange of the rows or columns.
137
+
138
+ Parameters
139
+ ----------
140
+ exposed_cases : nonnegative int
141
+ The number of "cases" (i.e. occurrence of disease or other event
142
+ of interest) among the sample of "exposed" individuals.
143
+ exposed_total : positive int
144
+ The total number of "exposed" individuals in the sample.
145
+ control_cases : nonnegative int
146
+ The number of "cases" among the sample of "control" or non-exposed
147
+ individuals.
148
+ control_total : positive int
149
+ The total number of "control" individuals in the sample.
150
+
151
+ Returns
152
+ -------
153
+ result : instance of `~scipy.stats._result_classes.RelativeRiskResult`
154
+ The object has the float attribute ``relative_risk``, which is::
155
+
156
+ rr = (exposed_cases/exposed_total) / (control_cases/control_total)
157
+
158
+ The object also has the method ``confidence_interval`` to compute
159
+ the confidence interval of the relative risk for a given confidence
160
+ level.
161
+
162
+ See Also
163
+ --------
164
+ odds_ratio
165
+
166
+ Notes
167
+ -----
168
+ The R package epitools has the function `riskratio`, which accepts
169
+ a table with the following layout::
170
+
171
+ disease=0 disease=1
172
+ exposed=0 (ref) n00 n01
173
+ exposed=1 n10 n11
174
+
175
+ With a 2x2 table in the above format, the estimate of the CI is
176
+ computed by `riskratio` when the argument method="wald" is given,
177
+ or with the function `riskratio.wald`.
178
+
179
+ For example, in a test of the incidence of lung cancer among a
180
+ sample of smokers and nonsmokers, the "exposed" category would
181
+ correspond to "is a smoker" and the "disease" category would
182
+ correspond to "has or had lung cancer".
183
+
184
+ To pass the same data to ``relative_risk``, use::
185
+
186
+ relative_risk(n11, n10 + n11, n01, n00 + n01)
187
+
188
+ .. versionadded:: 1.7.0
189
+
190
+ References
191
+ ----------
192
+ .. [1] Alan Agresti, An Introduction to Categorical Data Analysis
193
+ (second edition), Wiley, Hoboken, NJ, USA (2007).
194
+ .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
195
+ CRC Press LLC, Boca Raton, FL, USA (1996).
196
+
197
+ Examples
198
+ --------
199
+ >>> from scipy.stats.contingency import relative_risk
200
+
201
+ This example is from Example 3.1 of [2]_. The results of a heart
202
+ disease study are summarized in the following table::
203
+
204
+ High CAT Low CAT Total
205
+ -------- ------- -----
206
+ CHD 27 44 71
207
+ No CHD 95 443 538
208
+
209
+ Total 122 487 609
210
+
211
+ CHD is coronary heart disease, and CAT refers to the level of
212
+ circulating catecholamine. CAT is the "exposure" variable, and
213
+ high CAT is the "exposed" category. So the data from the table
214
+ to be passed to ``relative_risk`` is::
215
+
216
+ exposed_cases = 27
217
+ exposed_total = 122
218
+ control_cases = 44
219
+ control_total = 487
220
+
221
+ >>> result = relative_risk(27, 122, 44, 487)
222
+ >>> result.relative_risk
223
+ 2.4495156482861398
224
+
225
+ Find the confidence interval for the relative risk.
226
+
227
+ >>> result.confidence_interval(confidence_level=0.95)
228
+ ConfidenceInterval(low=1.5836990926700116, high=3.7886786315466354)
229
+
230
+ The interval does not contain 1, so the data supports the statement
231
+ that high CAT is associated with greater risk of CHD.
232
+ """
233
+ # Relative risk is a trivial calculation. The nontrivial part is in the
234
+ # `confidence_interval` method of the RelativeRiskResult class.
235
+
236
+ exposed_cases = _validate_int(exposed_cases, 0, "exposed_cases")
237
+ exposed_total = _validate_int(exposed_total, 1, "exposed_total")
238
+ control_cases = _validate_int(control_cases, 0, "control_cases")
239
+ control_total = _validate_int(control_total, 1, "control_total")
240
+
241
+ if exposed_cases > exposed_total:
242
+ raise ValueError('exposed_cases must not exceed exposed_total.')
243
+ if control_cases > control_total:
244
+ raise ValueError('control_cases must not exceed control_total.')
245
+
246
+ if exposed_cases == 0 and control_cases == 0:
247
+ # relative risk is 0/0.
248
+ rr = np.nan
249
+ elif exposed_cases == 0:
250
+ # relative risk is 0/nonzero
251
+ rr = 0.0
252
+ elif control_cases == 0:
253
+ # relative risk is nonzero/0.
254
+ rr = np.inf
255
+ else:
256
+ p1 = exposed_cases / exposed_total
257
+ p2 = control_cases / control_total
258
+ rr = p1 / p2
259
+ return RelativeRiskResult(relative_risk=rr,
260
+ exposed_cases=exposed_cases,
261
+ exposed_total=exposed_total,
262
+ control_cases=control_cases,
263
+ control_total=control_total)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_resampling.py ADDED
The diff for this file is too large to render. See raw diff
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_result_classes.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module exists only to allow Sphinx to generate docs
2
+ # for the result objects returned by some functions in stats
3
+ # _without_ adding them to the main stats documentation page.
4
+
5
+ """
6
+ Result classes
7
+ --------------
8
+
9
+ .. currentmodule:: scipy.stats._result_classes
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ RelativeRiskResult
15
+ BinomTestResult
16
+ TukeyHSDResult
17
+ DunnettResult
18
+ PearsonRResult
19
+ FitResult
20
+ OddsRatioResult
21
+ TtestResult
22
+ ECDFResult
23
+ EmpiricalDistributionFunction
24
+
25
+ """
26
+
27
+ __all__ = ['BinomTestResult', 'RelativeRiskResult', 'TukeyHSDResult',
28
+ 'PearsonRResult', 'FitResult', 'OddsRatioResult',
29
+ 'TtestResult', 'DunnettResult', 'ECDFResult',
30
+ 'EmpiricalDistributionFunction']
31
+
32
+
33
+ from ._binomtest import BinomTestResult
34
+ from ._odds_ratio import OddsRatioResult
35
+ from ._relative_risk import RelativeRiskResult
36
+ from ._hypotests import TukeyHSDResult
37
+ from ._multicomp import DunnettResult
38
+ from ._stats_py import PearsonRResult, TtestResult
39
+ from ._fit import FitResult
40
+ from ._survival import ECDFResult, EmpiricalDistributionFunction
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sampling.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import numpy as np
4
+ from scipy import stats
5
+ from scipy import special as sc
6
+ from ._qmc import (check_random_state as check_random_state_qmc,
7
+ Halton, QMCEngine)
8
+ from ._unuran.unuran_wrapper import NumericalInversePolynomial
9
+ from scipy._lib._util import check_random_state
10
+
11
+
12
+ __all__ = ['FastGeneratorInversion', 'RatioUniforms']
13
+
14
+
15
+ # define pdfs and other helper functions to create the generators
16
+
17
+ def argus_pdf(x, chi):
18
+ # approach follows Baumgarten/Hoermann: Generating ARGUS random variates
19
+ # for chi > 5, use relationship of the ARGUS distribution to Gamma(1.5)
20
+ if chi <= 5:
21
+ y = 1 - x * x
22
+ return x * math.sqrt(y) * math.exp(-0.5 * chi**2 * y)
23
+ return math.sqrt(x) * math.exp(-x)
24
+
25
+
26
+ def argus_gamma_trf(x, chi):
27
+ if chi <= 5:
28
+ return x
29
+ return np.sqrt(1.0 - 2 * x / chi**2)
30
+
31
+
32
+ def argus_gamma_inv_trf(x, chi):
33
+ if chi <= 5:
34
+ return x
35
+ return 0.5 * chi**2 * (1 - x**2)
36
+
37
+
38
+ def betaprime_pdf(x, a, b):
39
+ if x > 0:
40
+ logf = (a - 1) * math.log(x) - (a + b) * math.log1p(x) - sc.betaln(a, b)
41
+ return math.exp(logf)
42
+ else:
43
+ # return pdf at x == 0 separately to avoid runtime warnings
44
+ if a > 1:
45
+ return 0
46
+ elif a < 1:
47
+ return np.inf
48
+ else:
49
+ return 1 / sc.beta(a, b)
50
+
51
+
52
+ def beta_valid_params(a, b):
53
+ return (min(a, b) >= 0.1) and (max(a, b) <= 700)
54
+
55
+
56
+ def gamma_pdf(x, a):
57
+ if x > 0:
58
+ return math.exp(-math.lgamma(a) + (a - 1.0) * math.log(x) - x)
59
+ else:
60
+ return 0 if a >= 1 else np.inf
61
+
62
+
63
+ def invgamma_pdf(x, a):
64
+ if x > 0:
65
+ return math.exp(-(a + 1.0) * math.log(x) - math.lgamma(a) - 1 / x)
66
+ else:
67
+ return 0 if a >= 1 else np.inf
68
+
69
+
70
+ def burr_pdf(x, cc, dd):
71
+ # note: we use np.exp instead of math.exp, otherwise an overflow
72
+ # error can occur in the setup, e.g., for parameters
73
+ # 1.89128135, 0.30195177, see test test_burr_overflow
74
+ if x > 0:
75
+ lx = math.log(x)
76
+ return np.exp(-(cc + 1) * lx - (dd + 1) * math.log1p(np.exp(-cc * lx)))
77
+ else:
78
+ return 0
79
+
80
+
81
+ def burr12_pdf(x, cc, dd):
82
+ if x > 0:
83
+ lx = math.log(x)
84
+ logterm = math.log1p(math.exp(cc * lx))
85
+ return math.exp((cc - 1) * lx - (dd + 1) * logterm + math.log(cc * dd))
86
+ else:
87
+ return 0
88
+
89
+
90
+ def chi_pdf(x, a):
91
+ if x > 0:
92
+ return math.exp(
93
+ (a - 1) * math.log(x)
94
+ - 0.5 * (x * x)
95
+ - (a / 2 - 1) * math.log(2)
96
+ - math.lgamma(0.5 * a)
97
+ )
98
+ else:
99
+ return 0 if a >= 1 else np.inf
100
+
101
+
102
+ def chi2_pdf(x, df):
103
+ if x > 0:
104
+ return math.exp(
105
+ (df / 2 - 1) * math.log(x)
106
+ - 0.5 * x
107
+ - (df / 2) * math.log(2)
108
+ - math.lgamma(0.5 * df)
109
+ )
110
+ else:
111
+ return 0 if df >= 1 else np.inf
112
+
113
+
114
+ def alpha_pdf(x, a):
115
+ if x > 0:
116
+ return math.exp(-2.0 * math.log(x) - 0.5 * (a - 1.0 / x) ** 2)
117
+ return 0.0
118
+
119
+
120
+ def bradford_pdf(x, c):
121
+ if 0 <= x <= 1:
122
+ return 1.0 / (1.0 + c * x)
123
+ return 0.0
124
+
125
+
126
+ def crystalball_pdf(x, b, m):
127
+ if x > -b:
128
+ return math.exp(-0.5 * x * x)
129
+ return math.exp(m * math.log(m / b) - 0.5 * b * b - m * math.log(m / b - b - x))
130
+
131
+
132
+ def weibull_min_pdf(x, c):
133
+ if x > 0:
134
+ return c * math.exp((c - 1) * math.log(x) - x**c)
135
+ return 0.0
136
+
137
+
138
+ def weibull_max_pdf(x, c):
139
+ if x < 0:
140
+ return c * math.exp((c - 1) * math.log(-x) - ((-x) ** c))
141
+ return 0.0
142
+
143
+
144
+ def invweibull_pdf(x, c):
145
+ if x > 0:
146
+ return c * math.exp(-(c + 1) * math.log(x) - x ** (-c))
147
+ return 0.0
148
+
149
+
150
+ def wald_pdf(x):
151
+ if x > 0:
152
+ return math.exp(-((x - 1) ** 2) / (2 * x)) / math.sqrt(x**3)
153
+ return 0.0
154
+
155
+
156
+ def geninvgauss_mode(p, b):
157
+ if p > 1: # equivalent mode formulas numerical more stable versions
158
+ return (math.sqrt((1 - p) ** 2 + b**2) - (1 - p)) / b
159
+ return b / (math.sqrt((1 - p) ** 2 + b**2) + (1 - p))
160
+
161
+
162
+ def geninvgauss_pdf(x, p, b):
163
+ m = geninvgauss_mode(p, b)
164
+ lfm = (p - 1) * math.log(m) - 0.5 * b * (m + 1 / m)
165
+ if x > 0:
166
+ return math.exp((p - 1) * math.log(x) - 0.5 * b * (x + 1 / x) - lfm)
167
+ return 0.0
168
+
169
+
170
+ def invgauss_mode(mu):
171
+ return 1.0 / (math.sqrt(1.5 * 1.5 + 1 / (mu * mu)) + 1.5)
172
+
173
+
174
+ def invgauss_pdf(x, mu):
175
+ m = invgauss_mode(mu)
176
+ lfm = -1.5 * math.log(m) - (m - mu) ** 2 / (2 * m * mu**2)
177
+ if x > 0:
178
+ return math.exp(-1.5 * math.log(x) - (x - mu) ** 2 / (2 * x * mu**2) - lfm)
179
+ return 0.0
180
+
181
+
182
+ def powerlaw_pdf(x, a):
183
+ if x > 0:
184
+ return x ** (a - 1)
185
+ return 0.0
186
+
187
+
188
+ # Define a dictionary: for a given distribution (keys), another dictionary
189
+ # (values) specifies the parameters for NumericalInversePolynomial (PINV).
190
+ # The keys of the latter dictionary are:
191
+ # - pdf: the pdf of the distribution (callable). The signature of the pdf
192
+ # is float -> float (i.e., the function does not have to be vectorized).
193
+ # If possible, functions like log or exp from the module math should be
194
+ # preferred over functions from numpy since the PINV setup will be faster
195
+ # in that case.
196
+ # - check_pinv_params: callable f that returns true if the shape parameters
197
+ # (args) are recommended parameters for PINV (i.e., the u-error does
198
+ # not exceed the default tolerance)
199
+ # - center: scalar if the center does not depend on args, otherwise
200
+ # callable that returns the center as a function of the shape parameters
201
+ # - rvs_transform: a callable that can be used to transform the rvs that
202
+ # are distributed according to the pdf to the target distribution
203
+ # (as an example, see the entry for the beta distribution)
204
+ # - rvs_transform_inv: the inverse of rvs_transform (it is required
205
+ # for the transformed ppf)
206
+ # - mirror_uniform: boolean or a callable that returns true or false
207
+ # depending on the shape parameters. If True, the ppf is applied
208
+ # to 1-u instead of u to generate rvs, where u is a uniform rv.
209
+ # While both u and 1-u are uniform, it can be required to use 1-u
210
+ # to compute the u-error correctly. This is only relevant for the argus
211
+ # distribution.
212
+ # The only required keys are "pdf" and "check_pinv_params".
213
+ # All other keys are optional.
214
+
215
+ PINV_CONFIG = {
216
+ "alpha": {
217
+ "pdf": alpha_pdf,
218
+ "check_pinv_params": lambda a: 1.0e-11 <= a < 2.1e5,
219
+ "center": lambda a: 0.25 * (math.sqrt(a * a + 8.0) - a),
220
+ },
221
+ "anglit": {
222
+ "pdf": lambda x: math.cos(2 * x) + 1.0e-13,
223
+ # +1.e-13 is necessary, otherwise PINV has strange problems as
224
+ # f(upper border) is very close to 0
225
+ "center": 0,
226
+ },
227
+ "argus": {
228
+ "pdf": argus_pdf,
229
+ "center": lambda chi: 0.7 if chi <= 5 else 0.5,
230
+ "check_pinv_params": lambda chi: 1e-20 < chi < 901,
231
+ "rvs_transform": argus_gamma_trf,
232
+ "rvs_transform_inv": argus_gamma_inv_trf,
233
+ "mirror_uniform": lambda chi: chi > 5,
234
+ },
235
+ "beta": {
236
+ "pdf": betaprime_pdf,
237
+ "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
238
+ "check_pinv_params": beta_valid_params,
239
+ "rvs_transform": lambda x, *args: x / (1 + x),
240
+ "rvs_transform_inv": lambda x, *args: x / (1 - x) if x < 1 else np.inf,
241
+ },
242
+ "betaprime": {
243
+ "pdf": betaprime_pdf,
244
+ "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
245
+ "check_pinv_params": beta_valid_params,
246
+ },
247
+ "bradford": {
248
+ "pdf": bradford_pdf,
249
+ "check_pinv_params": lambda a: 1.0e-6 <= a <= 1e9,
250
+ "center": 0.5,
251
+ },
252
+ "burr": {
253
+ "pdf": burr_pdf,
254
+ "center": lambda a, b: (2 ** (1 / b) - 1) ** (-1 / a),
255
+ "check_pinv_params": lambda a, b: (min(a, b) >= 0.3) and (max(a, b) <= 50),
256
+ },
257
+ "burr12": {
258
+ "pdf": burr12_pdf,
259
+ "center": lambda a, b: (2 ** (1 / b) - 1) ** (1 / a),
260
+ "check_pinv_params": lambda a, b: (min(a, b) >= 0.2) and (max(a, b) <= 50),
261
+ },
262
+ "cauchy": {
263
+ "pdf": lambda x: 1 / (1 + (x * x)),
264
+ "center": 0,
265
+ },
266
+ "chi": {
267
+ "pdf": chi_pdf,
268
+ "check_pinv_params": lambda df: 0.05 <= df <= 1.0e6,
269
+ "center": lambda a: math.sqrt(a),
270
+ },
271
+ "chi2": {
272
+ "pdf": chi2_pdf,
273
+ "check_pinv_params": lambda df: 0.07 <= df <= 1e6,
274
+ "center": lambda a: a,
275
+ },
276
+ "cosine": {
277
+ "pdf": lambda x: 1 + math.cos(x),
278
+ "center": 0,
279
+ },
280
+ "crystalball": {
281
+ "pdf": crystalball_pdf,
282
+ "check_pinv_params": lambda b, m: (0.01 <= b <= 5.5)
283
+ and (1.1 <= m <= 75.1),
284
+ "center": 0.0,
285
+ },
286
+ "expon": {
287
+ "pdf": lambda x: math.exp(-x),
288
+ "center": 1.0,
289
+ },
290
+ "gamma": {
291
+ "pdf": gamma_pdf,
292
+ "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
293
+ "center": lambda a: a,
294
+ },
295
+ "gennorm": {
296
+ "pdf": lambda x, b: math.exp(-abs(x) ** b),
297
+ "check_pinv_params": lambda b: 0.081 <= b <= 45.0,
298
+ "center": 0.0,
299
+ },
300
+ "geninvgauss": {
301
+ "pdf": geninvgauss_pdf,
302
+ "check_pinv_params": lambda p, b: (abs(p) <= 1200.0)
303
+ and (1.0e-10 <= b <= 1200.0),
304
+ "center": geninvgauss_mode,
305
+ },
306
+ "gumbel_l": {
307
+ "pdf": lambda x: math.exp(x - math.exp(x)),
308
+ "center": -0.6,
309
+ },
310
+ "gumbel_r": {
311
+ "pdf": lambda x: math.exp(-x - math.exp(-x)),
312
+ "center": 0.6,
313
+ },
314
+ "hypsecant": {
315
+ "pdf": lambda x: 1.0 / (math.exp(x) + math.exp(-x)),
316
+ "center": 0.0,
317
+ },
318
+ "invgamma": {
319
+ "pdf": invgamma_pdf,
320
+ "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
321
+ "center": lambda a: 1 / a,
322
+ },
323
+ "invgauss": {
324
+ "pdf": invgauss_pdf,
325
+ "check_pinv_params": lambda mu: 1.0e-10 <= mu <= 1.0e9,
326
+ "center": invgauss_mode,
327
+ },
328
+ "invweibull": {
329
+ "pdf": invweibull_pdf,
330
+ "check_pinv_params": lambda a: 0.12 <= a <= 512,
331
+ "center": 1.0,
332
+ },
333
+ "laplace": {
334
+ "pdf": lambda x: math.exp(-abs(x)),
335
+ "center": 0.0,
336
+ },
337
+ "logistic": {
338
+ "pdf": lambda x: math.exp(-x) / (1 + math.exp(-x)) ** 2,
339
+ "center": 0.0,
340
+ },
341
+ "maxwell": {
342
+ "pdf": lambda x: x * x * math.exp(-0.5 * x * x),
343
+ "center": 1.41421,
344
+ },
345
+ "moyal": {
346
+ "pdf": lambda x: math.exp(-(x + math.exp(-x)) / 2),
347
+ "center": 1.2,
348
+ },
349
+ "norm": {
350
+ "pdf": lambda x: math.exp(-x * x / 2),
351
+ "center": 0.0,
352
+ },
353
+ "pareto": {
354
+ "pdf": lambda x, b: x ** -(b + 1),
355
+ "center": lambda b: b / (b - 1) if b > 2 else 1.5,
356
+ "check_pinv_params": lambda b: 0.08 <= b <= 400000,
357
+ },
358
+ "powerlaw": {
359
+ "pdf": powerlaw_pdf,
360
+ "center": 1.0,
361
+ "check_pinv_params": lambda a: 0.06 <= a <= 1.0e5,
362
+ },
363
+ "t": {
364
+ "pdf": lambda x, df: (1 + x * x / df) ** (-0.5 * (df + 1)),
365
+ "check_pinv_params": lambda a: 0.07 <= a <= 1e6,
366
+ "center": 0.0,
367
+ },
368
+ "rayleigh": {
369
+ "pdf": lambda x: x * math.exp(-0.5 * (x * x)),
370
+ "center": 1.0,
371
+ },
372
+ "semicircular": {
373
+ "pdf": lambda x: math.sqrt(1.0 - (x * x)),
374
+ "center": 0,
375
+ },
376
+ "wald": {
377
+ "pdf": wald_pdf,
378
+ "center": 1.0,
379
+ },
380
+ "weibull_max": {
381
+ "pdf": weibull_max_pdf,
382
+ "check_pinv_params": lambda a: 0.25 <= a <= 512,
383
+ "center": -1.0,
384
+ },
385
+ "weibull_min": {
386
+ "pdf": weibull_min_pdf,
387
+ "check_pinv_params": lambda a: 0.25 <= a <= 512,
388
+ "center": 1.0,
389
+ },
390
+ }
391
+
392
+
393
+ def _validate_qmc_input(qmc_engine, d, seed):
394
+ # Input validation for `qmc_engine` and `d`
395
+ # Error messages for invalid `d` are raised by QMCEngine
396
+ # we could probably use a stats.qmc.check_qrandom_state
397
+ if isinstance(qmc_engine, QMCEngine):
398
+ if d is not None and qmc_engine.d != d:
399
+ message = "`d` must be consistent with dimension of `qmc_engine`."
400
+ raise ValueError(message)
401
+ d = qmc_engine.d if d is None else d
402
+ elif qmc_engine is None:
403
+ d = 1 if d is None else d
404
+ qmc_engine = Halton(d, seed=seed)
405
+ else:
406
+ message = (
407
+ "`qmc_engine` must be an instance of "
408
+ "`scipy.stats.qmc.QMCEngine` or `None`."
409
+ )
410
+ raise ValueError(message)
411
+
412
+ return qmc_engine, d
413
+
414
+
415
+ class CustomDistPINV:
416
+ def __init__(self, pdf, args):
417
+ self._pdf = lambda x: pdf(x, *args)
418
+
419
+ def pdf(self, x):
420
+ return self._pdf(x)
421
+
422
+
423
+ class FastGeneratorInversion:
424
+ """
425
+ Fast sampling by numerical inversion of the CDF for a large class of
426
+ continuous distributions in `scipy.stats`.
427
+
428
+ Parameters
429
+ ----------
430
+ dist : rv_frozen object
431
+ Frozen distribution object from `scipy.stats`. The list of supported
432
+ distributions can be found in the Notes section. The shape parameters,
433
+ `loc` and `scale` used to create the distributions must be scalars.
434
+ For example, for the Gamma distribution with shape parameter `p`,
435
+ `p` has to be a float, and for the beta distribution with shape
436
+ parameters (a, b), both a and b have to be floats.
437
+ domain : tuple of floats, optional
438
+ If one wishes to sample from a truncated/conditional distribution,
439
+ the domain has to be specified.
440
+ The default is None. In that case, the random variates are not
441
+ truncated, and the domain is inferred from the support of the
442
+ distribution.
443
+ ignore_shape_range : boolean, optional.
444
+ If False, shape parameters that are outside of the valid range
445
+ of values to ensure that the numerical accuracy (see Notes) is
446
+ high, raise a ValueError. If True, any shape parameters that are valid
447
+ for the distribution are accepted. This can be useful for testing.
448
+ The default is False.
449
+ random_state : {None, int, `numpy.random.Generator`,
450
+ `numpy.random.RandomState`}, optional
451
+
452
+ A NumPy random number generator or seed for the underlying NumPy
453
+ random number generator used to generate the stream of uniform
454
+ random numbers.
455
+ If `random_state` is None, it uses ``self.random_state``.
456
+ If `random_state` is an int,
457
+ ``np.random.default_rng(random_state)`` is used.
458
+ If `random_state` is already a ``Generator`` or ``RandomState``
459
+ instance then that instance is used.
460
+
461
+ Attributes
462
+ ----------
463
+ loc : float
464
+ The location parameter.
465
+ random_state : {`numpy.random.Generator`, `numpy.random.RandomState`}
466
+ The random state used in relevant methods like `rvs` (unless
467
+ another `random_state` is passed as an argument to these methods).
468
+ scale : float
469
+ The scale parameter.
470
+
471
+ Methods
472
+ -------
473
+ cdf
474
+ evaluate_error
475
+ ppf
476
+ qrvs
477
+ rvs
478
+ support
479
+
480
+ Notes
481
+ -----
482
+ The class creates an object for continuous distributions specified
483
+ by `dist`. The method `rvs` uses a generator from
484
+ `scipy.stats.sampling` that is created when the object is instantiated.
485
+ In addition, the methods `qrvs` and `ppf` are added.
486
+ `qrvs` generate samples based on quasi-random numbers from
487
+ `scipy.stats.qmc`. `ppf` is the PPF based on the
488
+ numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is
489
+ used to generate random variates.
490
+
491
+ Supported distributions (`distname`) are:
492
+ ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``,
493
+ ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``,
494
+ ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``,
495
+ ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``,
496
+ ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``,
497
+ ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``,
498
+ ``wald``, ``weibull_max``, ``weibull_min``.
499
+
500
+ `rvs` relies on the accuracy of the numerical inversion. If very extreme
501
+ shape parameters are used, the numerical inversion might not work. However,
502
+ for all implemented distributions, the admissible shape parameters have
503
+ been tested, and an error will be raised if the user supplies values
504
+ outside of the allowed range. The u-error should not exceed 1e-10 for all
505
+ valid parameters. Note that warnings might be raised even if parameters
506
+ are within the valid range when the object is instantiated.
507
+ To check numerical accuracy, the method `evaluate_error` can be used.
508
+
509
+ Note that all implemented distributions are also part of `scipy.stats`, and
510
+ the object created by `FastGeneratorInversion` relies on methods like
511
+ `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this
512
+ class can be summarized as follows: Once the generator to sample random
513
+ variates is created in the setup step, sampling and evaluation of
514
+ the PPF using `ppf` are very fast,
515
+ and performance is essentially independent of the distribution. Therefore,
516
+ a substantial speed-up can be achieved for many distributions if large
517
+ numbers of random variates are required. It is important to know that this
518
+ fast sampling is achieved by inversion of the CDF. Thus, one uniform
519
+ random variate is transformed into a non-uniform variate, which is an
520
+ advantage for several simulation methods, e.g., when
521
+ the variance reduction methods of common random variates or
522
+ antithetic variates are be used ([2]_).
523
+
524
+ In addition, inversion makes it possible to
525
+ - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`),
526
+ - to generate random variates truncated to an interval. For example, if
527
+ one aims to sample standard normal random variates from
528
+ the interval (2, 4), this can be easily achieved by using the parameter
529
+ `domain`.
530
+
531
+ The location and scale that are initially defined by `dist`
532
+ can be reset without having to rerun the setup
533
+ step to create the generator that is used for sampling. The relation
534
+ of the distribution `Y` with `loc` and `scale` to the standard
535
+ distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by
536
+ ``Y = loc + scale * X``.
537
+
538
+ References
539
+ ----------
540
+ .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
541
+ "Random variate generation by numerical inversion when only the
542
+ density is known." ACM Transactions on Modeling and Computer
543
+ Simulation (TOMACS) 20.4 (2010): 1-25.
544
+ .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger.
545
+ "Automatic nonuniform random number generation."
546
+ Springer, 2004.
547
+
548
+ Examples
549
+ --------
550
+ >>> import numpy as np
551
+ >>> from scipy import stats
552
+ >>> from scipy.stats.sampling import FastGeneratorInversion
553
+
554
+ Let's start with a simple example to illustrate the main features:
555
+
556
+ >>> gamma_frozen = stats.gamma(1.5)
557
+ >>> gamma_dist = FastGeneratorInversion(gamma_frozen)
558
+ >>> r = gamma_dist.rvs(size=1000)
559
+
560
+ The mean should be approximately equal to the shape parameter 1.5:
561
+
562
+ >>> r.mean()
563
+ 1.52423591130436 # may vary
564
+
565
+ Similarly, we can draw a sample based on quasi-random numbers:
566
+
567
+ >>> r = gamma_dist.qrvs(size=1000)
568
+ >>> r.mean()
569
+ 1.4996639255942914 # may vary
570
+
571
+ Compare the PPF against approximation `ppf`.
572
+
573
+ >>> q = [0.001, 0.2, 0.5, 0.8, 0.999]
574
+ >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q)))
575
+ 4.313394796895409e-08
576
+
577
+ To confirm that the numerical inversion is accurate, we evaluate the
578
+ approximation error (u-error), which should be below 1e-10 (for more
579
+ details, refer to the documentation of `evaluate_error`):
580
+
581
+ >>> gamma_dist.evaluate_error()
582
+ (7.446320551265581e-11, nan) # may vary
583
+
584
+ Note that the location and scale can be changed without instantiating a
585
+ new generator:
586
+
587
+ >>> gamma_dist.loc = 2
588
+ >>> gamma_dist.scale = 3
589
+ >>> r = gamma_dist.rvs(size=1000)
590
+
591
+ The mean should be approximately 2 + 3*1.5 = 6.5.
592
+
593
+ >>> r.mean()
594
+ 6.399549295242894 # may vary
595
+
596
+ Let us also illustrate how truncation can be applied:
597
+
598
+ >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4))
599
+ >>> r = trunc_norm.rvs(size=1000)
600
+ >>> 3 < r.min() < r.max() < 4
601
+ True
602
+
603
+ Check the mean:
604
+
605
+ >>> r.mean()
606
+ 3.250433367078603 # may vary
607
+
608
+ >>> stats.norm.expect(lb=3, ub=4, conditional=True)
609
+ 3.260454285589997
610
+
611
+ In this particular, case, `scipy.stats.truncnorm` could also be used to
612
+ generate truncated normal random variates.
613
+
614
+ """
615
+
616
+ def __init__(
617
+ self,
618
+ dist,
619
+ *,
620
+ domain=None,
621
+ ignore_shape_range=False,
622
+ random_state=None,
623
+ ):
624
+
625
+ if isinstance(dist, stats.distributions.rv_frozen):
626
+ distname = dist.dist.name
627
+ if distname not in PINV_CONFIG.keys():
628
+ raise ValueError(
629
+ f"Distribution '{distname}' is not supported."
630
+ f"It must be one of {list(PINV_CONFIG.keys())}"
631
+ )
632
+ else:
633
+ raise ValueError("`dist` must be a frozen distribution object")
634
+
635
+ loc = dist.kwds.get("loc", 0)
636
+ scale = dist.kwds.get("scale", 1)
637
+ args = dist.args
638
+ if not np.isscalar(loc):
639
+ raise ValueError("loc must be scalar.")
640
+ if not np.isscalar(scale):
641
+ raise ValueError("scale must be scalar.")
642
+
643
+ self._frozendist = getattr(stats, distname)(
644
+ *args,
645
+ loc=loc,
646
+ scale=scale,
647
+ )
648
+ self._distname = distname
649
+
650
+ nargs = np.broadcast_arrays(args)[0].size
651
+ nargs_expected = self._frozendist.dist.numargs
652
+ if nargs != nargs_expected:
653
+ raise ValueError(
654
+ f"Each of the {nargs_expected} shape parameters must be a "
655
+ f"scalar, but {nargs} values are provided."
656
+ )
657
+
658
+ self.random_state = random_state
659
+
660
+ if domain is None:
661
+ self._domain = self._frozendist.support()
662
+ self._p_lower = 0.0
663
+ self._p_domain = 1.0
664
+ else:
665
+ self._domain = domain
666
+ self._p_lower = self._frozendist.cdf(self._domain[0])
667
+ _p_domain = self._frozendist.cdf(self._domain[1]) - self._p_lower
668
+ self._p_domain = _p_domain
669
+ self._set_domain_adj()
670
+ self._ignore_shape_range = ignore_shape_range
671
+
672
+ # the domain to be passed to NumericalInversePolynomial
673
+ # define a separate variable since in case of a transformation,
674
+ # domain_pinv will not be the same as self._domain
675
+ self._domain_pinv = self._domain
676
+
677
+ # get information about the distribution from the config to set up
678
+ # the generator
679
+ dist = self._process_config(distname, args)
680
+
681
+ if self._rvs_transform_inv is not None:
682
+ d0 = self._rvs_transform_inv(self._domain[0], *args)
683
+ d1 = self._rvs_transform_inv(self._domain[1], *args)
684
+ if d0 > d1:
685
+ # swap values if transformation if decreasing
686
+ d0, d1 = d1, d0
687
+ # only update _domain_pinv and not _domain
688
+ # _domain refers to the original distribution, _domain_pinv
689
+ # to the transformed distribution
690
+ self._domain_pinv = d0, d1
691
+
692
+ # self._center has been set by the call self._process_config
693
+ # check if self._center is inside the transformed domain
694
+ # _domain_pinv, otherwise move it to the endpoint that is closer
695
+ if self._center is not None:
696
+ if self._center < self._domain_pinv[0]:
697
+ self._center = self._domain_pinv[0]
698
+ elif self._center > self._domain_pinv[1]:
699
+ self._center = self._domain_pinv[1]
700
+
701
+ self._rng = NumericalInversePolynomial(
702
+ dist,
703
+ random_state=self.random_state,
704
+ domain=self._domain_pinv,
705
+ center=self._center,
706
+ )
707
+
708
+ @property
709
+ def random_state(self):
710
+ return self._random_state
711
+
712
+ @random_state.setter
713
+ def random_state(self, random_state):
714
+ self._random_state = check_random_state_qmc(random_state)
715
+
716
+ @property
717
+ def loc(self):
718
+ return self._frozendist.kwds.get("loc", 0)
719
+
720
+ @loc.setter
721
+ def loc(self, loc):
722
+ if not np.isscalar(loc):
723
+ raise ValueError("loc must be scalar.")
724
+ self._frozendist.kwds["loc"] = loc
725
+ # update the adjusted domain that depends on loc and scale
726
+ self._set_domain_adj()
727
+
728
+ @property
729
+ def scale(self):
730
+ return self._frozendist.kwds.get("scale", 0)
731
+
732
+ @scale.setter
733
+ def scale(self, scale):
734
+ if not np.isscalar(scale):
735
+ raise ValueError("scale must be scalar.")
736
+ self._frozendist.kwds["scale"] = scale
737
+ # update the adjusted domain that depends on loc and scale
738
+ self._set_domain_adj()
739
+
740
+ def _set_domain_adj(self):
741
+ """ Adjust the domain based on loc and scale. """
742
+ loc = self.loc
743
+ scale = self.scale
744
+ lb = self._domain[0] * scale + loc
745
+ ub = self._domain[1] * scale + loc
746
+ self._domain_adj = (lb, ub)
747
+
748
+ def _process_config(self, distname, args):
749
+ cfg = PINV_CONFIG[distname]
750
+ if "check_pinv_params" in cfg:
751
+ if not self._ignore_shape_range:
752
+ if not cfg["check_pinv_params"](*args):
753
+ msg = ("No generator is defined for the shape parameters "
754
+ f"{args}. Use ignore_shape_range to proceed "
755
+ "with the selected values.")
756
+ raise ValueError(msg)
757
+
758
+ if "center" in cfg.keys():
759
+ if not np.isscalar(cfg["center"]):
760
+ self._center = cfg["center"](*args)
761
+ else:
762
+ self._center = cfg["center"]
763
+ else:
764
+ self._center = None
765
+ self._rvs_transform = cfg.get("rvs_transform", None)
766
+ self._rvs_transform_inv = cfg.get("rvs_transform_inv", None)
767
+ _mirror_uniform = cfg.get("mirror_uniform", None)
768
+ if _mirror_uniform is None:
769
+ self._mirror_uniform = False
770
+ else:
771
+ self._mirror_uniform = _mirror_uniform(*args)
772
+
773
+ return CustomDistPINV(cfg["pdf"], args)
774
+
775
+ def rvs(self, size=None):
776
+ """
777
+ Sample from the distribution by inversion.
778
+
779
+ Parameters
780
+ ----------
781
+ size : int or tuple, optional
782
+ The shape of samples. Default is ``None`` in which case a scalar
783
+ sample is returned.
784
+
785
+ Returns
786
+ -------
787
+ rvs : array_like
788
+ A NumPy array of random variates.
789
+
790
+ Notes
791
+ -----
792
+ Random variates are generated by numerical inversion of the CDF, i.e.,
793
+ `ppf` computed by `NumericalInversePolynomial` when the class
794
+ is instantiated. Note that the
795
+ default ``rvs`` method of the rv_continuous class is
796
+ overwritten. Hence, a different stream of random numbers is generated
797
+ even if the same seed is used.
798
+ """
799
+ # note: we cannot use self._rng.rvs directly in case
800
+ # self._mirror_uniform is true
801
+ u = self.random_state.uniform(size=size)
802
+ if self._mirror_uniform:
803
+ u = 1 - u
804
+ r = self._rng.ppf(u)
805
+ if self._rvs_transform is not None:
806
+ r = self._rvs_transform(r, *self._frozendist.args)
807
+ return self.loc + self.scale * r
808
+
809
+ def ppf(self, q):
810
+ """
811
+ Very fast PPF (inverse CDF) of the distribution which
812
+ is a very close approximation of the exact PPF values.
813
+
814
+ Parameters
815
+ ----------
816
+ u : array_like
817
+ Array with probabilities.
818
+
819
+ Returns
820
+ -------
821
+ ppf : array_like
822
+ Quantiles corresponding to the values in `u`.
823
+
824
+ Notes
825
+ -----
826
+ The evaluation of the PPF is very fast but it may have a large
827
+ relative error in the far tails. The numerical precision of the PPF
828
+ is controlled by the u-error, that is,
829
+ ``max |u - CDF(PPF(u))|`` where the max is taken over points in
830
+ the interval [0,1], see `evaluate_error`.
831
+
832
+ Note that this PPF is designed to generate random samples.
833
+ """
834
+ q = np.asarray(q)
835
+ if self._mirror_uniform:
836
+ x = self._rng.ppf(1 - q)
837
+ else:
838
+ x = self._rng.ppf(q)
839
+ if self._rvs_transform is not None:
840
+ x = self._rvs_transform(x, *self._frozendist.args)
841
+ return self.scale * x + self.loc
842
+
843
+ def qrvs(self, size=None, d=None, qmc_engine=None):
844
+ """
845
+ Quasi-random variates of the given distribution.
846
+
847
+ The `qmc_engine` is used to draw uniform quasi-random variates, and
848
+ these are converted to quasi-random variates of the given distribution
849
+ using inverse transform sampling.
850
+
851
+ Parameters
852
+ ----------
853
+ size : int, tuple of ints, or None; optional
854
+ Defines shape of random variates array. Default is ``None``.
855
+ d : int or None, optional
856
+ Defines dimension of uniform quasi-random variates to be
857
+ transformed. Default is ``None``.
858
+ qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional
859
+ Defines the object to use for drawing
860
+ quasi-random variates. Default is ``None``, which uses
861
+ `scipy.stats.qmc.Halton(1)`.
862
+
863
+ Returns
864
+ -------
865
+ rvs : ndarray or scalar
866
+ Quasi-random variates. See Notes for shape information.
867
+
868
+ Notes
869
+ -----
870
+ The shape of the output array depends on `size`, `d`, and `qmc_engine`.
871
+ The intent is for the interface to be natural, but the detailed rules
872
+ to achieve this are complicated.
873
+
874
+ - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is
875
+ created with dimension `d`. If `d` is not provided, ``d=1``.
876
+ - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is
877
+ determined from the dimension of the `qmc_engine`.
878
+ - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the
879
+ dimensions are inconsistent, a ``ValueError`` is raised.
880
+ - After `d` is determined according to the rules above, the output
881
+ shape is ``tuple_shape + d_shape``, where:
882
+
883
+ - ``tuple_shape = tuple()`` if `size` is ``None``,
884
+ - ``tuple_shape = (size,)`` if `size` is an ``int``,
885
+ - ``tuple_shape = size`` if `size` is a sequence,
886
+ - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and
887
+ - ``d_shape = (d,)`` if `d` is greater than 1.
888
+
889
+ The elements of the returned array are part of a low-discrepancy
890
+ sequence. If `d` is 1, this means that none of the samples are truly
891
+ independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a
892
+ quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for
893
+ details. Note that when `d` > 1, the samples returned are still those
894
+ of the provided univariate distribution, not a multivariate
895
+ generalization of that distribution.
896
+
897
+ """
898
+ qmc_engine, d = _validate_qmc_input(qmc_engine, d, self.random_state)
899
+ # mainly copied from unuran_wrapper.pyx.templ
900
+ # `rvs` is flexible about whether `size` is an int or tuple, so this
901
+ # should be, too.
902
+ try:
903
+ if size is None:
904
+ tuple_size = (1,)
905
+ else:
906
+ tuple_size = tuple(size)
907
+ except TypeError:
908
+ tuple_size = (size,)
909
+ # we do not use rng.qrvs directly since we need to be
910
+ # able to apply the ppf to 1 - u
911
+ N = 1 if size is None else np.prod(size)
912
+ u = qmc_engine.random(N)
913
+ if self._mirror_uniform:
914
+ u = 1 - u
915
+ qrvs = self._ppf(u)
916
+ if self._rvs_transform is not None:
917
+ qrvs = self._rvs_transform(qrvs, *self._frozendist.args)
918
+ if size is None:
919
+ qrvs = qrvs.squeeze()[()]
920
+ else:
921
+ if d == 1:
922
+ qrvs = qrvs.reshape(tuple_size)
923
+ else:
924
+ qrvs = qrvs.reshape(tuple_size + (d,))
925
+ return self.loc + self.scale * qrvs
926
+
927
+ def evaluate_error(self, size=100000, random_state=None, x_error=False):
928
+ """
929
+ Evaluate the numerical accuracy of the inversion (u- and x-error).
930
+
931
+ Parameters
932
+ ----------
933
+ size : int, optional
934
+ The number of random points over which the error is estimated.
935
+ Default is ``100000``.
936
+ random_state : {None, int, `numpy.random.Generator`,
937
+ `numpy.random.RandomState`}, optional
938
+
939
+ A NumPy random number generator or seed for the underlying NumPy
940
+ random number generator used to generate the stream of uniform
941
+ random numbers.
942
+ If `random_state` is None, use ``self.random_state``.
943
+ If `random_state` is an int,
944
+ ``np.random.default_rng(random_state)`` is used.
945
+ If `random_state` is already a ``Generator`` or ``RandomState``
946
+ instance then that instance is used.
947
+
948
+ Returns
949
+ -------
950
+ u_error, x_error : tuple of floats
951
+ A NumPy array of random variates.
952
+
953
+ Notes
954
+ -----
955
+ The numerical precision of the inverse CDF `ppf` is controlled by
956
+ the u-error. It is computed as follows:
957
+ ``max |u - CDF(PPF(u))|`` where the max is taken `size` random
958
+ points in the interval [0,1]. `random_state` determines the random
959
+ sample. Note that if `ppf` was exact, the u-error would be zero.
960
+
961
+ The x-error measures the direct distance between the exact PPF
962
+ and `ppf`. If ``x_error`` is set to ``True`, it is
963
+ computed as the maximum of the minimum of the relative and absolute
964
+ x-error:
965
+ ``max(min(x_error_abs[i], x_error_rel[i]))`` where
966
+ ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``,
967
+ ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``.
968
+ Note that it is important to consider the relative x-error in the case
969
+ that ``PPF(u)`` is close to zero or very large.
970
+
971
+ By default, only the u-error is evaluated and the x-error is set to
972
+ ``np.nan``. Note that the evaluation of the x-error will be very slow
973
+ if the implementation of the PPF is slow.
974
+
975
+ Further information about these error measures can be found in [1]_.
976
+
977
+ References
978
+ ----------
979
+ .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
980
+ "Random variate generation by numerical inversion when only the
981
+ density is known." ACM Transactions on Modeling and Computer
982
+ Simulation (TOMACS) 20.4 (2010): 1-25.
983
+
984
+ Examples
985
+ --------
986
+
987
+ >>> import numpy as np
988
+ >>> from scipy import stats
989
+ >>> from scipy.stats.sampling import FastGeneratorInversion
990
+
991
+ Create an object for the normal distribution:
992
+
993
+ >>> d_norm_frozen = stats.norm()
994
+ >>> d_norm = FastGeneratorInversion(d_norm_frozen)
995
+
996
+ To confirm that the numerical inversion is accurate, we evaluate the
997
+ approximation error (u-error and x-error).
998
+
999
+ >>> u_error, x_error = d_norm.evaluate_error(x_error=True)
1000
+
1001
+ The u-error should be below 1e-10:
1002
+
1003
+ >>> u_error
1004
+ 8.785783212061915e-11 # may vary
1005
+
1006
+ Compare the PPF against approximation `ppf`:
1007
+
1008
+ >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999]
1009
+ >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q))
1010
+ >>> x_error_abs = np.max(diff)
1011
+ >>> x_error_abs
1012
+ 1.2937954707581412e-08
1013
+
1014
+ This is the absolute x-error evaluated at the points q. The relative
1015
+ error is given by
1016
+
1017
+ >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q)))
1018
+ >>> x_error_rel
1019
+ 4.186725600453555e-09
1020
+
1021
+ The x_error computed above is derived in a very similar way over a
1022
+ much larger set of random values q. At each value q[i], the minimum
1023
+ of the relative and absolute error is taken. The final value is then
1024
+ derived as the maximum of these values. In our example, we get the
1025
+ following value:
1026
+
1027
+ >>> x_error
1028
+ 4.507068014335139e-07 # may vary
1029
+
1030
+ """
1031
+ if not isinstance(size, (numbers.Integral, np.integer)):
1032
+ raise ValueError("size must be an integer.")
1033
+ # urng will be used to draw the samples for testing the error
1034
+ # it must not interfere with self.random_state. therefore, do not
1035
+ # call self.rvs, but draw uniform random numbers and apply
1036
+ # self.ppf (note: like in rvs, consider self._mirror_uniform)
1037
+ urng = check_random_state_qmc(random_state)
1038
+ u = urng.uniform(size=size)
1039
+ if self._mirror_uniform:
1040
+ u = 1 - u
1041
+ x = self.ppf(u)
1042
+ uerr = np.max(np.abs(self._cdf(x) - u))
1043
+ if not x_error:
1044
+ return uerr, np.nan
1045
+ ppf_u = self._ppf(u)
1046
+ x_error_abs = np.abs(self.ppf(u)-ppf_u)
1047
+ x_error_rel = x_error_abs / np.abs(ppf_u)
1048
+ x_error_combined = np.array([x_error_abs, x_error_rel]).min(axis=0)
1049
+ return uerr, np.max(x_error_combined)
1050
+
1051
+ def support(self):
1052
+ """Support of the distribution.
1053
+
1054
+ Returns
1055
+ -------
1056
+ a, b : float
1057
+ end-points of the distribution's support.
1058
+
1059
+ Notes
1060
+ -----
1061
+
1062
+ Note that the support of the distribution depends on `loc`,
1063
+ `scale` and `domain`.
1064
+
1065
+ Examples
1066
+ --------
1067
+
1068
+ >>> from scipy import stats
1069
+ >>> from scipy.stats.sampling import FastGeneratorInversion
1070
+
1071
+ Define a truncated normal distribution:
1072
+
1073
+ >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1))
1074
+ >>> d_norm.support()
1075
+ (0, 1)
1076
+
1077
+ Shift the distribution:
1078
+
1079
+ >>> d_norm.loc = 2.5
1080
+ >>> d_norm.support()
1081
+ (2.5, 3.5)
1082
+
1083
+ """
1084
+ return self._domain_adj
1085
+
1086
+ def _cdf(self, x):
1087
+ """Cumulative distribution function (CDF)
1088
+
1089
+ Parameters
1090
+ ----------
1091
+ x : array_like
1092
+ The values where the CDF is evaluated
1093
+
1094
+ Returns
1095
+ -------
1096
+ y : ndarray
1097
+ CDF evaluated at x
1098
+
1099
+ """
1100
+ y = self._frozendist.cdf(x)
1101
+ if self._p_domain == 1.0:
1102
+ return y
1103
+ return np.clip((y - self._p_lower) / self._p_domain, 0, 1)
1104
+
1105
+ def _ppf(self, q):
1106
+ """Percent point function (inverse of `cdf`)
1107
+
1108
+ Parameters
1109
+ ----------
1110
+ q : array_like
1111
+ lower tail probability
1112
+
1113
+ Returns
1114
+ -------
1115
+ x : array_like
1116
+ quantile corresponding to the lower tail probability q.
1117
+
1118
+ """
1119
+ if self._p_domain == 1.0:
1120
+ return self._frozendist.ppf(q)
1121
+ x = self._frozendist.ppf(self._p_domain * np.array(q) + self._p_lower)
1122
+ return np.clip(x, self._domain_adj[0], self._domain_adj[1])
1123
+
1124
+
1125
+ class RatioUniforms:
1126
+ """
1127
+ Generate random samples from a probability density function using the
1128
+ ratio-of-uniforms method.
1129
+
1130
+ Parameters
1131
+ ----------
1132
+ pdf : callable
1133
+ A function with signature `pdf(x)` that is proportional to the
1134
+ probability density function of the distribution.
1135
+ umax : float
1136
+ The upper bound of the bounding rectangle in the u-direction.
1137
+ vmin : float
1138
+ The lower bound of the bounding rectangle in the v-direction.
1139
+ vmax : float
1140
+ The upper bound of the bounding rectangle in the v-direction.
1141
+ c : float, optional.
1142
+ Shift parameter of ratio-of-uniforms method, see Notes. Default is 0.
1143
+ random_state : {None, int, `numpy.random.Generator`,
1144
+ `numpy.random.RandomState`}, optional
1145
+
1146
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
1147
+ singleton is used.
1148
+ If `seed` is an int, a new ``RandomState`` instance is used,
1149
+ seeded with `seed`.
1150
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
1151
+ that instance is used.
1152
+
1153
+ Methods
1154
+ -------
1155
+ rvs
1156
+
1157
+ Notes
1158
+ -----
1159
+ Given a univariate probability density function `pdf` and a constant `c`,
1160
+ define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``.
1161
+ If ``(U, V)`` is a random vector uniformly distributed over ``A``,
1162
+ then ``V/U + c`` follows a distribution according to `pdf`.
1163
+
1164
+ The above result (see [1]_, [2]_) can be used to sample random variables
1165
+ using only the PDF, i.e. no inversion of the CDF is required. Typical
1166
+ choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of
1167
+ the rectangle ``R = [0, umax] x [vmin, vmax]`` where
1168
+
1169
+ - ``umax = sup sqrt(pdf(x))``
1170
+ - ``vmin = inf (x - c) sqrt(pdf(x))``
1171
+ - ``vmax = sup (x - c) sqrt(pdf(x))``
1172
+
1173
+ In particular, these values are finite if `pdf` is bounded and
1174
+ ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails).
1175
+ One can generate ``(U, V)`` uniformly on ``R`` and return
1176
+ ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly
1177
+ verified.
1178
+
1179
+ The algorithm is not changed if one replaces `pdf` by k * `pdf` for any
1180
+ constant k > 0. Thus, it is often convenient to work with a function
1181
+ that is proportional to the probability density function by dropping
1182
+ unnecessary normalization factors.
1183
+
1184
+ Intuitively, the method works well if ``A`` fills up most of the
1185
+ enclosing rectangle such that the probability is high that ``(U, V)``
1186
+ lies in ``A`` whenever it lies in ``R`` as the number of required
1187
+ iterations becomes too large otherwise. To be more precise, note that
1188
+ the expected number of iterations to draw ``(U, V)`` uniformly
1189
+ distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by
1190
+ the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``,
1191
+ where `area(pdf)` is the integral of `pdf` (which is equal to one if the
1192
+ probability density function is used but can take on other values if a
1193
+ function proportional to the density is used). The equality holds since
1194
+ the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_).
1195
+ If the sampling fails to generate a single random variate after 50000
1196
+ iterations (i.e. not a single draw is in ``A``), an exception is raised.
1197
+
1198
+ If the bounding rectangle is not correctly specified (i.e. if it does not
1199
+ contain ``A``), the algorithm samples from a distribution different from
1200
+ the one given by `pdf`. It is therefore recommended to perform a
1201
+ test such as `~scipy.stats.kstest` as a check.
1202
+
1203
+ References
1204
+ ----------
1205
+ .. [1] L. Devroye, "Non-Uniform Random Variate Generation",
1206
+ Springer-Verlag, 1986.
1207
+
1208
+ .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
1209
+ random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
1210
+
1211
+ .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random
1212
+ Variables Using the Ratio of Uniform Deviates",
1213
+ ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977.
1214
+
1215
+ Examples
1216
+ --------
1217
+ >>> import numpy as np
1218
+ >>> from scipy import stats
1219
+
1220
+ >>> from scipy.stats.sampling import RatioUniforms
1221
+ >>> rng = np.random.default_rng()
1222
+
1223
+ Simulate normally distributed random variables. It is easy to compute the
1224
+ bounding rectangle explicitly in that case. For simplicity, we drop the
1225
+ normalization factor of the density.
1226
+
1227
+ >>> f = lambda x: np.exp(-x**2 / 2)
1228
+ >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
1229
+ >>> umax = np.sqrt(f(0))
1230
+ >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng)
1231
+ >>> r = gen.rvs(size=2500)
1232
+
1233
+ The K-S test confirms that the random variates are indeed normally
1234
+ distributed (normality is not rejected at 5% significance level):
1235
+
1236
+ >>> stats.kstest(r, 'norm')[1]
1237
+ 0.250634764150542
1238
+
1239
+ The exponential distribution provides another example where the bounding
1240
+ rectangle can be determined explicitly.
1241
+
1242
+ >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0,
1243
+ ... vmax=2*np.exp(-1), random_state=rng)
1244
+ >>> r = gen.rvs(1000)
1245
+ >>> stats.kstest(r, 'expon')[1]
1246
+ 0.21121052054580314
1247
+
1248
+ """
1249
+
1250
+ def __init__(self, pdf, *, umax, vmin, vmax, c=0, random_state=None):
1251
+ if vmin >= vmax:
1252
+ raise ValueError("vmin must be smaller than vmax.")
1253
+
1254
+ if umax <= 0:
1255
+ raise ValueError("umax must be positive.")
1256
+
1257
+ self._pdf = pdf
1258
+ self._umax = umax
1259
+ self._vmin = vmin
1260
+ self._vmax = vmax
1261
+ self._c = c
1262
+ self._rng = check_random_state(random_state)
1263
+
1264
+ def rvs(self, size=1):
1265
+ """Sampling of random variates
1266
+
1267
+ Parameters
1268
+ ----------
1269
+ size : int or tuple of ints, optional
1270
+ Number of random variates to be generated (default is 1).
1271
+
1272
+ Returns
1273
+ -------
1274
+ rvs : ndarray
1275
+ The random variates distributed according to the probability
1276
+ distribution defined by the pdf.
1277
+
1278
+ """
1279
+ size1d = tuple(np.atleast_1d(size))
1280
+ N = np.prod(size1d) # number of rvs needed, reshape upon return
1281
+
1282
+ # start sampling using ratio of uniforms method
1283
+ x = np.zeros(N)
1284
+ simulated, i = 0, 1
1285
+
1286
+ # loop until N rvs have been generated: expected runtime is finite.
1287
+ # to avoid infinite loop, raise exception if not a single rv has been
1288
+ # generated after 50000 tries. even if the expected number of iterations
1289
+ # is 1000, the probability of this event is (1-1/1000)**50000
1290
+ # which is of order 10e-22
1291
+ while simulated < N:
1292
+ k = N - simulated
1293
+ # simulate uniform rvs on [0, umax] and [vmin, vmax]
1294
+ u1 = self._umax * self._rng.uniform(size=k)
1295
+ v1 = self._rng.uniform(self._vmin, self._vmax, size=k)
1296
+ # apply rejection method
1297
+ rvs = v1 / u1 + self._c
1298
+ accept = (u1**2 <= self._pdf(rvs))
1299
+ num_accept = np.sum(accept)
1300
+ if num_accept > 0:
1301
+ x[simulated:(simulated + num_accept)] = rvs[accept]
1302
+ simulated += num_accept
1303
+
1304
+ if (simulated == 0) and (i*N >= 50000):
1305
+ msg = (
1306
+ f"Not a single random variate could be generated in {i*N} "
1307
+ "attempts. The ratio of uniforms method does not appear "
1308
+ "to work for the provided parameters. Please check the "
1309
+ "pdf and the bounds."
1310
+ )
1311
+ raise RuntimeError(msg)
1312
+ i += 1
1313
+
1314
+ return np.reshape(x, size1d)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sensitivity_analysis.py ADDED
@@ -0,0 +1,713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from dataclasses import dataclass
3
+ from typing import TYPE_CHECKING, Any
4
+ from collections.abc import Callable
5
+
6
+ import numpy as np
7
+
8
+ from scipy.stats._common import ConfidenceInterval
9
+ from scipy.stats._qmc import check_random_state
10
+ from scipy.stats._resampling import BootstrapResult
11
+ from scipy.stats import qmc, bootstrap
12
+ from scipy._lib._util import _transition_to_rng
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ import numpy.typing as npt
17
+ from scipy._lib._util import DecimalNumber, IntNumber
18
+
19
+
20
+ __all__ = [
21
+ 'sobol_indices'
22
+ ]
23
+
24
+
25
+ def f_ishigami(x: "npt.ArrayLike") -> "npt.NDArray[np.inexact[Any]]":
26
+ r"""Ishigami function.
27
+
28
+ .. math::
29
+
30
+ Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1
31
+
32
+ with :math:`\mathbf{x} \in [-\pi, \pi]^3`.
33
+
34
+ Parameters
35
+ ----------
36
+ x : array_like ([x1, x2, x3], n)
37
+
38
+ Returns
39
+ -------
40
+ f : array_like (n,)
41
+ Function evaluation.
42
+
43
+ References
44
+ ----------
45
+ .. [1] Ishigami, T. and T. Homma. "An importance quantification technique
46
+ in uncertainty analysis for computer models." IEEE,
47
+ :doi:`10.1109/ISUMA.1990.151285`, 1990.
48
+ """
49
+ x = np.atleast_2d(x)
50
+ f_eval = (
51
+ np.sin(x[0])
52
+ + 7 * np.sin(x[1])**2
53
+ + 0.1 * (x[2]**4) * np.sin(x[0])
54
+ )
55
+ return f_eval
56
+
57
+
58
+ def sample_A_B(
59
+ n,
60
+ dists,
61
+ rng=None
62
+ ):
63
+ """Sample two matrices A and B.
64
+
65
+ Uses a Sobol' sequence with 2`d` columns to have 2 uncorrelated matrices.
66
+ This is more efficient than using 2 random draw of Sobol'.
67
+ See sec. 5 from [1]_.
68
+
69
+ Output shape is (d, n).
70
+
71
+ References
72
+ ----------
73
+ .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
74
+ S. Tarantola. "Variance based sensitivity analysis of model
75
+ output. Design and estimator for the total sensitivity index."
76
+ Computer Physics Communications, 181(2):259-270,
77
+ :doi:`10.1016/j.cpc.2009.09.018`, 2010.
78
+ """
79
+ d = len(dists)
80
+ A_B = qmc.Sobol(d=2*d, seed=rng, bits=64).random(n).T
81
+ A_B = A_B.reshape(2, d, -1)
82
+ try:
83
+ for d_, dist in enumerate(dists):
84
+ A_B[:, d_] = dist.ppf(A_B[:, d_])
85
+ except AttributeError as exc:
86
+ message = "Each distribution in `dists` must have method `ppf`."
87
+ raise ValueError(message) from exc
88
+ return A_B
89
+
90
+
91
+ def sample_AB(A: np.ndarray, B: np.ndarray) -> np.ndarray:
92
+ """AB matrix.
93
+
94
+ AB: rows of B into A. Shape (d, d, n).
95
+ - Copy A into d "pages"
96
+ - In the first page, replace 1st rows of A with 1st row of B.
97
+ ...
98
+ - In the dth page, replace dth row of A with dth row of B.
99
+ - return the stack of pages
100
+ """
101
+ d, n = A.shape
102
+ AB = np.tile(A, (d, 1, 1))
103
+ i = np.arange(d)
104
+ AB[i, i] = B[i]
105
+ return AB
106
+
107
+
108
+ def saltelli_2010(
109
+ f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray
110
+ ) -> tuple[np.ndarray, np.ndarray]:
111
+ r"""Saltelli2010 formulation.
112
+
113
+ .. math::
114
+
115
+ S_i = \frac{1}{N} \sum_{j=1}^N
116
+ f(\mathbf{B})_j (f(\mathbf{AB}^{(i)})_j - f(\mathbf{A})_j)
117
+
118
+ .. math::
119
+
120
+ S_{T_i} = \frac{1}{N} \sum_{j=1}^N
121
+ (f(\mathbf{A})_j - f(\mathbf{AB}^{(i)})_j)^2
122
+
123
+ Parameters
124
+ ----------
125
+ f_A, f_B : array_like (s, n)
126
+ Function values at A and B, respectively
127
+ f_AB : array_like (d, s, n)
128
+ Function values at each of the AB pages
129
+
130
+ Returns
131
+ -------
132
+ s, st : array_like (s, d)
133
+ First order and total order Sobol' indices.
134
+
135
+ References
136
+ ----------
137
+ .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
138
+ S. Tarantola. "Variance based sensitivity analysis of model
139
+ output. Design and estimator for the total sensitivity index."
140
+ Computer Physics Communications, 181(2):259-270,
141
+ :doi:`10.1016/j.cpc.2009.09.018`, 2010.
142
+ """
143
+ # Empirical variance calculated using output from A and B which are
144
+ # independent. Output of AB is not independent and cannot be used
145
+ var = np.var([f_A, f_B], axis=(0, -1))
146
+
147
+ # We divide by the variance to have a ratio of variance
148
+ # this leads to eq. 2
149
+ s = np.mean(f_B * (f_AB - f_A), axis=-1) / var # Table 2 (b)
150
+ st = 0.5 * np.mean((f_A - f_AB) ** 2, axis=-1) / var # Table 2 (f)
151
+
152
+ return s.T, st.T
153
+
154
+
155
+ @dataclass
156
+ class BootstrapSobolResult:
157
+ first_order: BootstrapResult
158
+ total_order: BootstrapResult
159
+
160
+
161
+ @dataclass
162
+ class SobolResult:
163
+ first_order: np.ndarray
164
+ total_order: np.ndarray
165
+ _indices_method: Callable
166
+ _f_A: np.ndarray
167
+ _f_B: np.ndarray
168
+ _f_AB: np.ndarray
169
+ _A: np.ndarray | None = None
170
+ _B: np.ndarray | None = None
171
+ _AB: np.ndarray | None = None
172
+ _bootstrap_result: BootstrapResult | None = None
173
+
174
+ def bootstrap(
175
+ self,
176
+ confidence_level: "DecimalNumber" = 0.95,
177
+ n_resamples: "IntNumber" = 999
178
+ ) -> BootstrapSobolResult:
179
+ """Bootstrap Sobol' indices to provide confidence intervals.
180
+
181
+ Parameters
182
+ ----------
183
+ confidence_level : float, default: ``0.95``
184
+ The confidence level of the confidence intervals.
185
+ n_resamples : int, default: ``999``
186
+ The number of resamples performed to form the bootstrap
187
+ distribution of the indices.
188
+
189
+ Returns
190
+ -------
191
+ res : BootstrapSobolResult
192
+ Bootstrap result containing the confidence intervals and the
193
+ bootstrap distribution of the indices.
194
+
195
+ An object with attributes:
196
+
197
+ first_order : BootstrapResult
198
+ Bootstrap result of the first order indices.
199
+ total_order : BootstrapResult
200
+ Bootstrap result of the total order indices.
201
+ See `BootstrapResult` for more details.
202
+
203
+ """
204
+ def statistic(idx):
205
+ f_A_ = self._f_A[:, idx]
206
+ f_B_ = self._f_B[:, idx]
207
+ f_AB_ = self._f_AB[..., idx]
208
+ return self._indices_method(f_A_, f_B_, f_AB_)
209
+
210
+ n = self._f_A.shape[1]
211
+
212
+ res = bootstrap(
213
+ [np.arange(n)], statistic=statistic, method="BCa",
214
+ n_resamples=n_resamples,
215
+ confidence_level=confidence_level,
216
+ bootstrap_result=self._bootstrap_result
217
+ )
218
+ self._bootstrap_result = res
219
+
220
+ first_order = BootstrapResult(
221
+ confidence_interval=ConfidenceInterval(
222
+ res.confidence_interval.low[0], res.confidence_interval.high[0]
223
+ ),
224
+ bootstrap_distribution=res.bootstrap_distribution[0],
225
+ standard_error=res.standard_error[0],
226
+ )
227
+ total_order = BootstrapResult(
228
+ confidence_interval=ConfidenceInterval(
229
+ res.confidence_interval.low[1], res.confidence_interval.high[1]
230
+ ),
231
+ bootstrap_distribution=res.bootstrap_distribution[1],
232
+ standard_error=res.standard_error[1],
233
+ )
234
+
235
+ return BootstrapSobolResult(
236
+ first_order=first_order, total_order=total_order
237
+ )
238
+
239
+ @_transition_to_rng('random_state', replace_doc=False)
240
+ def sobol_indices(
241
+ *,
242
+ func,
243
+ n,
244
+ dists=None,
245
+ method='saltelli_2010',
246
+ rng=None
247
+ ):
248
+ r"""Global sensitivity indices of Sobol'.
249
+
250
+ Parameters
251
+ ----------
252
+ func : callable or dict(str, array_like)
253
+ If `func` is a callable, function to compute the Sobol' indices from.
254
+ Its signature must be::
255
+
256
+ func(x: ArrayLike) -> ArrayLike
257
+
258
+ with ``x`` of shape ``(d, n)`` and output of shape ``(s, n)`` where:
259
+
260
+ - ``d`` is the input dimensionality of `func`
261
+ (number of input variables),
262
+ - ``s`` is the output dimensionality of `func`
263
+ (number of output variables), and
264
+ - ``n`` is the number of samples (see `n` below).
265
+
266
+ Function evaluation values must be finite.
267
+
268
+ If `func` is a dictionary, contains the function evaluations from three
269
+ different arrays. Keys must be: ``f_A``, ``f_B`` and ``f_AB``.
270
+ ``f_A`` and ``f_B`` should have a shape ``(s, n)`` and ``f_AB``
271
+ should have a shape ``(d, s, n)``.
272
+ This is an advanced feature and misuse can lead to wrong analysis.
273
+ n : int
274
+ Number of samples used to generate the matrices ``A`` and ``B``.
275
+ Must be a power of 2. The total number of points at which `func` is
276
+ evaluated will be ``n*(d+2)``.
277
+ dists : list(distributions), optional
278
+ List of each parameter's distribution. The distribution of parameters
279
+ depends on the application and should be carefully chosen.
280
+ Parameters are assumed to be independently distributed, meaning there
281
+ is no constraint nor relationship between their values.
282
+
283
+ Distributions must be an instance of a class with a ``ppf``
284
+ method.
285
+
286
+ Must be specified if `func` is a callable, and ignored otherwise.
287
+ method : Callable or str, default: 'saltelli_2010'
288
+ Method used to compute the first and total Sobol' indices.
289
+
290
+ If a callable, its signature must be::
291
+
292
+ func(f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray)
293
+ -> Tuple[np.ndarray, np.ndarray]
294
+
295
+ with ``f_A, f_B`` of shape ``(s, n)`` and ``f_AB`` of shape
296
+ ``(d, s, n)``.
297
+ These arrays contain the function evaluations from three different sets
298
+ of samples.
299
+ The output is a tuple of the first and total indices with
300
+ shape ``(s, d)``.
301
+ This is an advanced feature and misuse can lead to wrong analysis.
302
+ rng : `numpy.random.Generator`, optional
303
+ Pseudorandom number generator state. When `rng` is None, a new
304
+ `numpy.random.Generator` is created using entropy from the
305
+ operating system. Types other than `numpy.random.Generator` are
306
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
307
+
308
+ .. versionchanged:: 1.15.0
309
+
310
+ As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
311
+ transition from use of `numpy.random.RandomState` to
312
+ `numpy.random.Generator`, this keyword was changed from `random_state` to
313
+ `rng`. For an interim period, both keywords will continue to work, although
314
+ only one may be specified at a time. After the interim period, function
315
+ calls using the `random_state` keyword will emit warnings. Following a
316
+ deprecation period, the `random_state` keyword will be removed.
317
+
318
+ Returns
319
+ -------
320
+ res : SobolResult
321
+ An object with attributes:
322
+
323
+ first_order : ndarray of shape (s, d)
324
+ First order Sobol' indices.
325
+ total_order : ndarray of shape (s, d)
326
+ Total order Sobol' indices.
327
+
328
+ And method:
329
+
330
+ bootstrap(confidence_level: float, n_resamples: int)
331
+ -> BootstrapSobolResult
332
+
333
+ A method providing confidence intervals on the indices.
334
+ See `scipy.stats.bootstrap` for more details.
335
+
336
+ The bootstrapping is done on both first and total order indices,
337
+ and they are available in `BootstrapSobolResult` as attributes
338
+ ``first_order`` and ``total_order``.
339
+
340
+ Notes
341
+ -----
342
+ The Sobol' method [1]_, [2]_ is a variance-based Sensitivity Analysis which
343
+ obtains the contribution of each parameter to the variance of the
344
+ quantities of interest (QoIs; i.e., the outputs of `func`).
345
+ Respective contributions can be used to rank the parameters and
346
+ also gauge the complexity of the model by computing the
347
+ model's effective (or mean) dimension.
348
+
349
+ .. note::
350
+
351
+ Parameters are assumed to be independently distributed. Each
352
+ parameter can still follow any distribution. In fact, the distribution
353
+ is very important and should match the real distribution of the
354
+ parameters.
355
+
356
+ It uses a functional decomposition of the variance of the function to
357
+ explore
358
+
359
+ .. math::
360
+
361
+ \mathbb{V}(Y) = \sum_{i}^{d} \mathbb{V}_i (Y) + \sum_{i<j}^{d}
362
+ \mathbb{V}_{ij}(Y) + ... + \mathbb{V}_{1,2,...,d}(Y),
363
+
364
+ introducing conditional variances:
365
+
366
+ .. math::
367
+
368
+ \mathbb{V}_i(Y) = \mathbb{\mathbb{V}}[\mathbb{E}(Y|x_i)]
369
+ \qquad
370
+ \mathbb{V}_{ij}(Y) = \mathbb{\mathbb{V}}[\mathbb{E}(Y|x_i x_j)]
371
+ - \mathbb{V}_i(Y) - \mathbb{V}_j(Y),
372
+
373
+ Sobol' indices are expressed as
374
+
375
+ .. math::
376
+
377
+ S_i = \frac{\mathbb{V}_i(Y)}{\mathbb{V}[Y]}
378
+ \qquad
379
+ S_{ij} =\frac{\mathbb{V}_{ij}(Y)}{\mathbb{V}[Y]}.
380
+
381
+ :math:`S_{i}` corresponds to the first-order term which apprises the
382
+ contribution of the i-th parameter, while :math:`S_{ij}` corresponds to the
383
+ second-order term which informs about the contribution of interactions
384
+ between the i-th and the j-th parameters. These equations can be
385
+ generalized to compute higher order terms; however, they are expensive to
386
+ compute and their interpretation is complex.
387
+ This is why only first order indices are provided.
388
+
389
+ Total order indices represent the global contribution of the parameters
390
+ to the variance of the QoI and are defined as:
391
+
392
+ .. math::
393
+
394
+ S_{T_i} = S_i + \sum_j S_{ij} + \sum_{j,k} S_{ijk} + ...
395
+ = 1 - \frac{\mathbb{V}[\mathbb{E}(Y|x_{\sim i})]}{\mathbb{V}[Y]}.
396
+
397
+ First order indices sum to at most 1, while total order indices sum to at
398
+ least 1. If there are no interactions, then first and total order indices
399
+ are equal, and both first and total order indices sum to 1.
400
+
401
+ .. warning::
402
+
403
+ Negative Sobol' values are due to numerical errors. Increasing the
404
+ number of points `n` should help.
405
+
406
+ The number of sample required to have a good analysis increases with
407
+ the dimensionality of the problem. e.g. for a 3 dimension problem,
408
+ consider at minima ``n >= 2**12``. The more complex the model is,
409
+ the more samples will be needed.
410
+
411
+ Even for a purely additive model, the indices may not sum to 1 due
412
+ to numerical noise.
413
+
414
+ References
415
+ ----------
416
+ .. [1] Sobol, I. M.. "Sensitivity analysis for nonlinear mathematical
417
+ models." Mathematical Modeling and Computational Experiment, 1:407-414,
418
+ 1993.
419
+ .. [2] Sobol, I. M. (2001). "Global sensitivity indices for nonlinear
420
+ mathematical models and their Monte Carlo estimates." Mathematics
421
+ and Computers in Simulation, 55(1-3):271-280,
422
+ :doi:`10.1016/S0378-4754(00)00270-6`, 2001.
423
+ .. [3] Saltelli, A. "Making best use of model evaluations to
424
+ compute sensitivity indices." Computer Physics Communications,
425
+ 145(2):280-297, :doi:`10.1016/S0010-4655(02)00280-1`, 2002.
426
+ .. [4] Saltelli, A., M. Ratto, T. Andres, F. Campolongo, J. Cariboni,
427
+ D. Gatelli, M. Saisana, and S. Tarantola. "Global Sensitivity Analysis.
428
+ The Primer." 2007.
429
+ .. [5] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
430
+ S. Tarantola. "Variance based sensitivity analysis of model
431
+ output. Design and estimator for the total sensitivity index."
432
+ Computer Physics Communications, 181(2):259-270,
433
+ :doi:`10.1016/j.cpc.2009.09.018`, 2010.
434
+ .. [6] Ishigami, T. and T. Homma. "An importance quantification technique
435
+ in uncertainty analysis for computer models." IEEE,
436
+ :doi:`10.1109/ISUMA.1990.151285`, 1990.
437
+
438
+ Examples
439
+ --------
440
+ The following is an example with the Ishigami function [6]_
441
+
442
+ .. math::
443
+
444
+ Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1,
445
+
446
+ with :math:`\mathbf{x} \in [-\pi, \pi]^3`. This function exhibits strong
447
+ non-linearity and non-monotonicity.
448
+
449
+ Remember, Sobol' indices assumes that samples are independently
450
+ distributed. In this case we use a uniform distribution on each marginals.
451
+
452
+ >>> import numpy as np
453
+ >>> from scipy.stats import sobol_indices, uniform
454
+ >>> rng = np.random.default_rng()
455
+ >>> def f_ishigami(x):
456
+ ... f_eval = (
457
+ ... np.sin(x[0])
458
+ ... + 7 * np.sin(x[1])**2
459
+ ... + 0.1 * (x[2]**4) * np.sin(x[0])
460
+ ... )
461
+ ... return f_eval
462
+ >>> indices = sobol_indices(
463
+ ... func=f_ishigami, n=1024,
464
+ ... dists=[
465
+ ... uniform(loc=-np.pi, scale=2*np.pi),
466
+ ... uniform(loc=-np.pi, scale=2*np.pi),
467
+ ... uniform(loc=-np.pi, scale=2*np.pi)
468
+ ... ],
469
+ ... rng=rng
470
+ ... )
471
+ >>> indices.first_order
472
+ array([0.31637954, 0.43781162, 0.00318825])
473
+ >>> indices.total_order
474
+ array([0.56122127, 0.44287857, 0.24229595])
475
+
476
+ Confidence interval can be obtained using bootstrapping.
477
+
478
+ >>> boot = indices.bootstrap()
479
+
480
+ Then, this information can be easily visualized.
481
+
482
+ >>> import matplotlib.pyplot as plt
483
+ >>> fig, axs = plt.subplots(1, 2, figsize=(9, 4))
484
+ >>> _ = axs[0].errorbar(
485
+ ... [1, 2, 3], indices.first_order, fmt='o',
486
+ ... yerr=[
487
+ ... indices.first_order - boot.first_order.confidence_interval.low,
488
+ ... boot.first_order.confidence_interval.high - indices.first_order
489
+ ... ],
490
+ ... )
491
+ >>> axs[0].set_ylabel("First order Sobol' indices")
492
+ >>> axs[0].set_xlabel('Input parameters')
493
+ >>> axs[0].set_xticks([1, 2, 3])
494
+ >>> _ = axs[1].errorbar(
495
+ ... [1, 2, 3], indices.total_order, fmt='o',
496
+ ... yerr=[
497
+ ... indices.total_order - boot.total_order.confidence_interval.low,
498
+ ... boot.total_order.confidence_interval.high - indices.total_order
499
+ ... ],
500
+ ... )
501
+ >>> axs[1].set_ylabel("Total order Sobol' indices")
502
+ >>> axs[1].set_xlabel('Input parameters')
503
+ >>> axs[1].set_xticks([1, 2, 3])
504
+ >>> plt.tight_layout()
505
+ >>> plt.show()
506
+
507
+ .. note::
508
+
509
+ By default, `scipy.stats.uniform` has support ``[0, 1]``.
510
+ Using the parameters ``loc`` and ``scale``, one obtains the uniform
511
+ distribution on ``[loc, loc + scale]``.
512
+
513
+ This result is particularly interesting because the first order index
514
+ :math:`S_{x_3} = 0` whereas its total order is :math:`S_{T_{x_3}} = 0.244`.
515
+ This means that higher order interactions with :math:`x_3` are responsible
516
+ for the difference. Almost 25% of the observed variance
517
+ on the QoI is due to the correlations between :math:`x_3` and :math:`x_1`,
518
+ although :math:`x_3` by itself has no impact on the QoI.
519
+
520
+ The following gives a visual explanation of Sobol' indices on this
521
+ function. Let's generate 1024 samples in :math:`[-\pi, \pi]^3` and
522
+ calculate the value of the output.
523
+
524
+ >>> from scipy.stats import qmc
525
+ >>> n_dim = 3
526
+ >>> p_labels = ['$x_1$', '$x_2$', '$x_3$']
527
+ >>> sample = qmc.Sobol(d=n_dim, seed=rng).random(1024)
528
+ >>> sample = qmc.scale(
529
+ ... sample=sample,
530
+ ... l_bounds=[-np.pi, -np.pi, -np.pi],
531
+ ... u_bounds=[np.pi, np.pi, np.pi]
532
+ ... )
533
+ >>> output = f_ishigami(sample.T)
534
+
535
+ Now we can do scatter plots of the output with respect to each parameter.
536
+ This gives a visual way to understand how each parameter impacts the
537
+ output of the function.
538
+
539
+ >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
540
+ >>> for i in range(n_dim):
541
+ ... xi = sample[:, i]
542
+ ... ax[i].scatter(xi, output, marker='+')
543
+ ... ax[i].set_xlabel(p_labels[i])
544
+ >>> ax[0].set_ylabel('Y')
545
+ >>> plt.tight_layout()
546
+ >>> plt.show()
547
+
548
+ Now Sobol' goes a step further:
549
+ by conditioning the output value by given values of the parameter
550
+ (black lines), the conditional output mean is computed. It corresponds to
551
+ the term :math:`\mathbb{E}(Y|x_i)`. Taking the variance of this term gives
552
+ the numerator of the Sobol' indices.
553
+
554
+ >>> mini = np.min(output)
555
+ >>> maxi = np.max(output)
556
+ >>> n_bins = 10
557
+ >>> bins = np.linspace(-np.pi, np.pi, num=n_bins, endpoint=False)
558
+ >>> dx = bins[1] - bins[0]
559
+ >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
560
+ >>> for i in range(n_dim):
561
+ ... xi = sample[:, i]
562
+ ... ax[i].scatter(xi, output, marker='+')
563
+ ... ax[i].set_xlabel(p_labels[i])
564
+ ... for bin_ in bins:
565
+ ... idx = np.where((bin_ <= xi) & (xi <= bin_ + dx))
566
+ ... xi_ = xi[idx]
567
+ ... y_ = output[idx]
568
+ ... ave_y_ = np.mean(y_)
569
+ ... ax[i].plot([bin_ + dx/2] * 2, [mini, maxi], c='k')
570
+ ... ax[i].scatter(bin_ + dx/2, ave_y_, c='r')
571
+ >>> ax[0].set_ylabel('Y')
572
+ >>> plt.tight_layout()
573
+ >>> plt.show()
574
+
575
+ Looking at :math:`x_3`, the variance
576
+ of the mean is zero leading to :math:`S_{x_3} = 0`. But we can further
577
+ observe that the variance of the output is not constant along the parameter
578
+ values of :math:`x_3`. This heteroscedasticity is explained by higher order
579
+ interactions. Moreover, an heteroscedasticity is also noticeable on
580
+ :math:`x_1` leading to an interaction between :math:`x_3` and :math:`x_1`.
581
+ On :math:`x_2`, the variance seems to be constant and thus null interaction
582
+ with this parameter can be supposed.
583
+
584
+ This case is fairly simple to analyse visually---although it is only a
585
+ qualitative analysis. Nevertheless, when the number of input parameters
586
+ increases such analysis becomes unrealistic as it would be difficult to
587
+ conclude on high-order terms. Hence the benefit of using Sobol' indices.
588
+
589
+ """
590
+ rng = check_random_state(rng)
591
+
592
+ n_ = int(n)
593
+ if not (n_ & (n_ - 1) == 0) or n != n_:
594
+ raise ValueError(
595
+ "The balance properties of Sobol' points require 'n' "
596
+ "to be a power of 2."
597
+ )
598
+ n = n_
599
+
600
+ if not callable(method):
601
+ indices_methods = {
602
+ "saltelli_2010": saltelli_2010,
603
+ }
604
+ try:
605
+ method = method.lower() # type: ignore[assignment]
606
+ indices_method_ = indices_methods[method]
607
+ except KeyError as exc:
608
+ message = (
609
+ f"{method!r} is not a valid 'method'. It must be one of"
610
+ f" {set(indices_methods)!r} or a callable."
611
+ )
612
+ raise ValueError(message) from exc
613
+ else:
614
+ indices_method_ = method
615
+ sig = inspect.signature(indices_method_)
616
+
617
+ if set(sig.parameters) != {'f_A', 'f_B', 'f_AB'}:
618
+ message = (
619
+ "If 'method' is a callable, it must have the following"
620
+ f" signature: {inspect.signature(saltelli_2010)}"
621
+ )
622
+ raise ValueError(message)
623
+
624
+ def indices_method(f_A, f_B, f_AB):
625
+ """Wrap indices method to ensure proper output dimension.
626
+
627
+ 1D when single output, 2D otherwise.
628
+ """
629
+ return np.squeeze(indices_method_(f_A=f_A, f_B=f_B, f_AB=f_AB))
630
+
631
+ if callable(func):
632
+ if dists is None:
633
+ raise ValueError(
634
+ "'dists' must be defined when 'func' is a callable."
635
+ )
636
+
637
+ def wrapped_func(x):
638
+ return np.atleast_2d(func(x))
639
+
640
+ A, B = sample_A_B(n=n, dists=dists, rng=rng)
641
+ AB = sample_AB(A=A, B=B)
642
+
643
+ f_A = wrapped_func(A)
644
+
645
+ if f_A.shape[1] != n:
646
+ raise ValueError(
647
+ "'func' output should have a shape ``(s, -1)`` with ``s`` "
648
+ "the number of output."
649
+ )
650
+
651
+ def funcAB(AB):
652
+ d, d, n = AB.shape
653
+ AB = np.moveaxis(AB, 0, -1).reshape(d, n*d)
654
+ f_AB = wrapped_func(AB)
655
+ return np.moveaxis(f_AB.reshape((-1, n, d)), -1, 0)
656
+
657
+ f_B = wrapped_func(B)
658
+ f_AB = funcAB(AB)
659
+ else:
660
+ message = (
661
+ "When 'func' is a dictionary, it must contain the following "
662
+ "keys: 'f_A', 'f_B' and 'f_AB'."
663
+ "'f_A' and 'f_B' should have a shape ``(s, n)`` and 'f_AB' "
664
+ "should have a shape ``(d, s, n)``."
665
+ )
666
+ try:
667
+ f_A, f_B, f_AB = map(lambda arr: arr.copy(), np.atleast_2d(
668
+ func['f_A'], func['f_B'], func['f_AB']
669
+ ))
670
+ except KeyError as exc:
671
+ raise ValueError(message) from exc
672
+
673
+ if f_A.shape[1] != n or f_A.shape != f_B.shape or \
674
+ f_AB.shape == f_A.shape or f_AB.shape[-1] % n != 0:
675
+ raise ValueError(message)
676
+
677
+ # Normalization by mean
678
+ # Sobol', I. and Levitan, Y. L. (1999). On the use of variance reducing
679
+ # multipliers in monte carlo computations of a global sensitivity index.
680
+ # Computer Physics Communications, 117(1) :52-61.
681
+ mean = np.mean([f_A, f_B], axis=(0, -1)).reshape(-1, 1)
682
+ f_A -= mean
683
+ f_B -= mean
684
+ f_AB -= mean
685
+
686
+ # Compute indices
687
+ # Filter warnings for constant output as var = 0
688
+ with np.errstate(divide='ignore', invalid='ignore'):
689
+ first_order, total_order = indices_method(f_A=f_A, f_B=f_B, f_AB=f_AB)
690
+
691
+ # null variance means null indices
692
+ first_order[~np.isfinite(first_order)] = 0
693
+ total_order[~np.isfinite(total_order)] = 0
694
+
695
+ res = dict(
696
+ first_order=first_order,
697
+ total_order=total_order,
698
+ _indices_method=indices_method,
699
+ _f_A=f_A,
700
+ _f_B=f_B,
701
+ _f_AB=f_AB
702
+ )
703
+
704
+ if callable(func):
705
+ res.update(
706
+ dict(
707
+ _A=A,
708
+ _B=B,
709
+ _AB=AB,
710
+ )
711
+ )
712
+
713
+ return SobolResult(**res)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d1abaf4884fef3fc9a9e555579459e2162fc1ce5ac6d6b490e0ca66fa848e5b
3
+ size 404192
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol.pyi ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._util import IntNumber
3
+ from typing import Literal
4
+
5
+ def _initialize_v(
6
+ v : np.ndarray,
7
+ dim : IntNumber,
8
+ bits: IntNumber
9
+ ) -> None: ...
10
+
11
+ def _cscramble (
12
+ dim : IntNumber,
13
+ bits: IntNumber,
14
+ ltm : np.ndarray,
15
+ sv: np.ndarray
16
+ ) -> None: ...
17
+
18
+ def _fill_p_cumulative(
19
+ p: np.ndarray,
20
+ p_cumulative: np.ndarray
21
+ ) -> None: ...
22
+
23
+ def _draw(
24
+ n : IntNumber,
25
+ num_gen: IntNumber,
26
+ dim: IntNumber,
27
+ scale: float,
28
+ sv: np.ndarray,
29
+ quasi: np.ndarray,
30
+ sample: np.ndarray
31
+ ) -> None: ...
32
+
33
+ def _fast_forward(
34
+ n: IntNumber,
35
+ num_gen: IntNumber,
36
+ dim: IntNumber,
37
+ sv: np.ndarray,
38
+ quasi: np.ndarray
39
+ ) -> None: ...
40
+
41
+ def _categorize(
42
+ draws: np.ndarray,
43
+ p_cumulative: np.ndarray,
44
+ result: np.ndarray
45
+ ) -> None: ...
46
+
47
+ _MAXDIM: Literal[21201]
48
+ _MAXDEG: Literal[18]
49
+
50
+ def _test_find_index(
51
+ p_cumulative: np.ndarray,
52
+ size: int,
53
+ value: float
54
+ ) -> int: ...
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_sobol_direction_numbers.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4859931147d42ce465b8605cb277f957d98b839d03194fdf06579357906d193b
3
+ size 589334
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f03d6b444968b8db7e1538f64e2124e142167e3f8aa2304a2e3531a615b2311
3
+ size 750304
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats.pxd ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # destined to be used in a LowLevelCallable
2
+
3
+ cdef double _geninvgauss_pdf(double x, void *user_data) noexcept nogil
4
+ cdef double _studentized_range_cdf(int n, double[2] x, void *user_data) noexcept nogil
5
+ cdef double _studentized_range_cdf_asymptotic(double z, void *user_data) noexcept nogil
6
+ cdef double _studentized_range_pdf(int n, double[2] x, void *user_data) noexcept nogil
7
+ cdef double _studentized_range_pdf_asymptotic(double z, void *user_data) noexcept nogil
8
+ cdef double _studentized_range_moment(int n, double[3] x_arg, void *user_data) noexcept nogil
9
+ cdef double _genhyperbolic_pdf(double x, void *user_data) noexcept nogil
10
+ cdef double _genhyperbolic_logpdf(double x, void *user_data) noexcept nogil
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_mstats_common.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import numpy as np
3
+ from . import distributions
4
+ from .._lib._bunch import _make_tuple_bunch
5
+ from ._stats_pythran import siegelslopes as siegelslopes_pythran
6
+
7
+ __all__ = ['_find_repeats', 'theilslopes', 'siegelslopes']
8
+
9
+ # This is not a namedtuple for backwards compatibility. See PR #12983
10
+ TheilslopesResult = _make_tuple_bunch('TheilslopesResult',
11
+ ['slope', 'intercept',
12
+ 'low_slope', 'high_slope'])
13
+ SiegelslopesResult = _make_tuple_bunch('SiegelslopesResult',
14
+ ['slope', 'intercept'])
15
+
16
+
17
+ def theilslopes(y, x=None, alpha=0.95, method='separate'):
18
+ r"""
19
+ Computes the Theil-Sen estimator for a set of points (x, y).
20
+
21
+ `theilslopes` implements a method for robust linear regression. It
22
+ computes the slope as the median of all slopes between paired values.
23
+
24
+ Parameters
25
+ ----------
26
+ y : array_like
27
+ Dependent variable.
28
+ x : array_like or None, optional
29
+ Independent variable. If None, use ``arange(len(y))`` instead.
30
+ alpha : float, optional
31
+ Confidence degree between 0 and 1. Default is 95% confidence.
32
+ Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are
33
+ interpreted as "find the 90% confidence interval".
34
+ method : {'joint', 'separate'}, optional
35
+ Method to be used for computing estimate for intercept.
36
+ Following methods are supported,
37
+
38
+ * 'joint': Uses np.median(y - slope * x) as intercept.
39
+ * 'separate': Uses np.median(y) - slope * np.median(x)
40
+ as intercept.
41
+
42
+ The default is 'separate'.
43
+
44
+ .. versionadded:: 1.8.0
45
+
46
+ Returns
47
+ -------
48
+ result : ``TheilslopesResult`` instance
49
+ The return value is an object with the following attributes:
50
+
51
+ slope : float
52
+ Theil slope.
53
+ intercept : float
54
+ Intercept of the Theil line.
55
+ low_slope : float
56
+ Lower bound of the confidence interval on `slope`.
57
+ high_slope : float
58
+ Upper bound of the confidence interval on `slope`.
59
+
60
+ See Also
61
+ --------
62
+ siegelslopes : a similar technique using repeated medians
63
+
64
+ Notes
65
+ -----
66
+ The implementation of `theilslopes` follows [1]_. The intercept is
67
+ not defined in [1]_, and here it is defined as ``median(y) -
68
+ slope*median(x)``, which is given in [3]_. Other definitions of
69
+ the intercept exist in the literature such as ``median(y - slope*x)``
70
+ in [4]_. The approach to compute the intercept can be determined by the
71
+ parameter ``method``. A confidence interval for the intercept is not
72
+ given as this question is not addressed in [1]_.
73
+
74
+ For compatibility with older versions of SciPy, the return value acts
75
+ like a ``namedtuple`` of length 4, with fields ``slope``, ``intercept``,
76
+ ``low_slope``, and ``high_slope``, so one can continue to write::
77
+
78
+ slope, intercept, low_slope, high_slope = theilslopes(y, x)
79
+
80
+ References
81
+ ----------
82
+ .. [1] P.K. Sen, "Estimates of the regression coefficient based on
83
+ Kendall's tau", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968.
84
+ .. [2] H. Theil, "A rank-invariant method of linear and polynomial
85
+ regression analysis I, II and III", Nederl. Akad. Wetensch., Proc.
86
+ 53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950.
87
+ .. [3] W.L. Conover, "Practical nonparametric statistics", 2nd ed.,
88
+ John Wiley and Sons, New York, pp. 493.
89
+ .. [4] https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator
90
+
91
+ Examples
92
+ --------
93
+ >>> import numpy as np
94
+ >>> from scipy import stats
95
+ >>> import matplotlib.pyplot as plt
96
+
97
+ >>> x = np.linspace(-5, 5, num=150)
98
+ >>> y = x + np.random.normal(size=x.size)
99
+ >>> y[11:15] += 10 # add outliers
100
+ >>> y[-5:] -= 7
101
+
102
+ Compute the slope, intercept and 90% confidence interval. For comparison,
103
+ also compute the least-squares fit with `linregress`:
104
+
105
+ >>> res = stats.theilslopes(y, x, 0.90, method='separate')
106
+ >>> lsq_res = stats.linregress(x, y)
107
+
108
+ Plot the results. The Theil-Sen regression line is shown in red, with the
109
+ dashed red lines illustrating the confidence interval of the slope (note
110
+ that the dashed red lines are not the confidence interval of the regression
111
+ as the confidence interval of the intercept is not included). The green
112
+ line shows the least-squares fit for comparison.
113
+
114
+ >>> fig = plt.figure()
115
+ >>> ax = fig.add_subplot(111)
116
+ >>> ax.plot(x, y, 'b.')
117
+ >>> ax.plot(x, res[1] + res[0] * x, 'r-')
118
+ >>> ax.plot(x, res[1] + res[2] * x, 'r--')
119
+ >>> ax.plot(x, res[1] + res[3] * x, 'r--')
120
+ >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
121
+ >>> plt.show()
122
+
123
+ """
124
+ if method not in ['joint', 'separate']:
125
+ raise ValueError("method must be either 'joint' or 'separate'."
126
+ f"'{method}' is invalid.")
127
+ # We copy both x and y so we can use _find_repeats.
128
+ y = np.array(y, dtype=float, copy=True).ravel()
129
+ if x is None:
130
+ x = np.arange(len(y), dtype=float)
131
+ else:
132
+ x = np.array(x, dtype=float, copy=True).ravel()
133
+ if len(x) != len(y):
134
+ raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
135
+
136
+ # Compute sorted slopes only when deltax > 0
137
+ deltax = x[:, np.newaxis] - x
138
+ deltay = y[:, np.newaxis] - y
139
+ slopes = deltay[deltax > 0] / deltax[deltax > 0]
140
+ if not slopes.size:
141
+ msg = "All `x` coordinates are identical."
142
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
143
+ slopes.sort()
144
+ medslope = np.median(slopes)
145
+ if method == 'joint':
146
+ medinter = np.median(y - medslope * x)
147
+ else:
148
+ medinter = np.median(y) - medslope * np.median(x)
149
+ # Now compute confidence intervals
150
+ if alpha > 0.5:
151
+ alpha = 1. - alpha
152
+
153
+ z = distributions.norm.ppf(alpha / 2.)
154
+ # This implements (2.6) from Sen (1968)
155
+ _, nxreps = _find_repeats(x)
156
+ _, nyreps = _find_repeats(y)
157
+ nt = len(slopes) # N in Sen (1968)
158
+ ny = len(y) # n in Sen (1968)
159
+ # Equation 2.6 in Sen (1968):
160
+ sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) -
161
+ sum(k * (k-1) * (2*k + 5) for k in nxreps) -
162
+ sum(k * (k-1) * (2*k + 5) for k in nyreps))
163
+ # Find the confidence interval indices in `slopes`
164
+ try:
165
+ sigma = np.sqrt(sigsq)
166
+ Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)
167
+ Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)
168
+ delta = slopes[[Rl, Ru]]
169
+ except (ValueError, IndexError):
170
+ delta = (np.nan, np.nan)
171
+
172
+ return TheilslopesResult(slope=medslope, intercept=medinter,
173
+ low_slope=delta[0], high_slope=delta[1])
174
+
175
+
176
+ def _find_repeats(arr):
177
+ # This function assumes it may clobber its input.
178
+ if len(arr) == 0:
179
+ return np.array(0, np.float64), np.array(0, np.intp)
180
+
181
+ # XXX This cast was previously needed for the Fortran implementation,
182
+ # should we ditch it?
183
+ arr = np.asarray(arr, np.float64).ravel()
184
+ arr.sort()
185
+
186
+ # Taken from NumPy 1.9's np.unique.
187
+ change = np.concatenate(([True], arr[1:] != arr[:-1]))
188
+ unique = arr[change]
189
+ change_idx = np.concatenate(np.nonzero(change) + ([arr.size],))
190
+ freq = np.diff(change_idx)
191
+ atleast2 = freq > 1
192
+ return unique[atleast2], freq[atleast2]
193
+
194
+
195
+ def siegelslopes(y, x=None, method="hierarchical"):
196
+ r"""
197
+ Computes the Siegel estimator for a set of points (x, y).
198
+
199
+ `siegelslopes` implements a method for robust linear regression
200
+ using repeated medians (see [1]_) to fit a line to the points (x, y).
201
+ The method is robust to outliers with an asymptotic breakdown point
202
+ of 50%.
203
+
204
+ Parameters
205
+ ----------
206
+ y : array_like
207
+ Dependent variable.
208
+ x : array_like or None, optional
209
+ Independent variable. If None, use ``arange(len(y))`` instead.
210
+ method : {'hierarchical', 'separate'}
211
+ If 'hierarchical', estimate the intercept using the estimated
212
+ slope ``slope`` (default option).
213
+ If 'separate', estimate the intercept independent of the estimated
214
+ slope. See Notes for details.
215
+
216
+ Returns
217
+ -------
218
+ result : ``SiegelslopesResult`` instance
219
+ The return value is an object with the following attributes:
220
+
221
+ slope : float
222
+ Estimate of the slope of the regression line.
223
+ intercept : float
224
+ Estimate of the intercept of the regression line.
225
+
226
+ See Also
227
+ --------
228
+ theilslopes : a similar technique without repeated medians
229
+
230
+ Notes
231
+ -----
232
+ With ``n = len(y)``, compute ``m_j`` as the median of
233
+ the slopes from the point ``(x[j], y[j])`` to all other `n-1` points.
234
+ ``slope`` is then the median of all slopes ``m_j``.
235
+ Two ways are given to estimate the intercept in [1]_ which can be chosen
236
+ via the parameter ``method``.
237
+ The hierarchical approach uses the estimated slope ``slope``
238
+ and computes ``intercept`` as the median of ``y - slope*x``.
239
+ The other approach estimates the intercept separately as follows: for
240
+ each point ``(x[j], y[j])``, compute the intercepts of all the `n-1`
241
+ lines through the remaining points and take the median ``i_j``.
242
+ ``intercept`` is the median of the ``i_j``.
243
+
244
+ The implementation computes `n` times the median of a vector of size `n`
245
+ which can be slow for large vectors. There are more efficient algorithms
246
+ (see [2]_) which are not implemented here.
247
+
248
+ For compatibility with older versions of SciPy, the return value acts
249
+ like a ``namedtuple`` of length 2, with fields ``slope`` and
250
+ ``intercept``, so one can continue to write::
251
+
252
+ slope, intercept = siegelslopes(y, x)
253
+
254
+ References
255
+ ----------
256
+ .. [1] A. Siegel, "Robust Regression Using Repeated Medians",
257
+ Biometrika, Vol. 69, pp. 242-244, 1982.
258
+
259
+ .. [2] A. Stein and M. Werman, "Finding the repeated median regression
260
+ line", Proceedings of the Third Annual ACM-SIAM Symposium on
261
+ Discrete Algorithms, pp. 409-413, 1992.
262
+
263
+ Examples
264
+ --------
265
+ >>> import numpy as np
266
+ >>> from scipy import stats
267
+ >>> import matplotlib.pyplot as plt
268
+
269
+ >>> x = np.linspace(-5, 5, num=150)
270
+ >>> y = x + np.random.normal(size=x.size)
271
+ >>> y[11:15] += 10 # add outliers
272
+ >>> y[-5:] -= 7
273
+
274
+ Compute the slope and intercept. For comparison, also compute the
275
+ least-squares fit with `linregress`:
276
+
277
+ >>> res = stats.siegelslopes(y, x)
278
+ >>> lsq_res = stats.linregress(x, y)
279
+
280
+ Plot the results. The Siegel regression line is shown in red. The green
281
+ line shows the least-squares fit for comparison.
282
+
283
+ >>> fig = plt.figure()
284
+ >>> ax = fig.add_subplot(111)
285
+ >>> ax.plot(x, y, 'b.')
286
+ >>> ax.plot(x, res[1] + res[0] * x, 'r-')
287
+ >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
288
+ >>> plt.show()
289
+
290
+ """
291
+ if method not in ['hierarchical', 'separate']:
292
+ raise ValueError("method can only be 'hierarchical' or 'separate'")
293
+ y = np.asarray(y).ravel()
294
+ if x is None:
295
+ x = np.arange(len(y), dtype=float)
296
+ else:
297
+ x = np.asarray(x, dtype=float).ravel()
298
+ if len(x) != len(y):
299
+ raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
300
+ dtype = np.result_type(x, y, np.float32) # use at least float32
301
+ y, x = y.astype(dtype), x.astype(dtype)
302
+ medslope, medinter = siegelslopes_pythran(y, x, method)
303
+ return SiegelslopesResult(slope=medslope, intercept=medinter)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_py.py ADDED
The diff for this file is too large to render. See raw diff
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_stats_pythran.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3382ceef44ec174b3454977fada0301904c7d5f3256689e2c6eb94a10e4bee6e
3
+ size 182392
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_survival.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import TYPE_CHECKING, Literal
3
+ import warnings
4
+
5
+ import numpy as np
6
+ from scipy import special, interpolate, stats
7
+ from scipy.stats._censored_data import CensoredData
8
+ from scipy.stats._common import ConfidenceInterval
9
+
10
+ if TYPE_CHECKING:
11
+ import numpy.typing as npt
12
+
13
+
14
+ __all__ = ['ecdf', 'logrank']
15
+
16
+
17
+ @dataclass
18
+ class EmpiricalDistributionFunction:
19
+ """An empirical distribution function produced by `scipy.stats.ecdf`
20
+
21
+ Attributes
22
+ ----------
23
+ quantiles : ndarray
24
+ The unique values of the sample from which the
25
+ `EmpiricalDistributionFunction` was estimated.
26
+ probabilities : ndarray
27
+ The point estimates of the cumulative distribution function (CDF) or
28
+ its complement, the survival function (SF), corresponding with
29
+ `quantiles`.
30
+ """
31
+ quantiles: np.ndarray
32
+ probabilities: np.ndarray
33
+ # Exclude these from __str__
34
+ _n: np.ndarray = field(repr=False) # number "at risk"
35
+ _d: np.ndarray = field(repr=False) # number of "deaths"
36
+ _sf: np.ndarray = field(repr=False) # survival function for var estimate
37
+ _kind: str = field(repr=False) # type of function: "cdf" or "sf"
38
+
39
+ def __init__(self, q, p, n, d, kind):
40
+ self.probabilities = p
41
+ self.quantiles = q
42
+ self._n = n
43
+ self._d = d
44
+ self._sf = p if kind == 'sf' else 1 - p
45
+ self._kind = kind
46
+
47
+ f0 = 1 if kind == 'sf' else 0 # leftmost function value
48
+ f1 = 1 - f0
49
+ # fill_value can't handle edge cases at infinity
50
+ x = np.insert(q, [0, len(q)], [-np.inf, np.inf])
51
+ y = np.insert(p, [0, len(p)], [f0, f1])
52
+ # `or` conditions handle the case of empty x, points
53
+ self._f = interpolate.interp1d(x, y, kind='previous',
54
+ assume_sorted=True)
55
+
56
+ def evaluate(self, x):
57
+ """Evaluate the empirical CDF/SF function at the input.
58
+
59
+ Parameters
60
+ ----------
61
+ x : ndarray
62
+ Argument to the CDF/SF
63
+
64
+ Returns
65
+ -------
66
+ y : ndarray
67
+ The CDF/SF evaluated at the input
68
+ """
69
+ return self._f(x)
70
+
71
+ def plot(self, ax=None, **matplotlib_kwargs):
72
+ """Plot the empirical distribution function
73
+
74
+ Available only if ``matplotlib`` is installed.
75
+
76
+ Parameters
77
+ ----------
78
+ ax : matplotlib.axes.Axes
79
+ Axes object to draw the plot onto, otherwise uses the current Axes.
80
+
81
+ **matplotlib_kwargs : dict, optional
82
+ Keyword arguments passed directly to `matplotlib.axes.Axes.step`.
83
+ Unless overridden, ``where='post'``.
84
+
85
+ Returns
86
+ -------
87
+ lines : list of `matplotlib.lines.Line2D`
88
+ Objects representing the plotted data
89
+ """
90
+ try:
91
+ import matplotlib # noqa: F401
92
+ except ModuleNotFoundError as exc:
93
+ message = "matplotlib must be installed to use method `plot`."
94
+ raise ModuleNotFoundError(message) from exc
95
+
96
+ if ax is None:
97
+ import matplotlib.pyplot as plt
98
+ ax = plt.gca()
99
+
100
+ kwargs = {'where': 'post'}
101
+ kwargs.update(matplotlib_kwargs)
102
+
103
+ delta = np.ptp(self.quantiles)*0.05 # how far past sample edge to plot
104
+ q = self.quantiles
105
+ q = [q[0] - delta] + list(q) + [q[-1] + delta]
106
+
107
+ return ax.step(q, self.evaluate(q), **kwargs)
108
+
109
+ def confidence_interval(self, confidence_level=0.95, *, method='linear'):
110
+ """Compute a confidence interval around the CDF/SF point estimate
111
+
112
+ Parameters
113
+ ----------
114
+ confidence_level : float, default: 0.95
115
+ Confidence level for the computed confidence interval
116
+
117
+ method : str, {"linear", "log-log"}
118
+ Method used to compute the confidence interval. Options are
119
+ "linear" for the conventional Greenwood confidence interval
120
+ (default) and "log-log" for the "exponential Greenwood",
121
+ log-negative-log-transformed confidence interval.
122
+
123
+ Returns
124
+ -------
125
+ ci : ``ConfidenceInterval``
126
+ An object with attributes ``low`` and ``high``, instances of
127
+ `~scipy.stats._result_classes.EmpiricalDistributionFunction` that
128
+ represent the lower and upper bounds (respectively) of the
129
+ confidence interval.
130
+
131
+ Notes
132
+ -----
133
+ Confidence intervals are computed according to the Greenwood formula
134
+ (``method='linear'``) or the more recent "exponential Greenwood"
135
+ formula (``method='log-log'``) as described in [1]_. The conventional
136
+ Greenwood formula can result in lower confidence limits less than 0
137
+ and upper confidence limits greater than 1; these are clipped to the
138
+ unit interval. NaNs may be produced by either method; these are
139
+ features of the formulas.
140
+
141
+ References
142
+ ----------
143
+ .. [1] Sawyer, Stanley. "The Greenwood and Exponential Greenwood
144
+ Confidence Intervals in Survival Analysis."
145
+ https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
146
+
147
+ """
148
+ message = ("Confidence interval bounds do not implement a "
149
+ "`confidence_interval` method.")
150
+ if self._n is None:
151
+ raise NotImplementedError(message)
152
+
153
+ methods = {'linear': self._linear_ci,
154
+ 'log-log': self._loglog_ci}
155
+
156
+ message = f"`method` must be one of {set(methods)}."
157
+ if method.lower() not in methods:
158
+ raise ValueError(message)
159
+
160
+ message = "`confidence_level` must be a scalar between 0 and 1."
161
+ confidence_level = np.asarray(confidence_level)[()]
162
+ if confidence_level.shape or not (0 <= confidence_level <= 1):
163
+ raise ValueError(message)
164
+
165
+ method_fun = methods[method.lower()]
166
+ low, high = method_fun(confidence_level)
167
+
168
+ message = ("The confidence interval is undefined at some observations."
169
+ " This is a feature of the mathematical formula used, not"
170
+ " an error in its implementation.")
171
+ if np.any(np.isnan(low) | np.isnan(high)):
172
+ warnings.warn(message, RuntimeWarning, stacklevel=2)
173
+
174
+ low, high = np.clip(low, 0, 1), np.clip(high, 0, 1)
175
+ low = EmpiricalDistributionFunction(self.quantiles, low, None, None,
176
+ self._kind)
177
+ high = EmpiricalDistributionFunction(self.quantiles, high, None, None,
178
+ self._kind)
179
+ return ConfidenceInterval(low, high)
180
+
181
+ def _linear_ci(self, confidence_level):
182
+ sf, d, n = self._sf, self._d, self._n
183
+ # When n == d, Greenwood's formula divides by zero.
184
+ # When s != 0, this can be ignored: var == inf, and CI is [0, 1]
185
+ # When s == 0, this results in NaNs. Produce an informative warning.
186
+ with np.errstate(divide='ignore', invalid='ignore'):
187
+ var = sf ** 2 * np.cumsum(d / (n * (n - d)))
188
+
189
+ se = np.sqrt(var)
190
+ z = special.ndtri(1 / 2 + confidence_level / 2)
191
+
192
+ z_se = z * se
193
+ low = self.probabilities - z_se
194
+ high = self.probabilities + z_se
195
+
196
+ return low, high
197
+
198
+ def _loglog_ci(self, confidence_level):
199
+ sf, d, n = self._sf, self._d, self._n
200
+
201
+ with np.errstate(divide='ignore', invalid='ignore'):
202
+ var = 1 / np.log(sf) ** 2 * np.cumsum(d / (n * (n - d)))
203
+
204
+ se = np.sqrt(var)
205
+ z = special.ndtri(1 / 2 + confidence_level / 2)
206
+
207
+ with np.errstate(divide='ignore'):
208
+ lnl_points = np.log(-np.log(sf))
209
+
210
+ z_se = z * se
211
+ low = np.exp(-np.exp(lnl_points + z_se))
212
+ high = np.exp(-np.exp(lnl_points - z_se))
213
+ if self._kind == "cdf":
214
+ low, high = 1-high, 1-low
215
+
216
+ return low, high
217
+
218
+
219
+ @dataclass
220
+ class ECDFResult:
221
+ """ Result object returned by `scipy.stats.ecdf`
222
+
223
+ Attributes
224
+ ----------
225
+ cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
226
+ An object representing the empirical cumulative distribution function.
227
+ sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
228
+ An object representing the complement of the empirical cumulative
229
+ distribution function.
230
+ """
231
+ cdf: EmpiricalDistributionFunction
232
+ sf: EmpiricalDistributionFunction
233
+
234
+ def __init__(self, q, cdf, sf, n, d):
235
+ self.cdf = EmpiricalDistributionFunction(q, cdf, n, d, "cdf")
236
+ self.sf = EmpiricalDistributionFunction(q, sf, n, d, "sf")
237
+
238
+
239
+ def _iv_CensoredData(
240
+ sample: "npt.ArrayLike | CensoredData", param_name: str = "sample"
241
+ ) -> CensoredData:
242
+ """Attempt to convert `sample` to `CensoredData`."""
243
+ if not isinstance(sample, CensoredData):
244
+ try: # takes care of input standardization/validation
245
+ sample = CensoredData(uncensored=sample)
246
+ except ValueError as e:
247
+ message = str(e).replace('uncensored', param_name)
248
+ raise type(e)(message) from e
249
+ return sample
250
+
251
+
252
+ def ecdf(sample: "npt.ArrayLike | CensoredData") -> ECDFResult:
253
+ """Empirical cumulative distribution function of a sample.
254
+
255
+ The empirical cumulative distribution function (ECDF) is a step function
256
+ estimate of the CDF of the distribution underlying a sample. This function
257
+ returns objects representing both the empirical distribution function and
258
+ its complement, the empirical survival function.
259
+
260
+ Parameters
261
+ ----------
262
+ sample : 1D array_like or `scipy.stats.CensoredData`
263
+ Besides array_like, instances of `scipy.stats.CensoredData` containing
264
+ uncensored and right-censored observations are supported. Currently,
265
+ other instances of `scipy.stats.CensoredData` will result in a
266
+ ``NotImplementedError``.
267
+
268
+ Returns
269
+ -------
270
+ res : `~scipy.stats._result_classes.ECDFResult`
271
+ An object with the following attributes.
272
+
273
+ cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
274
+ An object representing the empirical cumulative distribution
275
+ function.
276
+ sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
277
+ An object representing the empirical survival function.
278
+
279
+ The `cdf` and `sf` attributes themselves have the following attributes.
280
+
281
+ quantiles : ndarray
282
+ The unique values in the sample that defines the empirical CDF/SF.
283
+ probabilities : ndarray
284
+ The point estimates of the probabilities corresponding with
285
+ `quantiles`.
286
+
287
+ And the following methods:
288
+
289
+ evaluate(x) :
290
+ Evaluate the CDF/SF at the argument.
291
+
292
+ plot(ax) :
293
+ Plot the CDF/SF on the provided axes.
294
+
295
+ confidence_interval(confidence_level=0.95) :
296
+ Compute the confidence interval around the CDF/SF at the values in
297
+ `quantiles`.
298
+
299
+ Notes
300
+ -----
301
+ When each observation of the sample is a precise measurement, the ECDF
302
+ steps up by ``1/len(sample)`` at each of the observations [1]_.
303
+
304
+ When observations are lower bounds, upper bounds, or both upper and lower
305
+ bounds, the data is said to be "censored", and `sample` may be provided as
306
+ an instance of `scipy.stats.CensoredData`.
307
+
308
+ For right-censored data, the ECDF is given by the Kaplan-Meier estimator
309
+ [2]_; other forms of censoring are not supported at this time.
310
+
311
+ Confidence intervals are computed according to the Greenwood formula or the
312
+ more recent "Exponential Greenwood" formula as described in [4]_.
313
+
314
+ References
315
+ ----------
316
+ .. [1] Conover, William Jay. Practical nonparametric statistics. Vol. 350.
317
+ John Wiley & Sons, 1999.
318
+
319
+ .. [2] Kaplan, Edward L., and Paul Meier. "Nonparametric estimation from
320
+ incomplete observations." Journal of the American statistical
321
+ association 53.282 (1958): 457-481.
322
+
323
+ .. [3] Goel, Manish Kumar, Pardeep Khanna, and Jugal Kishore.
324
+ "Understanding survival analysis: Kaplan-Meier estimate."
325
+ International journal of Ayurveda research 1.4 (2010): 274.
326
+
327
+ .. [4] Sawyer, Stanley. "The Greenwood and Exponential Greenwood Confidence
328
+ Intervals in Survival Analysis."
329
+ https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
330
+
331
+ Examples
332
+ --------
333
+ **Uncensored Data**
334
+
335
+ As in the example from [1]_ page 79, five boys were selected at random from
336
+ those in a single high school. Their one-mile run times were recorded as
337
+ follows.
338
+
339
+ >>> sample = [6.23, 5.58, 7.06, 6.42, 5.20] # one-mile run times (minutes)
340
+
341
+ The empirical distribution function, which approximates the distribution
342
+ function of one-mile run times of the population from which the boys were
343
+ sampled, is calculated as follows.
344
+
345
+ >>> from scipy import stats
346
+ >>> res = stats.ecdf(sample)
347
+ >>> res.cdf.quantiles
348
+ array([5.2 , 5.58, 6.23, 6.42, 7.06])
349
+ >>> res.cdf.probabilities
350
+ array([0.2, 0.4, 0.6, 0.8, 1. ])
351
+
352
+ To plot the result as a step function:
353
+
354
+ >>> import matplotlib.pyplot as plt
355
+ >>> ax = plt.subplot()
356
+ >>> res.cdf.plot(ax)
357
+ >>> ax.set_xlabel('One-Mile Run Time (minutes)')
358
+ >>> ax.set_ylabel('Empirical CDF')
359
+ >>> plt.show()
360
+
361
+ **Right-censored Data**
362
+
363
+ As in the example from [1]_ page 91, the lives of ten car fanbelts were
364
+ tested. Five tests concluded because the fanbelt being tested broke, but
365
+ the remaining tests concluded for other reasons (e.g. the study ran out of
366
+ funding, but the fanbelt was still functional). The mileage driven
367
+ with the fanbelts were recorded as follows.
368
+
369
+ >>> broken = [77, 47, 81, 56, 80] # in thousands of miles driven
370
+ >>> unbroken = [62, 60, 43, 71, 37]
371
+
372
+ Precise survival times of the fanbelts that were still functional at the
373
+ end of the tests are unknown, but they are known to exceed the values
374
+ recorded in ``unbroken``. Therefore, these observations are said to be
375
+ "right-censored", and the data is represented using
376
+ `scipy.stats.CensoredData`.
377
+
378
+ >>> sample = stats.CensoredData(uncensored=broken, right=unbroken)
379
+
380
+ The empirical survival function is calculated as follows.
381
+
382
+ >>> res = stats.ecdf(sample)
383
+ >>> res.sf.quantiles
384
+ array([37., 43., 47., 56., 60., 62., 71., 77., 80., 81.])
385
+ >>> res.sf.probabilities
386
+ array([1. , 1. , 0.875, 0.75 , 0.75 , 0.75 , 0.75 , 0.5 , 0.25 , 0. ])
387
+
388
+ To plot the result as a step function:
389
+
390
+ >>> ax = plt.subplot()
391
+ >>> res.sf.plot(ax)
392
+ >>> ax.set_xlabel('Fanbelt Survival Time (thousands of miles)')
393
+ >>> ax.set_ylabel('Empirical SF')
394
+ >>> plt.show()
395
+
396
+ """
397
+ sample = _iv_CensoredData(sample)
398
+
399
+ if sample.num_censored() == 0:
400
+ res = _ecdf_uncensored(sample._uncensor())
401
+ elif sample.num_censored() == sample._right.size:
402
+ res = _ecdf_right_censored(sample)
403
+ else:
404
+ # Support additional censoring options in follow-up PRs
405
+ message = ("Currently, only uncensored and right-censored data is "
406
+ "supported.")
407
+ raise NotImplementedError(message)
408
+
409
+ t, cdf, sf, n, d = res
410
+ return ECDFResult(t, cdf, sf, n, d)
411
+
412
+
413
+ def _ecdf_uncensored(sample):
414
+ sample = np.sort(sample)
415
+ x, counts = np.unique(sample, return_counts=True)
416
+
417
+ # [1].81 "the fraction of [observations] that are less than or equal to x
418
+ events = np.cumsum(counts)
419
+ n = sample.size
420
+ cdf = events / n
421
+
422
+ # [1].89 "the relative frequency of the sample that exceeds x in value"
423
+ sf = 1 - cdf
424
+
425
+ at_risk = np.concatenate(([n], n - events[:-1]))
426
+ return x, cdf, sf, at_risk, counts
427
+
428
+
429
+ def _ecdf_right_censored(sample):
430
+ # It is conventional to discuss right-censored data in terms of
431
+ # "survival time", "death", and "loss" (e.g. [2]). We'll use that
432
+ # terminology here.
433
+ # This implementation was influenced by the references cited and also
434
+ # https://www.youtube.com/watch?v=lxoWsVco_iM
435
+ # https://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator
436
+ # In retrospect it is probably most easily compared against [3].
437
+ # Ultimately, the data needs to be sorted, so this implementation is
438
+ # written to avoid a separate call to `unique` after sorting. In hope of
439
+ # better performance on large datasets, it also computes survival
440
+ # probabilities at unique times only rather than at each observation.
441
+ tod = sample._uncensored # time of "death"
442
+ tol = sample._right # time of "loss"
443
+ times = np.concatenate((tod, tol))
444
+ died = np.asarray([1]*tod.size + [0]*tol.size)
445
+
446
+ # sort by times
447
+ i = np.argsort(times)
448
+ times = times[i]
449
+ died = died[i]
450
+ at_risk = np.arange(times.size, 0, -1)
451
+
452
+ # logical indices of unique times
453
+ j = np.diff(times, prepend=-np.inf, append=np.inf) > 0
454
+ j_l = j[:-1] # first instances of unique times
455
+ j_r = j[1:] # last instances of unique times
456
+
457
+ # get number at risk and deaths at each unique time
458
+ t = times[j_l] # unique times
459
+ n = at_risk[j_l] # number at risk at each unique time
460
+ cd = np.cumsum(died)[j_r] # cumulative deaths up to/including unique times
461
+ d = np.diff(cd, prepend=0) # deaths at each unique time
462
+
463
+ # compute survival function
464
+ sf = np.cumprod((n - d) / n)
465
+ cdf = 1 - sf
466
+ return t, cdf, sf, n, d
467
+
468
+
469
+ @dataclass
470
+ class LogRankResult:
471
+ """Result object returned by `scipy.stats.logrank`.
472
+
473
+ Attributes
474
+ ----------
475
+ statistic : float ndarray
476
+ The computed statistic (defined below). Its magnitude is the
477
+ square root of the magnitude returned by most other logrank test
478
+ implementations.
479
+ pvalue : float ndarray
480
+ The computed p-value of the test.
481
+ """
482
+ statistic: np.ndarray
483
+ pvalue: np.ndarray
484
+
485
+
486
+ def logrank(
487
+ x: "npt.ArrayLike | CensoredData",
488
+ y: "npt.ArrayLike | CensoredData",
489
+ alternative: Literal['two-sided', 'less', 'greater'] = "two-sided"
490
+ ) -> LogRankResult:
491
+ r"""Compare the survival distributions of two samples via the logrank test.
492
+
493
+ Parameters
494
+ ----------
495
+ x, y : array_like or CensoredData
496
+ Samples to compare based on their empirical survival functions.
497
+ alternative : {'two-sided', 'less', 'greater'}, optional
498
+ Defines the alternative hypothesis.
499
+
500
+ The null hypothesis is that the survival distributions of the two
501
+ groups, say *X* and *Y*, are identical.
502
+
503
+ The following alternative hypotheses [4]_ are available (default is
504
+ 'two-sided'):
505
+
506
+ * 'two-sided': the survival distributions of the two groups are not
507
+ identical.
508
+ * 'less': survival of group *X* is favored: the group *X* failure rate
509
+ function is less than the group *Y* failure rate function at some
510
+ times.
511
+ * 'greater': survival of group *Y* is favored: the group *X* failure
512
+ rate function is greater than the group *Y* failure rate function at
513
+ some times.
514
+
515
+ Returns
516
+ -------
517
+ res : `~scipy.stats._result_classes.LogRankResult`
518
+ An object containing attributes:
519
+
520
+ statistic : float ndarray
521
+ The computed statistic (defined below). Its magnitude is the
522
+ square root of the magnitude returned by most other logrank test
523
+ implementations.
524
+ pvalue : float ndarray
525
+ The computed p-value of the test.
526
+
527
+ See Also
528
+ --------
529
+ scipy.stats.ecdf
530
+
531
+ Notes
532
+ -----
533
+ The logrank test [1]_ compares the observed number of events to
534
+ the expected number of events under the null hypothesis that the two
535
+ samples were drawn from the same distribution. The statistic is
536
+
537
+ .. math::
538
+
539
+ Z_i = \frac{\sum_{j=1}^J(O_{i,j}-E_{i,j})}{\sqrt{\sum_{j=1}^J V_{i,j}}}
540
+ \rightarrow \mathcal{N}(0,1)
541
+
542
+ where
543
+
544
+ .. math::
545
+
546
+ E_{i,j} = O_j \frac{N_{i,j}}{N_j},
547
+ \qquad
548
+ V_{i,j} = E_{i,j} \left(\frac{N_j-O_j}{N_j}\right)
549
+ \left(\frac{N_j-N_{i,j}}{N_j-1}\right),
550
+
551
+ :math:`i` denotes the group (i.e. it may assume values :math:`x` or
552
+ :math:`y`, or it may be omitted to refer to the combined sample)
553
+ :math:`j` denotes the time (at which an event occurred),
554
+ :math:`N` is the number of subjects at risk just before an event occurred,
555
+ and :math:`O` is the observed number of events at that time.
556
+
557
+ The ``statistic`` :math:`Z_x` returned by `logrank` is the (signed) square
558
+ root of the statistic returned by many other implementations. Under the
559
+ null hypothesis, :math:`Z_x**2` is asymptotically distributed according to
560
+ the chi-squared distribution with one degree of freedom. Consequently,
561
+ :math:`Z_x` is asymptotically distributed according to the standard normal
562
+ distribution. The advantage of using :math:`Z_x` is that the sign
563
+ information (i.e. whether the observed number of events tends to be less
564
+ than or greater than the number expected under the null hypothesis) is
565
+ preserved, allowing `scipy.stats.logrank` to offer one-sided alternative
566
+ hypotheses.
567
+
568
+ References
569
+ ----------
570
+ .. [1] Mantel N. "Evaluation of survival data and two new rank order
571
+ statistics arising in its consideration."
572
+ Cancer Chemotherapy Reports, 50(3):163-170, PMID: 5910392, 1966
573
+ .. [2] Bland, Altman, "The logrank test", BMJ, 328:1073,
574
+ :doi:`10.1136/bmj.328.7447.1073`, 2004
575
+ .. [3] "Logrank test", Wikipedia,
576
+ https://en.wikipedia.org/wiki/Logrank_test
577
+ .. [4] Brown, Mark. "On the choice of variance for the log rank test."
578
+ Biometrika 71.1 (1984): 65-74.
579
+ .. [5] Klein, John P., and Melvin L. Moeschberger. Survival analysis:
580
+ techniques for censored and truncated data. Vol. 1230. New York:
581
+ Springer, 2003.
582
+
583
+ Examples
584
+ --------
585
+ Reference [2]_ compared the survival times of patients with two different
586
+ types of recurrent malignant gliomas. The samples below record the time
587
+ (number of weeks) for which each patient participated in the study. The
588
+ `scipy.stats.CensoredData` class is used because the data is
589
+ right-censored: the uncensored observations correspond with observed deaths
590
+ whereas the censored observations correspond with the patient leaving the
591
+ study for another reason.
592
+
593
+ >>> from scipy import stats
594
+ >>> x = stats.CensoredData(
595
+ ... uncensored=[6, 13, 21, 30, 37, 38, 49, 50,
596
+ ... 63, 79, 86, 98, 202, 219],
597
+ ... right=[31, 47, 80, 82, 82, 149]
598
+ ... )
599
+ >>> y = stats.CensoredData(
600
+ ... uncensored=[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24,
601
+ ... 25, 28,30, 33, 35, 37, 40, 40, 46, 48, 76, 81,
602
+ ... 82, 91, 112, 181],
603
+ ... right=[34, 40, 70]
604
+ ... )
605
+
606
+ We can calculate and visualize the empirical survival functions
607
+ of both groups as follows.
608
+
609
+ >>> import numpy as np
610
+ >>> import matplotlib.pyplot as plt
611
+ >>> ax = plt.subplot()
612
+ >>> ecdf_x = stats.ecdf(x)
613
+ >>> ecdf_x.sf.plot(ax, label='Astrocytoma')
614
+ >>> ecdf_y = stats.ecdf(y)
615
+ >>> ecdf_y.sf.plot(ax, label='Glioblastoma')
616
+ >>> ax.set_xlabel('Time to death (weeks)')
617
+ >>> ax.set_ylabel('Empirical SF')
618
+ >>> plt.legend()
619
+ >>> plt.show()
620
+
621
+ Visual inspection of the empirical survival functions suggests that the
622
+ survival times tend to be different between the two groups. To formally
623
+ assess whether the difference is significant at the 1% level, we use the
624
+ logrank test.
625
+
626
+ >>> res = stats.logrank(x=x, y=y)
627
+ >>> res.statistic
628
+ -2.73799
629
+ >>> res.pvalue
630
+ 0.00618
631
+
632
+ The p-value is less than 1%, so we can consider the data to be evidence
633
+ against the null hypothesis in favor of the alternative that there is a
634
+ difference between the two survival functions.
635
+
636
+ """
637
+ # Input validation. `alternative` IV handled in `_get_pvalue` below.
638
+ x = _iv_CensoredData(sample=x, param_name='x')
639
+ y = _iv_CensoredData(sample=y, param_name='y')
640
+
641
+ # Combined sample. (Under H0, the two groups are identical.)
642
+ xy = CensoredData(
643
+ uncensored=np.concatenate((x._uncensored, y._uncensored)),
644
+ right=np.concatenate((x._right, y._right))
645
+ )
646
+
647
+ # Extract data from the combined sample
648
+ res = ecdf(xy)
649
+ idx = res.sf._d.astype(bool) # indices of observed events
650
+ times_xy = res.sf.quantiles[idx] # unique times of observed events
651
+ at_risk_xy = res.sf._n[idx] # combined number of subjects at risk
652
+ deaths_xy = res.sf._d[idx] # combined number of events
653
+
654
+ # Get the number at risk within each sample.
655
+ # First compute the number at risk in group X at each of the `times_xy`.
656
+ # Could use `interpolate_1d`, but this is more compact.
657
+ res_x = ecdf(x)
658
+ i = np.searchsorted(res_x.sf.quantiles, times_xy)
659
+ at_risk_x = np.append(res_x.sf._n, 0)[i] # 0 at risk after last time
660
+ # Subtract from the combined number at risk to get number at risk in Y
661
+ at_risk_y = at_risk_xy - at_risk_x
662
+
663
+ # Compute the variance.
664
+ num = at_risk_x * at_risk_y * deaths_xy * (at_risk_xy - deaths_xy)
665
+ den = at_risk_xy**2 * (at_risk_xy - 1)
666
+ # Note: when `at_risk_xy == 1`, we would have `at_risk_xy - 1 == 0` in the
667
+ # numerator and denominator. Simplifying the fraction symbolically, we
668
+ # would always find the overall quotient to be zero, so don't compute it.
669
+ i = at_risk_xy > 1
670
+ sum_var = np.sum(num[i]/den[i])
671
+
672
+ # Get the observed and expected number of deaths in group X
673
+ n_died_x = x._uncensored.size
674
+ sum_exp_deaths_x = np.sum(at_risk_x * (deaths_xy/at_risk_xy))
675
+
676
+ # Compute the statistic. This is the square root of that in references.
677
+ statistic = (n_died_x - sum_exp_deaths_x)/np.sqrt(sum_var)
678
+
679
+ # Equivalent to chi2(df=1).sf(statistic**2) when alternative='two-sided'
680
+ norm = stats._stats_py._SimpleNormal()
681
+ pvalue = stats._stats_py._get_pvalue(statistic, norm, alternative, xp=np)
682
+
683
+ return LogRankResult(statistic=statistic[()], pvalue=pvalue[()])
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_tukeylambda_stats.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy import poly1d
3
+ from scipy.special import beta
4
+
5
+
6
+ # The following code was used to generate the Pade coefficients for the
7
+ # Tukey Lambda variance function. Version 0.17 of mpmath was used.
8
+ #---------------------------------------------------------------------------
9
+ # import mpmath as mp
10
+ #
11
+ # mp.mp.dps = 60
12
+ #
13
+ # one = mp.mpf(1)
14
+ # two = mp.mpf(2)
15
+ #
16
+ # def mpvar(lam):
17
+ # if lam == 0:
18
+ # v = mp.pi**2 / three
19
+ # else:
20
+ # v = (two / lam**2) * (one / (one + two*lam) -
21
+ # mp.beta(lam + one, lam + one))
22
+ # return v
23
+ #
24
+ # t = mp.taylor(mpvar, 0, 8)
25
+ # p, q = mp.pade(t, 4, 4)
26
+ # print("p =", [mp.fp.mpf(c) for c in p])
27
+ # print("q =", [mp.fp.mpf(c) for c in q])
28
+ #---------------------------------------------------------------------------
29
+
30
+ # Pade coefficients for the Tukey Lambda variance function.
31
+ _tukeylambda_var_pc = [3.289868133696453, 0.7306125098871127,
32
+ -0.5370742306855439, 0.17292046290190008,
33
+ -0.02371146284628187]
34
+ _tukeylambda_var_qc = [1.0, 3.683605511659861, 4.184152498888124,
35
+ 1.7660926747377275, 0.2643989311168465]
36
+
37
+ # numpy.poly1d instances for the numerator and denominator of the
38
+ # Pade approximation to the Tukey Lambda variance.
39
+ _tukeylambda_var_p = poly1d(_tukeylambda_var_pc[::-1])
40
+ _tukeylambda_var_q = poly1d(_tukeylambda_var_qc[::-1])
41
+
42
+
43
+ def tukeylambda_variance(lam):
44
+ """Variance of the Tukey Lambda distribution.
45
+
46
+ Parameters
47
+ ----------
48
+ lam : array_like
49
+ The lambda values at which to compute the variance.
50
+
51
+ Returns
52
+ -------
53
+ v : ndarray
54
+ The variance. For lam < -0.5, the variance is not defined, so
55
+ np.nan is returned. For lam = 0.5, np.inf is returned.
56
+
57
+ Notes
58
+ -----
59
+ In an interval around lambda=0, this function uses the [4,4] Pade
60
+ approximation to compute the variance. Otherwise it uses the standard
61
+ formula (https://en.wikipedia.org/wiki/Tukey_lambda_distribution). The
62
+ Pade approximation is used because the standard formula has a removable
63
+ discontinuity at lambda = 0, and does not produce accurate numerical
64
+ results near lambda = 0.
65
+ """
66
+ lam = np.asarray(lam)
67
+ shp = lam.shape
68
+ lam = np.atleast_1d(lam).astype(np.float64)
69
+
70
+ # For absolute values of lam less than threshold, use the Pade
71
+ # approximation.
72
+ threshold = 0.075
73
+
74
+ # Play games with masks to implement the conditional evaluation of
75
+ # the distribution.
76
+ # lambda < -0.5: var = nan
77
+ low_mask = lam < -0.5
78
+ # lambda == -0.5: var = inf
79
+ neghalf_mask = lam == -0.5
80
+ # abs(lambda) < threshold: use Pade approximation
81
+ small_mask = np.abs(lam) < threshold
82
+ # else the "regular" case: use the explicit formula.
83
+ reg_mask = ~(low_mask | neghalf_mask | small_mask)
84
+
85
+ # Get the 'lam' values for the cases where they are needed.
86
+ small = lam[small_mask]
87
+ reg = lam[reg_mask]
88
+
89
+ # Compute the function for each case.
90
+ v = np.empty_like(lam)
91
+ v[low_mask] = np.nan
92
+ v[neghalf_mask] = np.inf
93
+ if small.size > 0:
94
+ # Use the Pade approximation near lambda = 0.
95
+ v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small)
96
+ if reg.size > 0:
97
+ v[reg_mask] = (2.0 / reg**2) * (1.0 / (1.0 + 2 * reg) -
98
+ beta(reg + 1, reg + 1))
99
+ v.shape = shp
100
+ return v
101
+
102
+
103
+ # The following code was used to generate the Pade coefficients for the
104
+ # Tukey Lambda kurtosis function. Version 0.17 of mpmath was used.
105
+ #---------------------------------------------------------------------------
106
+ # import mpmath as mp
107
+ #
108
+ # mp.mp.dps = 60
109
+ #
110
+ # one = mp.mpf(1)
111
+ # two = mp.mpf(2)
112
+ # three = mp.mpf(3)
113
+ # four = mp.mpf(4)
114
+ #
115
+ # def mpkurt(lam):
116
+ # if lam == 0:
117
+ # k = mp.mpf(6)/5
118
+ # else:
119
+ # numer = (one/(four*lam+one) - four*mp.beta(three*lam+one, lam+one) +
120
+ # three*mp.beta(two*lam+one, two*lam+one))
121
+ # denom = two*(one/(two*lam+one) - mp.beta(lam+one,lam+one))**2
122
+ # k = numer / denom - three
123
+ # return k
124
+ #
125
+ # # There is a bug in mpmath 0.17: when we use the 'method' keyword of the
126
+ # # taylor function and we request a degree 9 Taylor polynomial, we actually
127
+ # # get degree 8.
128
+ # t = mp.taylor(mpkurt, 0, 9, method='quad', radius=0.01)
129
+ # t = [mp.chop(c, tol=1e-15) for c in t]
130
+ # p, q = mp.pade(t, 4, 4)
131
+ # print("p =", [mp.fp.mpf(c) for c in p])
132
+ # print("q =", [mp.fp.mpf(c) for c in q])
133
+ #---------------------------------------------------------------------------
134
+
135
+ # Pade coefficients for the Tukey Lambda kurtosis function.
136
+ _tukeylambda_kurt_pc = [1.2, -5.853465139719495, -22.653447381131077,
137
+ 0.20601184383406815, 4.59796302262789]
138
+ _tukeylambda_kurt_qc = [1.0, 7.171149192233599, 12.96663094361842,
139
+ 0.43075235247853005, -2.789746758009912]
140
+
141
+ # numpy.poly1d instances for the numerator and denominator of the
142
+ # Pade approximation to the Tukey Lambda kurtosis.
143
+ _tukeylambda_kurt_p = poly1d(_tukeylambda_kurt_pc[::-1])
144
+ _tukeylambda_kurt_q = poly1d(_tukeylambda_kurt_qc[::-1])
145
+
146
+
147
+ def tukeylambda_kurtosis(lam):
148
+ """Kurtosis of the Tukey Lambda distribution.
149
+
150
+ Parameters
151
+ ----------
152
+ lam : array_like
153
+ The lambda values at which to compute the variance.
154
+
155
+ Returns
156
+ -------
157
+ v : ndarray
158
+ The variance. For lam < -0.25, the variance is not defined, so
159
+ np.nan is returned. For lam = 0.25, np.inf is returned.
160
+
161
+ """
162
+ lam = np.asarray(lam)
163
+ shp = lam.shape
164
+ lam = np.atleast_1d(lam).astype(np.float64)
165
+
166
+ # For absolute values of lam less than threshold, use the Pade
167
+ # approximation.
168
+ threshold = 0.055
169
+
170
+ # Use masks to implement the conditional evaluation of the kurtosis.
171
+ # lambda < -0.25: kurtosis = nan
172
+ low_mask = lam < -0.25
173
+ # lambda == -0.25: kurtosis = inf
174
+ negqrtr_mask = lam == -0.25
175
+ # lambda near 0: use Pade approximation
176
+ small_mask = np.abs(lam) < threshold
177
+ # else the "regular" case: use the explicit formula.
178
+ reg_mask = ~(low_mask | negqrtr_mask | small_mask)
179
+
180
+ # Get the 'lam' values for the cases where they are needed.
181
+ small = lam[small_mask]
182
+ reg = lam[reg_mask]
183
+
184
+ # Compute the function for each case.
185
+ k = np.empty_like(lam)
186
+ k[low_mask] = np.nan
187
+ k[negqrtr_mask] = np.inf
188
+ if small.size > 0:
189
+ k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small)
190
+ if reg.size > 0:
191
+ numer = (1.0 / (4 * reg + 1) - 4 * beta(3 * reg + 1, reg + 1) +
192
+ 3 * beta(2 * reg + 1, 2 * reg + 1))
193
+ denom = 2 * (1.0/(2 * reg + 1) - beta(reg + 1, reg + 1))**2
194
+ k[reg_mask] = numer / denom - 3
195
+
196
+ # The return value will be a numpy array; resetting the shape ensures that
197
+ # if `lam` was a scalar, the return value is a 0-d array.
198
+ k.shape = shp
199
+ return k
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/__init__.py ADDED
File without changes
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c489e54afb47f1682d2e100983f88f56a6fbbfa3ca7729561716baeb702a320a
3
+ size 1577840
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from typing import (overload, Callable, NamedTuple, Protocol)
3
+ import numpy.typing as npt
4
+ from scipy._lib._util import SeedType
5
+ import scipy.stats as stats
6
+
7
+
8
+ ArrayLike0D = bool | int | float | complex | str | bytes | np.generic
9
+
10
+
11
+ __all__: list[str]
12
+
13
+
14
+ class UNURANError(RuntimeError):
15
+ ...
16
+
17
+
18
+ class Method:
19
+ @overload
20
+ def rvs(self, size: None = ...) -> float | int: ... # type: ignore[overload-overlap]
21
+ @overload
22
+ def rvs(self, size: int | tuple[int, ...] = ...) -> np.ndarray: ...
23
+ def set_random_state(self, random_state: SeedType) -> None: ...
24
+
25
+
26
+ class TDRDist(Protocol):
27
+ @property
28
+ def pdf(self) -> Callable[..., float]: ...
29
+ @property
30
+ def dpdf(self) -> Callable[..., float]: ...
31
+ @property
32
+ def support(self) -> tuple[float, float]: ...
33
+
34
+
35
+ class TransformedDensityRejection(Method):
36
+ def __init__(self,
37
+ dist: TDRDist,
38
+ *,
39
+ mode: None | float = ...,
40
+ center: None | float = ...,
41
+ domain: None | tuple[float, float] = ...,
42
+ c: float = ...,
43
+ construction_points: int | npt.ArrayLike = ...,
44
+ use_dars: bool = ...,
45
+ max_squeeze_hat_ratio: float = ...,
46
+ random_state: SeedType = ...) -> None: ...
47
+ @property
48
+ def squeeze_hat_ratio(self) -> float: ...
49
+ @property
50
+ def squeeze_area(self) -> float: ...
51
+ @overload
52
+ def ppf_hat(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap]
53
+ @overload
54
+ def ppf_hat(self, u: npt.ArrayLike) -> np.ndarray: ...
55
+
56
+
57
+ class SROUDist(Protocol):
58
+ @property
59
+ def pdf(self) -> Callable[..., float]: ...
60
+ @property
61
+ def support(self) -> tuple[float, float]: ...
62
+
63
+
64
+ class SimpleRatioUniforms(Method):
65
+ def __init__(self,
66
+ dist: SROUDist,
67
+ *,
68
+ mode: None | float = ...,
69
+ pdf_area: float = ...,
70
+ domain: None | tuple[float, float] = ...,
71
+ cdf_at_mode: float = ...,
72
+ random_state: SeedType = ...) -> None: ...
73
+
74
+
75
+ class UError(NamedTuple):
76
+ max_error: float
77
+ mean_absolute_error: float
78
+
79
+ class PINVDist(Protocol):
80
+ @property
81
+ def pdf(self) -> Callable[..., float]: ...
82
+ @property
83
+ def cdf(self) -> Callable[..., float]: ...
84
+ @property
85
+ def logpdf(self) -> Callable[..., float]: ...
86
+
87
+
88
+ class NumericalInversePolynomial(Method):
89
+ def __init__(self,
90
+ dist: PINVDist,
91
+ *,
92
+ mode: None | float = ...,
93
+ center: None | float = ...,
94
+ domain: None | tuple[float, float] = ...,
95
+ order: int = ...,
96
+ u_resolution: float = ...,
97
+ random_state: SeedType = ...) -> None: ...
98
+ @property
99
+ def intervals(self) -> int: ...
100
+ @overload
101
+ def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap]
102
+ @overload
103
+ def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
104
+ @overload
105
+ def cdf(self, x: ArrayLike0D) -> float: ... # type: ignore[overload-overlap]
106
+ @overload
107
+ def cdf(self, x: npt.ArrayLike) -> np.ndarray: ...
108
+ def u_error(self, sample_size: int = ...) -> UError: ...
109
+ def qrvs(self,
110
+ size: None | int | tuple[int, ...] = ...,
111
+ d: None | int = ...,
112
+ qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ...
113
+
114
+
115
+ class HINVDist(Protocol):
116
+ @property
117
+ def pdf(self) -> Callable[..., float]: ...
118
+ @property
119
+ def cdf(self) -> Callable[..., float]: ...
120
+ @property
121
+ def support(self) -> tuple[float, float]: ...
122
+
123
+
124
+ class NumericalInverseHermite(Method):
125
+ def __init__(self,
126
+ dist: HINVDist,
127
+ *,
128
+ domain: None | tuple[float, float] = ...,
129
+ order: int= ...,
130
+ u_resolution: float = ...,
131
+ construction_points: None | npt.ArrayLike = ...,
132
+ max_intervals: int = ...,
133
+ random_state: SeedType = ...) -> None: ...
134
+ @property
135
+ def intervals(self) -> int: ...
136
+ @overload
137
+ def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap]
138
+ @overload
139
+ def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
140
+ def qrvs(self,
141
+ size: None | int | tuple[int, ...] = ...,
142
+ d: None | int = ...,
143
+ qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ...
144
+ def u_error(self, sample_size: int = ...) -> UError: ...
145
+
146
+
147
+ class DAUDist(Protocol):
148
+ @property
149
+ def pmf(self) -> Callable[..., float]: ...
150
+ @property
151
+ def support(self) -> tuple[float, float]: ...
152
+
153
+ class DiscreteAliasUrn(Method):
154
+ def __init__(self,
155
+ dist: npt.ArrayLike | DAUDist,
156
+ *,
157
+ domain: None | tuple[float, float] = ...,
158
+ urn_factor: float = ...,
159
+ random_state: SeedType = ...) -> None: ...
160
+
161
+
162
+ class DGTDist(Protocol):
163
+ @property
164
+ def pmf(self) -> Callable[..., float]: ...
165
+ @property
166
+ def support(self) -> tuple[float, float]: ...
167
+
168
+ class DiscreteGuideTable(Method):
169
+ def __init__(self,
170
+ dist: npt.ArrayLike | DGTDist,
171
+ *,
172
+ domain: None | tuple[float, float] = ...,
173
+ guide_factor: float = ...,
174
+ random_state: SeedType = ...) -> None: ...
175
+ @overload
176
+ def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap]
177
+ @overload
178
+ def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_variation.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from scipy._lib._util import _get_nan
4
+ from scipy._lib._array_api import array_namespace, xp_copysign
5
+
6
+ from ._axis_nan_policy import _axis_nan_policy_factory
7
+
8
+
9
+ @_axis_nan_policy_factory(
10
+ lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
11
+ )
12
+ def variation(a, axis=0, nan_policy='propagate', ddof=0, *, keepdims=False):
13
+ """
14
+ Compute the coefficient of variation.
15
+
16
+ The coefficient of variation is the standard deviation divided by the
17
+ mean. This function is equivalent to::
18
+
19
+ np.std(x, axis=axis, ddof=ddof) / np.mean(x)
20
+
21
+ The default for ``ddof`` is 0, but many definitions of the coefficient
22
+ of variation use the square root of the unbiased sample variance
23
+ for the sample standard deviation, which corresponds to ``ddof=1``.
24
+
25
+ The function does not take the absolute value of the mean of the data,
26
+ so the return value is negative if the mean is negative.
27
+
28
+ Parameters
29
+ ----------
30
+ a : array_like
31
+ Input array.
32
+ axis : int or None, optional
33
+ Axis along which to calculate the coefficient of variation.
34
+ Default is 0. If None, compute over the whole array `a`.
35
+ nan_policy : {'propagate', 'raise', 'omit'}, optional
36
+ Defines how to handle when input contains ``nan``.
37
+ The following options are available:
38
+
39
+ * 'propagate': return ``nan``
40
+ * 'raise': raise an exception
41
+ * 'omit': perform the calculation with ``nan`` values omitted
42
+
43
+ The default is 'propagate'.
44
+ ddof : int, optional
45
+ Gives the "Delta Degrees Of Freedom" used when computing the
46
+ standard deviation. The divisor used in the calculation of the
47
+ standard deviation is ``N - ddof``, where ``N`` is the number of
48
+ elements. `ddof` must be less than ``N``; if it isn't, the result
49
+ will be ``nan`` or ``inf``, depending on ``N`` and the values in
50
+ the array. By default `ddof` is zero for backwards compatibility,
51
+ but it is recommended to use ``ddof=1`` to ensure that the sample
52
+ standard deviation is computed as the square root of the unbiased
53
+ sample variance.
54
+
55
+ Returns
56
+ -------
57
+ variation : ndarray
58
+ The calculated variation along the requested axis.
59
+
60
+ Notes
61
+ -----
62
+ There are several edge cases that are handled without generating a
63
+ warning:
64
+
65
+ * If both the mean and the standard deviation are zero, ``nan``
66
+ is returned.
67
+ * If the mean is zero and the standard deviation is nonzero, ``inf``
68
+ is returned.
69
+ * If the input has length zero (either because the array has zero
70
+ length, or all the input values are ``nan`` and ``nan_policy`` is
71
+ ``'omit'``), ``nan`` is returned.
72
+ * If the input contains ``inf``, ``nan`` is returned.
73
+
74
+ References
75
+ ----------
76
+ .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
77
+ Probability and Statistics Tables and Formulae. Chapman & Hall: New
78
+ York. 2000.
79
+
80
+ Examples
81
+ --------
82
+ >>> import numpy as np
83
+ >>> from scipy.stats import variation
84
+ >>> variation([1, 2, 3, 4, 5], ddof=1)
85
+ 0.5270462766947299
86
+
87
+ Compute the variation along a given dimension of an array that contains
88
+ a few ``nan`` values:
89
+
90
+ >>> x = np.array([[ 10.0, np.nan, 11.0, 19.0, 23.0, 29.0, 98.0],
91
+ ... [ 29.0, 30.0, 32.0, 33.0, 35.0, 56.0, 57.0],
92
+ ... [np.nan, np.nan, 12.0, 13.0, 16.0, 16.0, 17.0]])
93
+ >>> variation(x, axis=1, ddof=1, nan_policy='omit')
94
+ array([1.05109361, 0.31428986, 0.146483 ])
95
+
96
+ """
97
+ xp = array_namespace(a)
98
+ a = xp.asarray(a)
99
+ # `nan_policy` and `keepdims` are handled by `_axis_nan_policy`
100
+ # `axis=None` is only handled for NumPy backend
101
+ if axis is None:
102
+ a = xp.reshape(a, (-1,))
103
+ axis = 0
104
+
105
+ n = a.shape[axis]
106
+ NaN = _get_nan(a)
107
+
108
+ if a.size == 0 or ddof > n:
109
+ # Handle as a special case to avoid spurious warnings.
110
+ # The return values, if any, are all nan.
111
+ shp = list(a.shape)
112
+ shp.pop(axis)
113
+ result = xp.full(shp, fill_value=NaN)
114
+ return result[()] if result.ndim == 0 else result
115
+
116
+ mean_a = xp.mean(a, axis=axis)
117
+
118
+ if ddof == n:
119
+ # Another special case. Result is either inf or nan.
120
+ std_a = xp.std(a, axis=axis, correction=0)
121
+ result = xp.where(std_a > 0, xp_copysign(xp.asarray(xp.inf), mean_a), NaN)
122
+ return result[()] if result.ndim == 0 else result
123
+
124
+ with np.errstate(divide='ignore', invalid='ignore'):
125
+ std_a = xp.std(a, axis=axis, correction=ddof)
126
+ result = std_a / mean_a
127
+
128
+ return result[()] if result.ndim == 0 else result
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_warnings_errors.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Warnings
2
+
3
+
4
+ class DegenerateDataWarning(RuntimeWarning):
5
+ """Warns when data is degenerate and results may not be reliable."""
6
+ def __init__(self, msg=None):
7
+ if msg is None:
8
+ msg = ("Degenerate data encountered; results may not be reliable.")
9
+ self.args = (msg,)
10
+
11
+
12
+ class ConstantInputWarning(DegenerateDataWarning):
13
+ """Warns when all values in data are exactly equal."""
14
+ def __init__(self, msg=None):
15
+ if msg is None:
16
+ msg = ("All values in data are exactly equal; "
17
+ "results may not be reliable.")
18
+ self.args = (msg,)
19
+
20
+
21
+ class NearConstantInputWarning(DegenerateDataWarning):
22
+ """Warns when all values in data are nearly equal."""
23
+ def __init__(self, msg=None):
24
+ if msg is None:
25
+ msg = ("All values in data are nearly equal; "
26
+ "results may not be reliable.")
27
+ self.args = (msg,)
28
+
29
+
30
+ # Errors
31
+
32
+
33
+ class FitError(RuntimeError):
34
+ """Represents an error condition when fitting a distribution to data."""
35
+ def __init__(self, msg=None):
36
+ if msg is None:
37
+ msg = ("An error occurred when fitting a distribution to data.")
38
+ self.args = (msg,)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_wilcoxon.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from scipy import stats
4
+ from ._stats_py import _get_pvalue, _rankdata, _SimpleNormal
5
+ from . import _morestats
6
+ from ._axis_nan_policy import _broadcast_arrays
7
+ from ._hypotests import _get_wilcoxon_distr
8
+ from scipy._lib._util import _lazywhere, _get_nan
9
+
10
+
11
+ class WilcoxonDistribution:
12
+
13
+ def __init__(self, n):
14
+ n = np.asarray(n).astype(int, copy=False)
15
+ self.n = n
16
+ self._dists = {ni: _get_wilcoxon_distr(ni) for ni in np.unique(n)}
17
+
18
+ def _cdf1(self, k, n):
19
+ pmfs = self._dists[n]
20
+ return pmfs[:k + 1].sum()
21
+
22
+ def _cdf(self, k, n):
23
+ return np.vectorize(self._cdf1, otypes=[float])(k, n)
24
+
25
+ def _sf1(self, k, n):
26
+ pmfs = self._dists[n]
27
+ return pmfs[k:].sum()
28
+
29
+ def _sf(self, k, n):
30
+ return np.vectorize(self._sf1, otypes=[float])(k, n)
31
+
32
+ def mean(self):
33
+ return self.n * (self.n + 1) / 4
34
+
35
+ def _prep(self, k):
36
+ k = np.asarray(k).astype(int, copy=False)
37
+ mn = self.mean()
38
+ out = np.empty(k.shape, dtype=np.float64)
39
+ return k, mn, out
40
+
41
+ def cdf(self, k):
42
+ k, mn, out = self._prep(k)
43
+ return _lazywhere(k <= mn, (k, self.n), self._cdf,
44
+ f2=lambda k, n: 1 - self._sf(k+1, n))[()]
45
+
46
+ def sf(self, k):
47
+ k, mn, out = self._prep(k)
48
+ return _lazywhere(k <= mn, (k, self.n), self._sf,
49
+ f2=lambda k, n: 1 - self._cdf(k-1, n))[()]
50
+
51
+
52
+ def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis):
53
+
54
+ axis = np.asarray(axis)[()]
55
+ message = "`axis` must be an integer."
56
+ if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
57
+ raise ValueError(message)
58
+
59
+ message = '`axis` must be compatible with the shape(s) of `x` (and `y`)'
60
+ try:
61
+ if y is None:
62
+ x = np.asarray(x)
63
+ d = x
64
+ else:
65
+ x, y = _broadcast_arrays((x, y), axis=axis)
66
+ d = x - y
67
+ d = np.moveaxis(d, axis, -1)
68
+ except np.AxisError as e:
69
+ raise ValueError(message) from e
70
+
71
+ message = "`x` and `y` must have the same length along `axis`."
72
+ if y is not None and x.shape[axis] != y.shape[axis]:
73
+ raise ValueError(message)
74
+
75
+ message = "`x` (and `y`, if provided) must be an array of real numbers."
76
+ if np.issubdtype(d.dtype, np.integer):
77
+ d = d.astype(np.float64)
78
+ if not np.issubdtype(d.dtype, np.floating):
79
+ raise ValueError(message)
80
+
81
+ zero_method = str(zero_method).lower()
82
+ zero_methods = {"wilcox", "pratt", "zsplit"}
83
+ message = f"`zero_method` must be one of {zero_methods}."
84
+ if zero_method not in zero_methods:
85
+ raise ValueError(message)
86
+
87
+ corrections = {True, False}
88
+ message = f"`correction` must be one of {corrections}."
89
+ if correction not in corrections:
90
+ raise ValueError(message)
91
+
92
+ alternative = str(alternative).lower()
93
+ alternatives = {"two-sided", "less", "greater"}
94
+ message = f"`alternative` must be one of {alternatives}."
95
+ if alternative not in alternatives:
96
+ raise ValueError(message)
97
+
98
+ if not isinstance(method, stats.PermutationMethod):
99
+ methods = {"auto", "asymptotic", "exact"}
100
+ message = (f"`method` must be one of {methods} or "
101
+ "an instance of `stats.PermutationMethod`.")
102
+ if method not in methods:
103
+ raise ValueError(message)
104
+ output_z = True if method == 'asymptotic' else False
105
+
106
+ # For small samples, we decide later whether to perform an exact test or a
107
+ # permutation test. The reason is that the presence of ties is not
108
+ # known at the input validation stage.
109
+ n_zero = np.sum(d == 0)
110
+ if method == "auto" and d.shape[-1] > 50:
111
+ method = "asymptotic"
112
+
113
+ return d, zero_method, correction, alternative, method, axis, output_z, n_zero
114
+
115
+
116
+ def _wilcoxon_statistic(d, method, zero_method='wilcox'):
117
+
118
+ i_zeros = (d == 0)
119
+
120
+ if zero_method == 'wilcox':
121
+ # Wilcoxon's method for treating zeros was to remove them from
122
+ # the calculation. We do this by replacing 0s with NaNs, which
123
+ # are ignored anyway.
124
+ if not d.flags['WRITEABLE']:
125
+ d = d.copy()
126
+ d[i_zeros] = np.nan
127
+
128
+ i_nan = np.isnan(d)
129
+ n_nan = np.sum(i_nan, axis=-1)
130
+ count = d.shape[-1] - n_nan
131
+
132
+ r, t = _rankdata(abs(d), 'average', return_ties=True)
133
+
134
+ r_plus = np.sum((d > 0) * r, axis=-1)
135
+ r_minus = np.sum((d < 0) * r, axis=-1)
136
+
137
+ has_ties = (t == 0).any()
138
+
139
+ if zero_method == "zsplit":
140
+ # The "zero-split" method for treating zeros is to add half their contribution
141
+ # to r_plus and half to r_minus.
142
+ # See gh-2263 for the origin of this method.
143
+ r_zero_2 = np.sum(i_zeros * r, axis=-1) / 2
144
+ r_plus += r_zero_2
145
+ r_minus += r_zero_2
146
+
147
+ mn = count * (count + 1.) * 0.25
148
+ se = count * (count + 1.) * (2. * count + 1.)
149
+
150
+ if zero_method == "pratt":
151
+ # Pratt's method for treating zeros was just to modify the z-statistic.
152
+
153
+ # normal approximation needs to be adjusted, see Cureton (1967)
154
+ n_zero = i_zeros.sum(axis=-1)
155
+ mn -= n_zero * (n_zero + 1.) * 0.25
156
+ se -= n_zero * (n_zero + 1.) * (2. * n_zero + 1.)
157
+
158
+ # zeros are not to be included in tie-correction.
159
+ # any tie counts corresponding with zeros are in the 0th column
160
+ t[i_zeros.any(axis=-1), 0] = 0
161
+
162
+ tie_correct = (t**3 - t).sum(axis=-1)
163
+ se -= tie_correct/2
164
+ se = np.sqrt(se / 24)
165
+
166
+ # se = 0 means that no non-zero values are left in d. we only need z
167
+ # if method is asymptotic. however, if method="auto", the switch to
168
+ # asymptotic might only happen after the statistic is calculated, so z
169
+ # needs to be computed. in all other cases, avoid division by zero warning
170
+ # (z is not needed anyways)
171
+ if method in ["asymptotic", "auto"]:
172
+ z = (r_plus - mn) / se
173
+ else:
174
+ z = np.nan
175
+
176
+ return r_plus, r_minus, se, z, count, has_ties
177
+
178
+
179
+ def _correction_sign(z, alternative):
180
+ if alternative == 'greater':
181
+ return 1
182
+ elif alternative == 'less':
183
+ return -1
184
+ else:
185
+ return np.sign(z)
186
+
187
+
188
+ def _wilcoxon_nd(x, y=None, zero_method='wilcox', correction=True,
189
+ alternative='two-sided', method='auto', axis=0):
190
+
191
+ temp = _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis)
192
+ d, zero_method, correction, alternative, method, axis, output_z, n_zero = temp
193
+
194
+ if d.size == 0:
195
+ NaN = _get_nan(d)
196
+ res = _morestats.WilcoxonResult(statistic=NaN, pvalue=NaN)
197
+ if method == 'asymptotic':
198
+ res.zstatistic = NaN
199
+ return res
200
+
201
+ r_plus, r_minus, se, z, count, has_ties = _wilcoxon_statistic(
202
+ d, method, zero_method
203
+ )
204
+
205
+ # we only know if there are ties after computing the statistic and not
206
+ # at the input validation stage. if the original method was auto and
207
+ # the decision was to use an exact test, we override this to
208
+ # a permutation test now (since method='exact' is not exact in the
209
+ # presence of ties)
210
+ if method == "auto":
211
+ if not (has_ties or n_zero > 0):
212
+ method = "exact"
213
+ elif d.shape[-1] <= 13:
214
+ # the possible outcomes to be simulated by the permutation test
215
+ # are 2**n, where n is the sample size.
216
+ # if n <= 13, the p-value is deterministic since 2**13 is less
217
+ # than 9999, the default number of n_resamples
218
+ method = stats.PermutationMethod()
219
+ else:
220
+ # if there are ties and the sample size is too large to
221
+ # run a deterministic permutation test, fall back to asymptotic
222
+ method = "asymptotic"
223
+
224
+ if method == 'asymptotic':
225
+ if correction:
226
+ sign = _correction_sign(z, alternative)
227
+ z -= sign * 0.5 / se
228
+ p = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
229
+ elif method == 'exact':
230
+ dist = WilcoxonDistribution(count)
231
+ # The null distribution in `dist` is exact only if there are no ties
232
+ # or zeros. If there are ties or zeros, the statistic can be non-
233
+ # integral, but the null distribution is only defined for integral
234
+ # values of the statistic. Therefore, we're conservative: round
235
+ # non-integral statistic up before computing CDF and down before
236
+ # computing SF. This preserves symmetry w.r.t. alternatives and
237
+ # order of the input arguments. See gh-19872.
238
+ if alternative == 'less':
239
+ p = dist.cdf(np.ceil(r_plus))
240
+ elif alternative == 'greater':
241
+ p = dist.sf(np.floor(r_plus))
242
+ else:
243
+ p = 2 * np.minimum(dist.sf(np.floor(r_plus)),
244
+ dist.cdf(np.ceil(r_plus)))
245
+ p = np.clip(p, 0, 1)
246
+ else: # `PermutationMethod` instance (already validated)
247
+ p = stats.permutation_test(
248
+ (d,), lambda d: _wilcoxon_statistic(d, method, zero_method)[0],
249
+ permutation_type='samples', **method._asdict(),
250
+ alternative=alternative, axis=-1).pvalue
251
+
252
+ # for backward compatibility...
253
+ statistic = np.minimum(r_plus, r_minus) if alternative=='two-sided' else r_plus
254
+ z = -np.abs(z) if (alternative == 'two-sided' and method == 'asymptotic') else z
255
+
256
+ res = _morestats.WilcoxonResult(statistic=statistic, pvalue=p[()])
257
+ if output_z:
258
+ res.zstatistic = z[()]
259
+ return res
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/biasedurn.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+
3
+ from scipy._lib.deprecation import _sub_module_deprecation
4
+
5
+
6
+ __all__: list[str] = []
7
+
8
+
9
+ def __dir__():
10
+ return __all__
11
+
12
+
13
+ def __getattr__(name):
14
+ return _sub_module_deprecation(sub_package="stats", module="biasedurn",
15
+ private_modules=["_biasedurn"], all=__all__,
16
+ attribute=name)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/contingency.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contingency table functions (:mod:`scipy.stats.contingency`)
3
+ ============================================================
4
+
5
+ Functions for creating and analyzing contingency tables.
6
+
7
+ .. currentmodule:: scipy.stats.contingency
8
+
9
+ .. autosummary::
10
+ :toctree: generated/
11
+
12
+ chi2_contingency
13
+ relative_risk
14
+ odds_ratio
15
+ crosstab
16
+ association
17
+
18
+ expected_freq
19
+ margins
20
+
21
+ """
22
+
23
+
24
+ from functools import reduce
25
+ import math
26
+ import numpy as np
27
+ from ._stats_py import power_divergence, _untabulate
28
+ from ._relative_risk import relative_risk
29
+ from ._crosstab import crosstab
30
+ from ._odds_ratio import odds_ratio
31
+ from scipy._lib._bunch import _make_tuple_bunch
32
+ from scipy import stats
33
+
34
+
35
+ __all__ = ['margins', 'expected_freq', 'chi2_contingency', 'crosstab',
36
+ 'association', 'relative_risk', 'odds_ratio']
37
+
38
+
39
+ def margins(a):
40
+ """Return a list of the marginal sums of the array `a`.
41
+
42
+ Parameters
43
+ ----------
44
+ a : ndarray
45
+ The array for which to compute the marginal sums.
46
+
47
+ Returns
48
+ -------
49
+ margsums : list of ndarrays
50
+ A list of length `a.ndim`. `margsums[k]` is the result
51
+ of summing `a` over all axes except `k`; it has the same
52
+ number of dimensions as `a`, but the length of each axis
53
+ except axis `k` will be 1.
54
+
55
+ Examples
56
+ --------
57
+ >>> import numpy as np
58
+ >>> from scipy.stats.contingency import margins
59
+
60
+ >>> a = np.arange(12).reshape(2, 6)
61
+ >>> a
62
+ array([[ 0, 1, 2, 3, 4, 5],
63
+ [ 6, 7, 8, 9, 10, 11]])
64
+ >>> m0, m1 = margins(a)
65
+ >>> m0
66
+ array([[15],
67
+ [51]])
68
+ >>> m1
69
+ array([[ 6, 8, 10, 12, 14, 16]])
70
+
71
+ >>> b = np.arange(24).reshape(2,3,4)
72
+ >>> m0, m1, m2 = margins(b)
73
+ >>> m0
74
+ array([[[ 66]],
75
+ [[210]]])
76
+ >>> m1
77
+ array([[[ 60],
78
+ [ 92],
79
+ [124]]])
80
+ >>> m2
81
+ array([[[60, 66, 72, 78]]])
82
+ """
83
+ margsums = []
84
+ ranged = list(range(a.ndim))
85
+ for k in ranged:
86
+ marg = np.apply_over_axes(np.sum, a, [j for j in ranged if j != k])
87
+ margsums.append(marg)
88
+ return margsums
89
+
90
+
91
+ def expected_freq(observed):
92
+ """
93
+ Compute the expected frequencies from a contingency table.
94
+
95
+ Given an n-dimensional contingency table of observed frequencies,
96
+ compute the expected frequencies for the table based on the marginal
97
+ sums under the assumption that the groups associated with each
98
+ dimension are independent.
99
+
100
+ Parameters
101
+ ----------
102
+ observed : array_like
103
+ The table of observed frequencies. (While this function can handle
104
+ a 1-D array, that case is trivial. Generally `observed` is at
105
+ least 2-D.)
106
+
107
+ Returns
108
+ -------
109
+ expected : ndarray of float64
110
+ The expected frequencies, based on the marginal sums of the table.
111
+ Same shape as `observed`.
112
+
113
+ Examples
114
+ --------
115
+ >>> import numpy as np
116
+ >>> from scipy.stats.contingency import expected_freq
117
+ >>> observed = np.array([[10, 10, 20],[20, 20, 20]])
118
+ >>> expected_freq(observed)
119
+ array([[ 12., 12., 16.],
120
+ [ 18., 18., 24.]])
121
+
122
+ """
123
+ # Typically `observed` is an integer array. If `observed` has a large
124
+ # number of dimensions or holds large values, some of the following
125
+ # computations may overflow, so we first switch to floating point.
126
+ observed = np.asarray(observed, dtype=np.float64)
127
+
128
+ # Create a list of the marginal sums.
129
+ margsums = margins(observed)
130
+
131
+ # Create the array of expected frequencies. The shapes of the
132
+ # marginal sums returned by apply_over_axes() are just what we
133
+ # need for broadcasting in the following product.
134
+ d = observed.ndim
135
+ expected = reduce(np.multiply, margsums) / observed.sum() ** (d - 1)
136
+ return expected
137
+
138
+
139
+ Chi2ContingencyResult = _make_tuple_bunch(
140
+ 'Chi2ContingencyResult',
141
+ ['statistic', 'pvalue', 'dof', 'expected_freq'], []
142
+ )
143
+
144
+
145
+ def chi2_contingency(observed, correction=True, lambda_=None, *, method=None):
146
+ """Chi-square test of independence of variables in a contingency table.
147
+
148
+ This function computes the chi-square statistic and p-value for the
149
+ hypothesis test of independence of the observed frequencies in the
150
+ contingency table [1]_ `observed`. The expected frequencies are computed
151
+ based on the marginal sums under the assumption of independence; see
152
+ `scipy.stats.contingency.expected_freq`. The number of degrees of
153
+ freedom is (expressed using numpy functions and attributes)::
154
+
155
+ dof = observed.size - sum(observed.shape) + observed.ndim - 1
156
+
157
+
158
+ Parameters
159
+ ----------
160
+ observed : array_like
161
+ The contingency table. The table contains the observed frequencies
162
+ (i.e. number of occurrences) in each category. In the two-dimensional
163
+ case, the table is often described as an "R x C table".
164
+ correction : bool, optional
165
+ If True, *and* the degrees of freedom is 1, apply Yates' correction
166
+ for continuity. The effect of the correction is to adjust each
167
+ observed value by 0.5 towards the corresponding expected value.
168
+ lambda_ : float or str, optional
169
+ By default, the statistic computed in this test is Pearson's
170
+ chi-squared statistic [2]_. `lambda_` allows a statistic from the
171
+ Cressie-Read power divergence family [3]_ to be used instead. See
172
+ `scipy.stats.power_divergence` for details.
173
+ method : ResamplingMethod, optional
174
+ Defines the method used to compute the p-value. Compatible only with
175
+ `correction=False`, default `lambda_`, and two-way tables.
176
+ If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
177
+ the p-value is computed using
178
+ `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
179
+ provided configuration options and other appropriate settings.
180
+ Otherwise, the p-value is computed as documented in the notes.
181
+ Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
182
+ attribute must be left unspecified; Monte Carlo samples are always drawn
183
+ using the ``rvs`` method of `scipy.stats.random_table`.
184
+
185
+ .. versionadded:: 1.15.0
186
+
187
+
188
+ Returns
189
+ -------
190
+ res : Chi2ContingencyResult
191
+ An object containing attributes:
192
+
193
+ statistic : float
194
+ The test statistic.
195
+ pvalue : float
196
+ The p-value of the test.
197
+ dof : int
198
+ The degrees of freedom. NaN if `method` is not ``None``.
199
+ expected_freq : ndarray, same shape as `observed`
200
+ The expected frequencies, based on the marginal sums of the table.
201
+
202
+ See Also
203
+ --------
204
+ scipy.stats.contingency.expected_freq
205
+ scipy.stats.fisher_exact
206
+ scipy.stats.chisquare
207
+ scipy.stats.power_divergence
208
+ scipy.stats.barnard_exact
209
+ scipy.stats.boschloo_exact
210
+ :ref:`hypothesis_chi2_contingency` : Extended example
211
+
212
+ Notes
213
+ -----
214
+ An often quoted guideline for the validity of this calculation is that
215
+ the test should be used only if the observed and expected frequencies
216
+ in each cell are at least 5.
217
+
218
+ This is a test for the independence of different categories of a
219
+ population. The test is only meaningful when the dimension of
220
+ `observed` is two or more. Applying the test to a one-dimensional
221
+ table will always result in `expected` equal to `observed` and a
222
+ chi-square statistic equal to 0.
223
+
224
+ This function does not handle masked arrays, because the calculation
225
+ does not make sense with missing values.
226
+
227
+ Like `scipy.stats.chisquare`, this function computes a chi-square
228
+ statistic; the convenience this function provides is to figure out the
229
+ expected frequencies and degrees of freedom from the given contingency
230
+ table. If these were already known, and if the Yates' correction was not
231
+ required, one could use `scipy.stats.chisquare`. That is, if one calls::
232
+
233
+ res = chi2_contingency(obs, correction=False)
234
+
235
+ then the following is true::
236
+
237
+ (res.statistic, res.pvalue) == stats.chisquare(obs.ravel(),
238
+ f_exp=ex.ravel(),
239
+ ddof=obs.size - 1 - dof)
240
+
241
+ The `lambda_` argument was added in version 0.13.0 of scipy.
242
+
243
+ References
244
+ ----------
245
+ .. [1] "Contingency table",
246
+ https://en.wikipedia.org/wiki/Contingency_table
247
+ .. [2] "Pearson's chi-squared test",
248
+ https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
249
+ .. [3] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
250
+ Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
251
+ pp. 440-464.
252
+
253
+ Examples
254
+ --------
255
+ A two-way example (2 x 3):
256
+
257
+ >>> import numpy as np
258
+ >>> from scipy.stats import chi2_contingency
259
+ >>> obs = np.array([[10, 10, 20], [20, 20, 20]])
260
+ >>> res = chi2_contingency(obs)
261
+ >>> res.statistic
262
+ 2.7777777777777777
263
+ >>> res.pvalue
264
+ 0.24935220877729619
265
+ >>> res.dof
266
+ 2
267
+ >>> res.expected_freq
268
+ array([[ 12., 12., 16.],
269
+ [ 18., 18., 24.]])
270
+
271
+ Perform the test using the log-likelihood ratio (i.e. the "G-test")
272
+ instead of Pearson's chi-squared statistic.
273
+
274
+ >>> res = chi2_contingency(obs, lambda_="log-likelihood")
275
+ >>> res.statistic
276
+ 2.7688587616781319
277
+ >>> res.pvalue
278
+ 0.25046668010954165
279
+
280
+ A four-way example (2 x 2 x 2 x 2):
281
+
282
+ >>> obs = np.array(
283
+ ... [[[[12, 17],
284
+ ... [11, 16]],
285
+ ... [[11, 12],
286
+ ... [15, 16]]],
287
+ ... [[[23, 15],
288
+ ... [30, 22]],
289
+ ... [[14, 17],
290
+ ... [15, 16]]]])
291
+ >>> res = chi2_contingency(obs)
292
+ >>> res.statistic
293
+ 8.7584514426741897
294
+ >>> res.pvalue
295
+ 0.64417725029295503
296
+
297
+ When the sum of the elements in a two-way table is small, the p-value
298
+ produced by the default asymptotic approximation may be inaccurate.
299
+ Consider passing a `PermutationMethod` or `MonteCarloMethod` as the
300
+ `method` parameter with `correction=False`.
301
+
302
+ >>> from scipy.stats import PermutationMethod
303
+ >>> obs = np.asarray([[12, 3],
304
+ ... [17, 16]])
305
+ >>> res = chi2_contingency(obs, correction=False)
306
+ >>> ref = chi2_contingency(obs, correction=False, method=PermutationMethod())
307
+ >>> res.pvalue, ref.pvalue
308
+ (0.0614122539870913, 0.1074) # may vary
309
+
310
+ For a more detailed example, see :ref:`hypothesis_chi2_contingency`.
311
+
312
+ """
313
+ observed = np.asarray(observed)
314
+ if np.any(observed < 0):
315
+ raise ValueError("All values in `observed` must be nonnegative.")
316
+ if observed.size == 0:
317
+ raise ValueError("No data; `observed` has size 0.")
318
+
319
+ expected = expected_freq(observed)
320
+ if np.any(expected == 0):
321
+ # Include one of the positions where expected is zero in
322
+ # the exception message.
323
+ zeropos = list(zip(*np.nonzero(expected == 0)))[0]
324
+ raise ValueError("The internally computed table of expected "
325
+ f"frequencies has a zero element at {zeropos}.")
326
+
327
+ if method is not None:
328
+ return _chi2_resampling_methods(observed, expected, correction, lambda_, method)
329
+
330
+ # The degrees of freedom
331
+ dof = expected.size - sum(expected.shape) + expected.ndim - 1
332
+
333
+ if dof == 0:
334
+ # Degenerate case; this occurs when `observed` is 1D (or, more
335
+ # generally, when it has only one nontrivial dimension). In this
336
+ # case, we also have observed == expected, so chi2 is 0.
337
+ chi2 = 0.0
338
+ p = 1.0
339
+ else:
340
+ if dof == 1 and correction:
341
+ # Adjust `observed` according to Yates' correction for continuity.
342
+ # Magnitude of correction no bigger than difference; see gh-13875
343
+ diff = expected - observed
344
+ direction = np.sign(diff)
345
+ magnitude = np.minimum(0.5, np.abs(diff))
346
+ observed = observed + magnitude * direction
347
+
348
+ chi2, p = power_divergence(observed, expected,
349
+ ddof=observed.size - 1 - dof, axis=None,
350
+ lambda_=lambda_)
351
+
352
+ return Chi2ContingencyResult(chi2, p, dof, expected)
353
+
354
+
355
+ def _chi2_resampling_methods(observed, expected, correction, lambda_, method):
356
+
357
+ if observed.ndim != 2:
358
+ message = 'Use of `method` is only compatible with two-way tables.'
359
+ raise ValueError(message)
360
+
361
+ if correction:
362
+ message = f'`{correction=}` is not compatible with `{method=}.`'
363
+ raise ValueError(message)
364
+
365
+ if lambda_ is not None:
366
+ message = f'`{lambda_=}` is not compatible with `{method=}.`'
367
+ raise ValueError(message)
368
+
369
+ if isinstance(method, stats.PermutationMethod):
370
+ res = _chi2_permutation_method(observed, expected, method)
371
+ elif isinstance(method, stats.MonteCarloMethod):
372
+ res = _chi2_monte_carlo_method(observed, expected, method)
373
+ else:
374
+ message = (f'`{method=}` not recognized; if provided, `method` must be an '
375
+ 'instance of `PermutationMethod` or `MonteCarloMethod`.')
376
+ raise ValueError(message)
377
+
378
+ return Chi2ContingencyResult(res.statistic, res.pvalue, np.nan, expected)
379
+
380
+
381
+ def _chi2_permutation_method(observed, expected, method):
382
+ x, y = _untabulate(observed)
383
+ # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
384
+ # which pairs observations in `x` with different observations in `y`.
385
+ def statistic(x):
386
+ # crosstab the resample and compute the statistic
387
+ table = crosstab(x, y)[1]
388
+ return np.sum((table - expected)**2/expected)
389
+
390
+ return stats.permutation_test((x,), statistic, permutation_type='pairings',
391
+ alternative='greater', **method._asdict())
392
+
393
+
394
+ def _chi2_monte_carlo_method(observed, expected, method):
395
+ method = method._asdict()
396
+
397
+ if method.pop('rvs', None) is not None:
398
+ message = ('If the `method` argument of `chi2_contingency` is an '
399
+ 'instance of `MonteCarloMethod`, its `rvs` attribute '
400
+ 'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
401
+ 'to control the random state.')
402
+ raise ValueError(message)
403
+ rng = np.random.default_rng(method.pop('rng', None))
404
+
405
+ # `random_table.rvs` produces random contingency tables with the given marginals
406
+ # under the null hypothesis of independence
407
+ rowsums, colsums = stats.contingency.margins(observed)
408
+ X = stats.random_table(rowsums.ravel(), colsums.ravel(), seed=rng)
409
+ def rvs(size):
410
+ n_resamples = size[0]
411
+ return X.rvs(size=n_resamples).reshape(size)
412
+
413
+ expected = expected.ravel()
414
+ def statistic(table, axis):
415
+ return np.sum((table - expected)**2/expected, axis=axis)
416
+
417
+ return stats.monte_carlo_test(observed.ravel(), rvs, statistic,
418
+ alternative='greater', **method)
419
+
420
+
421
+ def association(observed, method="cramer", correction=False, lambda_=None):
422
+ """Calculates degree of association between two nominal variables.
423
+
424
+ The function provides the option for computing one of three measures of
425
+ association between two nominal variables from the data given in a 2d
426
+ contingency table: Tschuprow's T, Pearson's Contingency Coefficient
427
+ and Cramer's V.
428
+
429
+ Parameters
430
+ ----------
431
+ observed : array-like
432
+ The array of observed values
433
+ method : {"cramer", "tschuprow", "pearson"} (default = "cramer")
434
+ The association test statistic.
435
+ correction : bool, optional
436
+ Inherited from `scipy.stats.contingency.chi2_contingency()`
437
+ lambda_ : float or str, optional
438
+ Inherited from `scipy.stats.contingency.chi2_contingency()`
439
+
440
+ Returns
441
+ -------
442
+ statistic : float
443
+ Value of the test statistic
444
+
445
+ Notes
446
+ -----
447
+ Cramer's V, Tschuprow's T and Pearson's Contingency Coefficient, all
448
+ measure the degree to which two nominal or ordinal variables are related,
449
+ or the level of their association. This differs from correlation, although
450
+ many often mistakenly consider them equivalent. Correlation measures in
451
+ what way two variables are related, whereas, association measures how
452
+ related the variables are. As such, association does not subsume
453
+ independent variables, and is rather a test of independence. A value of
454
+ 1.0 indicates perfect association, and 0.0 means the variables have no
455
+ association.
456
+
457
+ Both the Cramer's V and Tschuprow's T are extensions of the phi
458
+ coefficient. Moreover, due to the close relationship between the
459
+ Cramer's V and Tschuprow's T the returned values can often be similar
460
+ or even equivalent. They are likely to diverge more as the array shape
461
+ diverges from a 2x2.
462
+
463
+ References
464
+ ----------
465
+ .. [1] "Tschuprow's T",
466
+ https://en.wikipedia.org/wiki/Tschuprow's_T
467
+ .. [2] Tschuprow, A. A. (1939)
468
+ Principles of the Mathematical Theory of Correlation;
469
+ translated by M. Kantorowitsch. W. Hodge & Co.
470
+ .. [3] "Cramer's V", https://en.wikipedia.org/wiki/Cramer's_V
471
+ .. [4] "Nominal Association: Phi and Cramer's V",
472
+ http://www.people.vcu.edu/~pdattalo/702SuppRead/MeasAssoc/NominalAssoc.html
473
+ .. [5] Gingrich, Paul, "Association Between Variables",
474
+ http://uregina.ca/~gingrich/ch11a.pdf
475
+
476
+ Examples
477
+ --------
478
+ An example with a 4x2 contingency table:
479
+
480
+ >>> import numpy as np
481
+ >>> from scipy.stats.contingency import association
482
+ >>> obs4x2 = np.array([[100, 150], [203, 322], [420, 700], [320, 210]])
483
+
484
+ Pearson's contingency coefficient
485
+
486
+ >>> association(obs4x2, method="pearson")
487
+ 0.18303298140595667
488
+
489
+ Cramer's V
490
+
491
+ >>> association(obs4x2, method="cramer")
492
+ 0.18617813077483678
493
+
494
+ Tschuprow's T
495
+
496
+ >>> association(obs4x2, method="tschuprow")
497
+ 0.14146478765062995
498
+ """
499
+ arr = np.asarray(observed)
500
+ if not np.issubdtype(arr.dtype, np.integer):
501
+ raise ValueError("`observed` must be an integer array.")
502
+
503
+ if len(arr.shape) != 2:
504
+ raise ValueError("method only accepts 2d arrays")
505
+
506
+ chi2_stat = chi2_contingency(arr, correction=correction,
507
+ lambda_=lambda_)
508
+
509
+ phi2 = chi2_stat.statistic / arr.sum()
510
+ n_rows, n_cols = arr.shape
511
+ if method == "cramer":
512
+ value = phi2 / min(n_cols - 1, n_rows - 1)
513
+ elif method == "tschuprow":
514
+ value = phi2 / math.sqrt((n_rows - 1) * (n_cols - 1))
515
+ elif method == 'pearson':
516
+ value = phi2 / (1 + phi2)
517
+ else:
518
+ raise ValueError("Invalid argument value: 'method' argument must "
519
+ "be 'cramer', 'tschuprow', or 'pearson'")
520
+
521
+ return math.sqrt(value)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/distributions.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Author: Travis Oliphant 2002-2011 with contributions from
3
+ # SciPy Developers 2004-2011
4
+ #
5
+ # NOTE: To look at history using `git blame`, use `git blame -M -C -C`
6
+ # instead of `git blame -Lxxx,+x`.
7
+ #
8
+ from ._distn_infrastructure import (rv_discrete, rv_continuous, rv_frozen) # noqa: F401
9
+
10
+ from . import _continuous_distns
11
+ from . import _discrete_distns
12
+
13
+ from ._continuous_distns import * # noqa: F403
14
+ from ._levy_stable import levy_stable
15
+ from ._discrete_distns import * # noqa: F403
16
+ from ._entropy import entropy
17
+
18
+ # For backwards compatibility e.g. pymc expects distributions.__all__.
19
+ __all__ = ['rv_discrete', 'rv_continuous', 'rv_histogram', 'entropy'] # noqa: F405
20
+
21
+ # Add only the distribution names, not the *_gen names.
22
+ __all__ += _continuous_distns._distn_names
23
+ __all__ += ['levy_stable']
24
+ __all__ += _discrete_distns._distn_names
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/kde.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.stats` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = ["gaussian_kde"] # noqa: F822
9
+
10
+
11
+ def __dir__():
12
+ return __all__
13
+
14
+
15
+ def __getattr__(name):
16
+ return _sub_module_deprecation(sub_package="stats", module="kde",
17
+ private_modules=["_kde"], all=__all__,
18
+ attribute=name)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/morestats.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.stats` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'mvsdist',
10
+ 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
11
+ 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
12
+ 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
13
+ 'fligner', 'mood', 'wilcoxon', 'median_test',
14
+ 'circmean', 'circvar', 'circstd', 'anderson_ksamp',
15
+ 'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
16
+ 'yeojohnson_normplot', 'find_repeats', 'chi2_contingency', 'distributions',
17
+ ]
18
+
19
+
20
+ def __dir__():
21
+ return __all__
22
+
23
+
24
+ def __getattr__(name):
25
+ return _sub_module_deprecation(sub_package="stats", module="morestats",
26
+ private_modules=["_morestats"], all=__all__,
27
+ attribute=name)