robustbase 0.2.9__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. robustbase-3.1.0/MANIFEST.in +2 -0
  2. robustbase-3.1.0/PKG-INFO +152 -0
  3. robustbase-3.1.0/README.md +119 -0
  4. robustbase-3.1.0/requirements.txt +4 -0
  5. robustbase-3.1.0/robustbase/__init__.py +0 -0
  6. robustbase-3.1.0/robustbase/stats/Qn.py +69 -0
  7. robustbase-3.1.0/robustbase/stats/Sn.py +40 -0
  8. robustbase-3.1.0/robustbase/stats/__init__.py +5 -0
  9. robustbase-3.1.0/robustbase/stats/covComed.py +76 -0
  10. robustbase-3.1.0/robustbase/stats/iqr.py +14 -0
  11. robustbase-3.1.0/robustbase/stats/mad.py +29 -0
  12. robustbase-3.1.0/robustbase/utils/__init__.py +2 -0
  13. robustbase-3.1.0/robustbase/utils/mean.py +17 -0
  14. robustbase-3.1.0/robustbase/utils/median.py +35 -0
  15. robustbase-3.1.0/robustbase/version.py +1 -0
  16. robustbase-3.1.0/robustbase.egg-info/PKG-INFO +152 -0
  17. robustbase-3.1.0/robustbase.egg-info/SOURCES.txt +28 -0
  18. robustbase-3.1.0/robustbase.egg-info/requires.txt +11 -0
  19. robustbase-3.1.0/setup.py +71 -0
  20. robustbase-3.1.0/tests/test_Qn.py +15 -0
  21. robustbase-3.1.0/tests/test_Sn.py +15 -0
  22. robustbase-3.1.0/tests/test_covcomed.py +66 -0
  23. robustbase-3.1.0/tests/test_import.py +25 -0
  24. robustbase-3.1.0/tests/test_iqr.py +12 -0
  25. robustbase-3.1.0/tests/test_mad.py +15 -0
  26. robustbase-3.1.0/tests/test_median.py +47 -0
  27. robustbase-0.2.9/PKG-INFO +0 -131
  28. robustbase-0.2.9/README.md +0 -115
  29. robustbase-0.2.9/setup.py +0 -62
  30. robustbase-0.2.9/src/robustbase.egg-info/PKG-INFO +0 -131
  31. robustbase-0.2.9/src/robustbase.egg-info/SOURCES.txt +0 -8
  32. robustbase-0.2.9/src/robustbase.py +0 -156
  33. {robustbase-0.2.9 → robustbase-3.1.0}/LICENSE +0 -0
  34. {robustbase-0.2.9/src → robustbase-3.1.0}/robustbase.egg-info/dependency_links.txt +0 -0
  35. {robustbase-0.2.9/src → robustbase-3.1.0}/robustbase.egg-info/top_level.txt +0 -0
  36. {robustbase-0.2.9 → robustbase-3.1.0}/setup.cfg +0 -0
@@ -0,0 +1,2 @@
1
+ include README.md
2
+ include requirements.txt
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.1
2
+ Name: robustbase
3
+ Version: 3.1.0
4
+ Summary: A Python Based Library to Calculate Estimators (Sn, Qn, MAD, IQR, covComed)
5
+ Home-page: https://github.com/deepak7376/robustbase
6
+ Author: Deepak Yadav
7
+ Author-email: dky.united@gmail.com
8
+ License: MIT
9
+ Project-URL: Source, https://github.com/deepak7376/robustbase
10
+ Project-URL: Tracker, https://github.com/deepak7376/robustbase/issues
11
+ Keywords: robust statistics robustness Sn Qn MAD IQR
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.6
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Requires-Python: >=3.0
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: certifi>=2019.11.28
24
+ Requires-Dist: docutils>=0.15.2
25
+ Requires-Dist: numpy>=1.18.0
26
+ Requires-Dist: scipy>=1.13.1
27
+ Requires-Dist: statistics>=1.0.3.5
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=6.0.0; extra == "dev"
30
+ Requires-Dist: pytest-cov>=2.10.0; extra == "dev"
31
+ Requires-Dist: coverage>=5.0; extra == "dev"
32
+ Requires-Dist: flake8>=3.8.0; extra == "dev"
33
+
34
+ [![Downloads](https://pepy.tech/badge/robustbase)](https://pepy.tech/project/robustbase)
35
+ [![Downloads](https://pepy.tech/badge/robustbase/month)](https://pepy.tech/project/robustbase/month)
36
+ [![Downloads](https://pepy.tech/badge/robustbase/week)](https://pepy.tech/project/robustbase/week)
37
+
38
+ # robustbase
39
+ > A Python Library to Calculate Robust Statistical Estimators.
40
+
41
+ ## Installation
42
+
43
+ OS X, Windows & Linux:
44
+
45
+ ```sh
46
+ pip install robustbase
47
+ ```
48
+ ## Usage Example
49
+
50
+ This package provides functions to calculate the following robust statistical estimators:
51
+
52
+ * **Qn Scale Estimator**
53
+ * Computes the robust scale estimator Qn, an efficient alternative to the MAD. [Read More](https://rdrr.io/rforge/robustbase/man/Qn.html)
54
+
55
+ ```python
56
+ from robustbase.stats import Qn
57
+
58
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
59
+
60
+ # With bias correction
61
+ res = Qn(x) # result: 3.196183
62
+
63
+ # Without bias correction
64
+ res = Qn(x, finite_corr=False) # result: 4.43828
65
+
66
+ ```
67
+
68
+ * **Sn Scale Estimator**
69
+ * Computes the robust scale estimator Sn, an efficient alternative to the MAD. [Read More](https://rdrr.io/rforge/robustbase/man/Sn.html)
70
+
71
+ ```python
72
+ from robustbase.stats import Sn
73
+
74
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
75
+
76
+ # With bias correction
77
+ res = Sn(x) # result: 3.5778
78
+
79
+ # Without bias correction
80
+ res = Sn(x, finite_corr=False) # result: 3.5778
81
+
82
+ ```
83
+
84
+ * **Median Absolute Deviation (MAD)**
85
+ * Compute the MAD, a robust measure of the variability of a univariate sample of quantitative data. [Read More](https://en.wikipedia.org/wiki/Median_absolute_deviation)
86
+
87
+ ```python
88
+ from robustbase.stats import mad
89
+
90
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
91
+ res = mad(x)
92
+
93
+ ```
94
+ * **Interquartile Range (IQR)**
95
+ * Compute the interquartile range, a measure of statistical dispersion, or spread. [Read More](https://en.wikipedia.org/wiki/Interquartile_range)
96
+
97
+ ```python
98
+ from robustbase.stats import iqr
99
+
100
+ x = [1, 2, 3, 4, 5]
101
+ res = iqr(x)
102
+ ```
103
+
104
+ * **Co-Median Location and Scatter "Covariance" Estimator**
105
+ * Compute the multivariate "Comedian" covariance, a robust measure of multivariate location and scatter. Read More
106
+
107
+ ```python
108
+ from robustbase.stats import covComed
109
+
110
+ # Example data matrix
111
+ X = np.random.rand(100, 3)
112
+
113
+ # Compute the Co-Median covariance estimator
114
+ result = covComed(X)
115
+
116
+ # Access the components of the result
117
+ print("Covariance Matrix:", result.cov)
118
+ print("Center:", result.center)
119
+ print("Weights:", result.weights)
120
+ ```
121
+
122
+ ## Development Setup
123
+
124
+ For local development setup:
125
+
126
+ ```sh
127
+ git clone https://github.com/deepak7376/robustbase
128
+ cd robustbase
129
+ pip install -r requirements.txt -r requirements-dev.txt
130
+ ```
131
+
132
+ ## Recent Changes
133
+
134
+ ### Version 3.0.0
135
+ - Changed the API's call
136
+ - Refactored the dir structure
137
+ - Updated README with usage examples for all functions.
138
+
139
+
140
+ ## Contributing
141
+
142
+ 1. Fork it ([https://github.com/deepak7376/robustbase/fork](https://github.com/deepak7376/robustbase/fork))
143
+ 2. Create your feature branch (`git checkout -b feature/fooBar`)
144
+ 3. Commit your changes (`git commit -am 'Add some fooBar'`)
145
+ 4. Push to the branch (`git push origin feature/fooBar`)
146
+ 5. Create a new Pull Request
147
+
148
+ ## References
149
+ - [Qn Scale Estimator](https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/qn_scale.htm)
150
+ - [Sn Scale Estimator](https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/sn_scale.htm)
151
+ - [Median Absolute Deviation](https://www.statisticshowto.datasciencecentral.com/median-absolute-deviation/)
152
+ - [Interquartile Range](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/interquartile-range/)
@@ -0,0 +1,119 @@
1
+ [![Downloads](https://pepy.tech/badge/robustbase)](https://pepy.tech/project/robustbase)
2
+ [![Downloads](https://pepy.tech/badge/robustbase/month)](https://pepy.tech/project/robustbase/month)
3
+ [![Downloads](https://pepy.tech/badge/robustbase/week)](https://pepy.tech/project/robustbase/week)
4
+
5
+ # robustbase
6
+ > A Python Library to Calculate Robust Statistical Estimators.
7
+
8
+ ## Installation
9
+
10
+ OS X, Windows & Linux:
11
+
12
+ ```sh
13
+ pip install robustbase
14
+ ```
15
+ ## Usage Example
16
+
17
+ This package provides functions to calculate the following robust statistical estimators:
18
+
19
+ * **Qn Scale Estimator**
20
+ * Computes the robust scale estimator Qn, an efficient alternative to the MAD. [Read More](https://rdrr.io/rforge/robustbase/man/Qn.html)
21
+
22
+ ```python
23
+ from robustbase.stats import Qn
24
+
25
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
26
+
27
+ # With bias correction
28
+ res = Qn(x) # result: 3.196183
29
+
30
+ # Without bias correction
31
+ res = Qn(x, finite_corr=False) # result: 4.43828
32
+
33
+ ```
34
+
35
+ * **Sn Scale Estimator**
36
+ * Computes the robust scale estimator Sn, an efficient alternative to the MAD. [Read More](https://rdrr.io/rforge/robustbase/man/Sn.html)
37
+
38
+ ```python
39
+ from robustbase.stats import Sn
40
+
41
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
42
+
43
+ # With bias correction
44
+ res = Sn(x) # result: 3.5778
45
+
46
+ # Without bias correction
47
+ res = Sn(x, finite_corr=False) # result: 3.5778
48
+
49
+ ```
50
+
51
+ * **Median Absolute Deviation (MAD)**
52
+ * Compute the MAD, a robust measure of the variability of a univariate sample of quantitative data. [Read More](https://en.wikipedia.org/wiki/Median_absolute_deviation)
53
+
54
+ ```python
55
+ from robustbase.stats import mad
56
+
57
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
58
+ res = mad(x)
59
+
60
+ ```
61
+ * **Interquartile Range (IQR)**
62
+ * Compute the interquartile range, a measure of statistical dispersion, or spread. [Read More](https://en.wikipedia.org/wiki/Interquartile_range)
63
+
64
+ ```python
65
+ from robustbase.stats import iqr
66
+
67
+ x = [1, 2, 3, 4, 5]
68
+ res = iqr(x)
69
+ ```
70
+
71
+ * **Co-Median Location and Scatter "Covariance" Estimator**
72
+ * Compute the multivariate "Comedian" covariance, a robust measure of multivariate location and scatter. Read More
73
+
74
+ ```python
75
+ from robustbase.stats import covComed
76
+
77
+ # Example data matrix
78
+ X = np.random.rand(100, 3)
79
+
80
+ # Compute the Co-Median covariance estimator
81
+ result = covComed(X)
82
+
83
+ # Access the components of the result
84
+ print("Covariance Matrix:", result.cov)
85
+ print("Center:", result.center)
86
+ print("Weights:", result.weights)
87
+ ```
88
+
89
+ ## Development Setup
90
+
91
+ For local development setup:
92
+
93
+ ```sh
94
+ git clone https://github.com/deepak7376/robustbase
95
+ cd robustbase
96
+ pip install -r requirements.txt -r requirements-dev.txt
97
+ ```
98
+
99
+ ## Recent Changes
100
+
101
+ ### Version 3.0.0
102
+ - Changed the API's call
103
+ - Refactored the dir structure
104
+ - Updated README with usage examples for all functions.
105
+
106
+
107
+ ## Contributing
108
+
109
+ 1. Fork it ([https://github.com/deepak7376/robustbase/fork](https://github.com/deepak7376/robustbase/fork))
110
+ 2. Create your feature branch (`git checkout -b feature/fooBar`)
111
+ 3. Commit your changes (`git commit -am 'Add some fooBar'`)
112
+ 4. Push to the branch (`git push origin feature/fooBar`)
113
+ 5. Create a new Pull Request
114
+
115
+ ## References
116
+ - [Qn Scale Estimator](https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/qn_scale.htm)
117
+ - [Sn Scale Estimator](https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/sn_scale.htm)
118
+ - [Median Absolute Deviation](https://www.statisticshowto.datasciencecentral.com/median-absolute-deviation/)
119
+ - [Interquartile Range](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/interquartile-range/)
@@ -0,0 +1,4 @@
1
+ numpy>=1.18.0
2
+ scipy
3
+ statistics>=1.0.3.5
4
+
File without changes
@@ -0,0 +1,69 @@
1
+ import numpy as np
2
+
3
+ def Qn(x, constant=2.21914, finite_corr=True):
4
+ """
5
+ Qn scale estimator, Gaussian efficiency 82%
6
+
7
+ Parameters:
8
+ - x: list or array-like, numeric vector of observations.
9
+ - constant: float, number by which the result is multiplied; the default achieves consistency for normally distributed data.
10
+ - finite_corr: bool, logical indicating if the finite sample bias correction factor should be applied. Default to True unless constant is specified.
11
+
12
+ Returns:
13
+ - float: Qn scale estimator.
14
+ """
15
+ x = np.asarray(x) # Convert input to NumPy array
16
+ n = len(x)
17
+ if n < 2:
18
+ raise ValueError("At least 2 observations are required.")
19
+
20
+ # Calculate all pairwise absolute differences using NumPy broadcasting
21
+ diffs = np.abs(x[:, np.newaxis] - x)
22
+
23
+ # Flatten the upper triangle of the absolute differences matrix and sort
24
+ diffs_flat = np.triu(diffs).flatten()
25
+ diffs_flat = diffs_flat[diffs_flat != 0] # Remove zeros from the diagonal
26
+ diffs_flat.sort()
27
+
28
+ # Calculate the index for Qn estimation
29
+ h = int(np.floor(n / 2) + 1)
30
+ k = int(h * (h - 1) / 2)
31
+
32
+ # Calculate the bias correction factor
33
+ corr_factor = bias_corr(n)
34
+
35
+ # Calculate the Qn estimator
36
+ qn = constant * diffs_flat[k - 1] * corr_factor if finite_corr else constant * diffs_flat[k - 1]
37
+
38
+ return qn
39
+
40
+ def bias_corr(n):
41
+ """
42
+ Bias correction factor for Qn estimator.
43
+
44
+ Parameters:
45
+ - n: int, number of observations.
46
+
47
+ Returns:
48
+ - float: Bias correction factor.
49
+ """
50
+ # Determine if the number of observations is even or odd
51
+ even = (n % 2 == 0)
52
+
53
+ # Determine the magnitude of n
54
+ magnitude_n = min(n, 13)
55
+
56
+ # Calculate the key for bias correction
57
+ n_key = (even, magnitude_n)
58
+
59
+ # Calculate the bias correction factor based on key
60
+ if n_key == (True, 13):
61
+ corr_factor = 3.67561 + ((1.9654 + ((6.987 - (77 / n)) / n)) / n)
62
+ corr_factor = 1 / ((corr_factor / n) + 1)
63
+ elif n_key == (False, 13):
64
+ corr_factor = 1.60188 + ((- 2.1284 - (5.172 / n)) / n)
65
+ corr_factor = 1 / ((corr_factor / n) + 1)
66
+ else:
67
+ corr_factor = np.array([0.399356, 0.99365, 0.51321, 0.84401, 0.61220,
68
+ 0.85877, 0.66993, 0.87344, 0.72014, 0.88906, 0.75743])[n - 2]
69
+ return corr_factor
@@ -0,0 +1,40 @@
1
+ import numpy as np
2
+
3
+ def Sn(x, constant=1.1926, finite_corr=True):
4
+ """
5
+ Sn scale estimator, Gaussian efficiency 58%
6
+
7
+ Parameters:
8
+ - x: list or array-like, numeric vector of observations.
9
+ - constant: float, number by which the result is multiplied; the default achieves consistency for normally distributed data.
10
+ - finite_corr: bool, logical indicating if the finite sample bias correction factor should be applied. Default to True unless constant is specified.
11
+
12
+ Returns:
13
+ - float: Sn scale estimator.
14
+ """
15
+ # Check if the input array has at least 2 observations
16
+ n = len(x)
17
+ if n < 2:
18
+ raise ValueError("At least 2 observations are required.")
19
+
20
+ # Calculate all pairwise absolute differences
21
+ pairwise_diffs = np.abs(np.subtract.outer(x, x))
22
+
23
+ # Calculate the medians of the pairwise absolute differences
24
+ medians = np.median(pairwise_diffs, axis=0)
25
+
26
+ # Calculate the Sn estimator
27
+ sn = constant * np.median(medians)
28
+
29
+ # Apply finite sample correction if specified
30
+ if finite_corr:
31
+ if n <= 9:
32
+ correction = [0.743, 1.851, 0.954, 1.351, 0.993, 1.198, 1.005, 1.131]
33
+ correction = correction[n - 2]
34
+ elif n % 2 == 1:
35
+ correction = n / (n - 0.9)
36
+ else:
37
+ correction = 1
38
+ sn *= correction
39
+
40
+ return sn
@@ -0,0 +1,5 @@
1
+ from .iqr import iqr
2
+ from .mad import mad
3
+ from .Qn import Qn
4
+ from .Sn import Sn
5
+ from .covComed import covComed
@@ -0,0 +1,76 @@
1
+ import numpy as np
2
+ from scipy.linalg import solve, LinAlgError
3
+ from scipy.spatial.distance import mahalanobis
4
+ from collections import namedtuple
5
+
6
+ CovComedResult = namedtuple('CovComedResult', ['cov', 'center', 'weights'])
7
+
8
+ def covComed(X, n_iter=2, reweight=False, tol_solve=1e-7, trace=False, wgt_fun="01.original", control=None):
9
+ if control is None:
10
+ control = {}
11
+
12
+ # Default control values
13
+ control_defaults = {
14
+ 'tolSolve': tol_solve,
15
+ 'trace': trace,
16
+ 'wgtFUN': wgt_fun
17
+ }
18
+
19
+ # Update control with any additional parameters provided
20
+ control.update(control_defaults)
21
+
22
+ # Initial center and covariance
23
+ center = np.median(X, axis=0)
24
+ cov = np.cov(X, rowvar=False)
25
+
26
+ for i in range(n_iter):
27
+ # Check if covariance matrix is singular
28
+ if np.linalg.matrix_rank(cov) < cov.shape[0]:
29
+ raise LinAlgError("Covariance matrix is singular. Cannot proceed with computations.")
30
+
31
+ # Compute Mahalanobis distances
32
+ inv_cov = solve(cov, np.eye(cov.shape[0]), assume_a='pos')
33
+ dists = np.array([mahalanobis(x, center, inv_cov) for x in X])
34
+
35
+ if control['trace']:
36
+ print(f"Iteration {i}: center={center}, cov={cov}")
37
+
38
+ # Compute weights
39
+ if wgt_fun == "01.original":
40
+ weights = (dists <= 1).astype(int)
41
+ else:
42
+ raise ValueError("Only '01.original' wgtFUN is implemented")
43
+
44
+ # Update center and covariance with weights
45
+ if np.sum(weights) == 0:
46
+ break
47
+
48
+ center = np.average(X, axis=0, weights=weights)
49
+ cov = np.cov(X.T, aweights=weights)
50
+
51
+ # Final reweighting step
52
+ if reweight:
53
+ if np.linalg.matrix_rank(cov) < cov.shape[0]:
54
+ raise LinAlgError("Covariance matrix is singular. Cannot proceed with computations.")
55
+
56
+ inv_cov = solve(cov, np.eye(cov.shape[0]), assume_a='pos')
57
+ dists = np.array([mahalanobis(x, center, inv_cov) for x in X])
58
+ if wgt_fun == "01.original":
59
+ weights = (dists <= 1).astype(int)
60
+ else:
61
+ raise ValueError("Only '01.original' wgtFUN is implemented")
62
+
63
+ return CovComedResult(cov, center, weights)
64
+
65
+ # Example usage
66
+ if __name__ == "__main__":
67
+ # Example data matrix (with non-singular covariance matrix)
68
+ X = np.random.rand(100, 3) # 100 samples, 3 features
69
+
70
+ try:
71
+ result = covComed(X)
72
+ print("Covariance Matrix:", result.cov)
73
+ print("Center:", result.center)
74
+ print("Weights:", result.weights)
75
+ except LinAlgError as e:
76
+ print("Error:", e)
@@ -0,0 +1,14 @@
1
+ import numpy as np
2
+
3
+ def iqr(x):
4
+ """
5
+ Interquartile range
6
+
7
+ Parameters:
8
+ - x: list or array-like, numeric vector of observations.
9
+
10
+ Returns:
11
+ - tuple: Interquartile range (Q3 - Q1).
12
+ """
13
+ q1, q3 = np.percentile(x, [25, 75])
14
+ return (q3, q1)
@@ -0,0 +1,29 @@
1
+ import numpy as np
2
+ from robustbase.utils.median import median
3
+
4
+
5
+ def mad(x, center=None, constant=1.4826, na=False, low=False, high=False):
6
+ """
7
+ Calculate the Median Absolute Deviation (MAD).
8
+
9
+ Parameters:
10
+ - x: list or array-like, numeric vector of observations.
11
+ - center: float or None, value around which the MAD is computed. If None, median of x is used.
12
+ - constant: float, scaling factor to make MAD consistent estimator of the standard deviation.
13
+ - na: bool, if True, handle NA/NaN values in x. (Not implemented in this function)
14
+ - low: bool, if True, compute the ‘lo-median’. (Not applicable in this function)
15
+ - high: bool, if True, compute the ‘hi-median’. (Not applicable in this function)
16
+
17
+ Returns:
18
+ - float: MAD value.
19
+ """
20
+ x = np.asarray(x)
21
+ if len(x) == 0:
22
+ raise ValueError("Empty list provided.")
23
+ if len(x) == 1:
24
+ return 0.0
25
+
26
+ center = median(x) if center is None else center
27
+ amd = np.abs(x - center)
28
+
29
+ return constant * median(amd)
@@ -0,0 +1,2 @@
1
+ from .mean import mean # noqa: F401
2
+ from .median import median # noqa: F401
@@ -0,0 +1,17 @@
1
+ import numpy as np
2
+
3
+ def mean(x):
4
+ """
5
+ Calculate the mean of a list or array-like object.
6
+
7
+ Parameters:
8
+ - x: list or array-like, numeric vector of observations.
9
+
10
+ Returns:
11
+ - float: Mean value.
12
+ """
13
+ x = np.asarray(x)
14
+ if len(x) == 0:
15
+ raise ValueError("Empty list provided.")
16
+
17
+ return np.mean(x)
@@ -0,0 +1,35 @@
1
+ import numpy as np
2
+
3
+
4
+ def median(x, low=False, high=False):
5
+ """
6
+ Calculate the median of a list or array-like object.
7
+
8
+ Parameters:
9
+ - x: list or array-like, numeric vector of observations.
10
+ - low: bool, if True, return the low median for even sample size. If ``True``, ``high`` is ignored.
11
+ - high: bool, if True, return the high median for even sample size.
12
+
13
+ Returns:
14
+ - float: Median value.
15
+ """
16
+
17
+ n = len(x)
18
+ if n == 0:
19
+ raise ValueError("Empty list provided.")
20
+
21
+ # for odd sample size, all three medians are the same
22
+ if n % 2 == 1:
23
+ return np.median(a=x)
24
+
25
+ # for even sample sizes, the median is the average of the two middle values if
26
+ # neither the low nor high median is requested
27
+ if not (low or high):
28
+ return np.median(a=x)
29
+
30
+ # otherwise, either the low or the high median are found via introselect
31
+ median_idx = n // 2
32
+ if low:
33
+ median_idx -= 1
34
+
35
+ return np.partition(a=x, kth=median_idx)[median_idx]
@@ -0,0 +1 @@
1
+ __version__ = '3.0.7'