robpy 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of robpy might be problematic. Click here for more details.

Files changed (55) hide show
  1. robpy/__init__.py +0 -0
  2. robpy/covariance/__init__.py +6 -0
  3. robpy/covariance/base.py +82 -0
  4. robpy/covariance/cellmcd.py +621 -0
  5. robpy/covariance/initial_ddcw.py +133 -0
  6. robpy/covariance/kendall.py +21 -0
  7. robpy/covariance/mcd.py +470 -0
  8. robpy/covariance/ogk.py +95 -0
  9. robpy/covariance/utils/alter_covariance.py +31 -0
  10. robpy/covariance/utils/cellmcd_utils.py +38 -0
  11. robpy/covariance/utils/cellmcd_visualization_utils.py +96 -0
  12. robpy/covariance/wrapping.py +72 -0
  13. robpy/datasets/__init__.py +4 -0
  14. robpy/datasets/base.py +389 -0
  15. robpy/datasets/data/animals.csv +66 -0
  16. robpy/datasets/data/glass.csv +181 -0
  17. robpy/datasets/data/stars.csv +48 -0
  18. robpy/datasets/data/telephone.csv +25 -0
  19. robpy/datasets/data/topgear.csv +298 -0
  20. robpy/datasets/descr/animals.rst +26 -0
  21. robpy/datasets/descr/glass.rst +20 -0
  22. robpy/datasets/descr/stars.rst +28 -0
  23. robpy/datasets/descr/telephone.rst +23 -0
  24. robpy/datasets/descr/topgear.rst +51 -0
  25. robpy/outliers/__init__.py +4 -0
  26. robpy/outliers/ddc.py +296 -0
  27. robpy/pca/__init__.py +3 -0
  28. robpy/pca/base.py +97 -0
  29. robpy/pca/robpca.py +89 -0
  30. robpy/pca/spca.py +48 -0
  31. robpy/preprocessing/__init__.py +3 -0
  32. robpy/preprocessing/data_cleaner.py +214 -0
  33. robpy/preprocessing/scaling.py +57 -0
  34. robpy/preprocessing/transfo.py +591 -0
  35. robpy/preprocessing/utils.py +63 -0
  36. robpy/regression/__init__.py +3 -0
  37. robpy/regression/base.py +116 -0
  38. robpy/regression/lts.py +408 -0
  39. robpy/regression/mm_estimator.py +57 -0
  40. robpy/regression/s_estimator.py +188 -0
  41. robpy/univariate/__init__.py +9 -0
  42. robpy/univariate/base.py +53 -0
  43. robpy/univariate/mcd.py +84 -0
  44. robpy/univariate/onestep_m.py +143 -0
  45. robpy/univariate/qn.py +112 -0
  46. robpy/univariate/tau.py +63 -0
  47. robpy/utils/distance.py +24 -0
  48. robpy/utils/general.py +31 -0
  49. robpy/utils/logging.py +22 -0
  50. robpy/utils/median.py +62 -0
  51. robpy/utils/outlyingness.py +61 -0
  52. robpy/utils/rho.py +35 -0
  53. robpy-0.1.0.dist-info/METADATA +31 -0
  54. robpy-0.1.0.dist-info/RECORD +55 -0
  55. robpy-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,188 @@
1
+ import logging
2
+ import numpy as np
3
+
4
+ from sklearn.exceptions import NotFittedError
5
+ from statsmodels.api import WLS, add_constant
6
+ from statsmodels.regression.linear_model import RegressionResultsWrapper
7
+
8
+ from robpy.regression.base import RobustRegressor, _convert_input_to_array
9
+ from robpy.utils.rho import BaseRho, TukeyBisquare
10
+
11
+
12
+ class SEstimator(RobustRegressor):
13
+ """Fast S algorithm similar to lmrob.S on robustbase
14
+ (https://search.r-project.org/CRAN/refmans/robustbase/html/lmrob.S.html).
15
+ S-estimation was initially described in
16
+
17
+ Rousseeuw, P. J., and Yohai, V. J. (1984), "Robust Regression by Means of S-Estimators,"
18
+ in Robust and Nonlinear Time Series,
19
+ eds. J. Franke, W. Hardie, and D. Martin, Lecture Notes in Statistics, 26, Berlin:
20
+ Springer-Verlag, pp. 256-272.
21
+
22
+ This code is an implementation of the Fast S algorithm described in
23
+
24
+ Salibian-Barrera, M., & Yohai, V. J. (2006).
25
+ A Fast Algorithm for S-Regression Estimates.
26
+ Journal of Computational and Graphical Statistics, 15(2), 414–427.
27
+ http://www.jstor.org/stable/27594186
28
+
29
+
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ rho: BaseRho = TukeyBisquare(c=1.547),
35
+ n_initial_subsets: int = 500,
36
+ n_initial_i_steps: int = 2,
37
+ n_best_subsets: int = 5,
38
+ max_scale_iterations: int = 2,
39
+ b: float = 0.5,
40
+ fit_intercept: bool = True,
41
+ relative_tolerance: float = 1e-7,
42
+ scale_tolerance: float = 1e-10,
43
+ random_state: int = 101,
44
+ ):
45
+ """Fast S estimator.
46
+
47
+ Args:
48
+ rho (BaseRho, optional):
49
+ score function to use on the residuals. Defaults to bisquare.
50
+ n_initial_subsets (int, optional):
51
+ Number of initial subsets to sample (`N` in the original paper).
52
+ Defaults to 500.
53
+ n_initial_i_steps (int, optional):
54
+ Number of i-steps to take on the initial subsets (`k` in the original paper).
55
+ Defaults to 2.
56
+ n_best_subsets (int, optional):
57
+ Number of subsets with the best M-scales (residuals transformered by score function)
58
+ (`t` in the original paper).
59
+ Defaults to 5.
60
+ max_scale_iterations (int, optional):
61
+ number of iterative steps to derive M-scale estimates (`r` in the original paper).
62
+ b (float, optional):
63
+ constant on the RHS of the M scale equation
64
+ fit_intercept (bool, optional):
65
+ Whether an intercept should be included in the linear regression
66
+ relative_tolerance (float, optional):
67
+ Determines the stopping criterium for the i-steps untill convergence
68
+ (diff in beta norm should be higher then
69
+ relative_tolerance * max(relative_tolerance, beta_norm))
70
+ scale_tolerance (float, optional):
71
+ If the difference between 2 subsequent scale estimates is below this threshold,
72
+ the iterations are stopped and it is assumed the scale estimate converged.
73
+ """
74
+ self.rho = rho
75
+ self.n_initial_subsets = n_initial_subsets
76
+ self.n_initial_i_steps = n_initial_i_steps
77
+ self.n_best_subsets = n_best_subsets
78
+ self.max_scale_iterations = max_scale_iterations
79
+ self.b = b
80
+ self.fit_intercept = fit_intercept
81
+ self.model = None
82
+ self.random_state = random_state
83
+ self.relative_tolerance = relative_tolerance
84
+ self.scale_tolerance = scale_tolerance
85
+ self.logger = logging.getLogger("S-estimator")
86
+
87
+ def fit(self, X, y, verbosity=logging.WARNING):
88
+ self.logger.setLevel(verbosity)
89
+
90
+ X, y = _convert_input_to_array(X, y)
91
+ if self.fit_intercept:
92
+ X = add_constant(X)
93
+ models, scales = self._get_initial_models(X, y)
94
+ self.logger.info(f"Fitted {len(models)} initial models.")
95
+ best_idx = np.argsort(scales)[: self.n_best_subsets]
96
+ best_models = []
97
+ best_scales = []
98
+ for i, idx in enumerate(best_idx, start=1):
99
+ self.logger.info(
100
+ f"Applying i-steps untill convergence for model {i} out of {self.n_best_subsets}"
101
+ )
102
+ previous_m = models[idx]
103
+ previous_s = scales[idx]
104
+ n_iter = 0
105
+ while True:
106
+ try:
107
+ m, s = self._i_step(X, y, (previous_m.predict(X) - y).flatten())
108
+ n_iter += 1
109
+ except np.linalg.LinAlgError:
110
+ self.logger.warning(
111
+ f"Failed to aply i-steps untill convergence. "
112
+ f"Starting scale was: {previous_s}. Failed iteration = {n_iter}."
113
+ f"Storing model after last successfull i-step."
114
+ )
115
+ m.n_iter = n_iter
116
+ best_models.append(previous_m)
117
+ best_scales.append(previous_s)
118
+ break
119
+ if self._converged(previous_m.params, m.params):
120
+ m.n_iter = n_iter
121
+ best_models.append(m)
122
+ best_scales.append(s)
123
+ break
124
+ previous_m = m
125
+ previous_s = s
126
+
127
+ best_idx = np.argmin(best_scales)
128
+ self.model = best_models[best_idx]
129
+ self._scale = best_scales[best_idx]
130
+ return self
131
+
132
+ def predict(self, X) -> np.ndarray:
133
+ if self.model is None:
134
+ raise NotFittedError
135
+ X, _ = _convert_input_to_array(X)
136
+ if self.fit_intercept:
137
+ X = add_constant(X)
138
+ return self.model.predict(X)
139
+
140
+ def _get_scale(self, s0: float, residuals: np.ndarray):
141
+ for i in range(self.max_scale_iterations):
142
+ new_s = s0 * np.sqrt(np.mean(self.rho.rho(residuals / s0)) / self.b)
143
+ if np.abs(s0 - new_s) < self.scale_tolerance:
144
+ break
145
+ s0 = new_s
146
+ return new_s
147
+
148
+ def _converged(self, previous_beta: np.ndarray, current_beta: np.ndarray) -> bool:
149
+ norm_diff = float(np.linalg.norm(current_beta - previous_beta))
150
+ norm_beta = float(np.linalg.norm(current_beta))
151
+
152
+ return norm_diff <= self.relative_tolerance * max(self.relative_tolerance, norm_beta)
153
+
154
+ def _i_step(
155
+ self,
156
+ X,
157
+ y,
158
+ residuals: np.ndarray,
159
+ initial_scale: float | None = None,
160
+ ) -> tuple[RegressionResultsWrapper, float]:
161
+ if initial_scale is None:
162
+ initial_scale = np.median(np.abs(residuals)) / 0.6745
163
+ new_scale = self._get_scale(s0=initial_scale, residuals=residuals)
164
+ residuals[residuals == 0] = np.finfo(np.float64).eps # avoid divide by 0 errors
165
+ weights = self.rho.psi(residuals / new_scale) / (residuals / new_scale)
166
+ model = WLS(endog=y, exog=X, weights=weights).fit()
167
+ model.weights = weights
168
+ return model, new_scale
169
+
170
+ def _get_initial_models(self, X, y) -> tuple[list[RegressionResultsWrapper], list[float]]:
171
+ models = []
172
+ scales = []
173
+ for seed in range(self.random_state, self.random_state + self.n_initial_subsets):
174
+ np.random.seed(seed)
175
+ sample_idx = np.random.choice(X.shape[0], X.shape[1] + 1, replace=False)
176
+ model = WLS(y[sample_idx], X[sample_idx]).fit()
177
+ residuals = model.predict(X) - y
178
+ scale = np.median(np.abs(residuals)) / 0.6745
179
+ try:
180
+ for _ in range(self.n_initial_i_steps):
181
+ model, scale = self._i_step(X, y, residuals)
182
+ residuals = model.resid
183
+ models.append(model)
184
+ scales.append(scale)
185
+ except np.linalg.LinAlgError as e:
186
+ self.logger.debug(f"Failed to apply i-steps on initial model with seed {seed}: {e}")
187
+
188
+ return models, scales
@@ -0,0 +1,9 @@
1
+ from robpy.univariate.base import LocationOrScaleEstimator
2
+ from robpy.univariate.qn import QnEstimator
3
+ from robpy.univariate.mcd import UnivariateMCDEstimator
4
+ from robpy.univariate.tau import TauEstimator
5
+ from robpy.univariate.onestep_m import (
6
+ OneStepMEstimator,
7
+ HuberOneStepMEstimator,
8
+ CellwiseOneStepMEstimator,
9
+ )
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ from sklearn.exceptions import NotFittedError
5
+ from abc import abstractmethod, ABC
6
+ from typing import Protocol
7
+
8
+
9
+ class LocationOrScaleEstimator(Protocol):
10
+ def __call__(self, x: np.ndarray, axis: int = 0) -> np.ndarray | float:
11
+ ...
12
+
13
+
14
+ class RobustScaleEstimator(ABC):
15
+ def __init__(self, *, can_handle_nan: bool = False):
16
+ """Base class for robust univariate scale estimators
17
+
18
+ Args:
19
+ can_handle_nan (bool, optional):
20
+ Attribute specifying if the robust scaler can handles nans.
21
+ Defaults to False.
22
+
23
+ """
24
+ self.can_handle_nan = can_handle_nan
25
+
26
+ def fit(self, X: np.ndarray, ignore_nan: bool = False) -> RobustScaleEstimator:
27
+ if len(X.shape) != 1:
28
+ raise ValueError(
29
+ f"X must be univariate, but received a matrix with dimensions {X.shape}"
30
+ )
31
+ if not self.can_handle_nan and not ignore_nan and np.isnan(X).any():
32
+ raise ValueError("The data X contains NaN and estimator cannot handle missing values.")
33
+ elif ignore_nan and np.isnan(X).any():
34
+ X = X[~np.isnan(X)]
35
+ self._calculate(X)
36
+ return self
37
+
38
+ @abstractmethod
39
+ def _calculate(self, X: np.ndarray):
40
+ """Must set self.scale_ and self.location_"""
41
+ pass
42
+
43
+ @property
44
+ def scale(self):
45
+ if not hasattr(self, "scale_"):
46
+ raise NotFittedError("Scale not available. First run .fit()")
47
+ return self.scale_
48
+
49
+ @property
50
+ def location(self):
51
+ if not hasattr(self, "location_"):
52
+ raise NotFittedError("Location not available. First run .fit()")
53
+ return self.location_
@@ -0,0 +1,84 @@
1
+ import numpy as np
2
+
3
+ from robpy.univariate.base import RobustScaleEstimator
4
+ from scipy.stats import chi2, gamma
5
+
6
+
7
+ class UnivariateMCDEstimator(RobustScaleEstimator):
8
+ def __init__(self, h_size: float | int | None = None, consistency_correction: bool = True):
9
+ """
10
+ Implementation of univariate MCD (Hubert & Debruyne, 2009)
11
+
12
+ Args:
13
+ h_size (float or int, optional): size of the h subset.
14
+ If an integer between n/2 and n is passed, it is interpreted as an absolute value.
15
+ If a float between 0.5 and 1 is passed, it is interpreted as a proportation
16
+ of n (the training set size).
17
+ If None, it is set to floor(n/2) + 1.
18
+ Defaults to None.
19
+ consistency_correction (boolean, optional):
20
+ whether the estimates should be consistent at the normal model.
21
+ Defaults to True.
22
+
23
+ References:
24
+ Hubert, M., & Debruyne, M. (2010). Minimum covariance determinant.
25
+ Wiley interdisciplinary reviews: Computational statistics, 2(1), 36-43.
26
+ """
27
+ super().__init__()
28
+ self.h_size = h_size
29
+ self.consistency_correction = consistency_correction
30
+
31
+ def _calculate(self, X: np.ndarray):
32
+ self._set_h_size(X)
33
+ if self.h_size == X.shape[0]:
34
+ self.raw_location_ = self.location_ = X.mean()
35
+ self.raw_scale_ = self.scale_ = X.std()
36
+ self.raw_variance_ = self.variance_ = np.square(self.raw_scale_)
37
+ return
38
+
39
+ self.raw_variance_, self.raw_location_ = self._get_raw_estimates(X)
40
+ self.variance_, self.location_ = self._reweighting(X)
41
+ self.raw_scale_ = np.sqrt(self.raw_variance_)
42
+ self.scale_ = np.sqrt(self.variance_)
43
+
44
+ def _get_raw_estimates(self, X: np.ndarray):
45
+ n = len(X)
46
+ X = np.sort(X)
47
+ var_best = np.inf
48
+ index_best = 1
49
+ for i in range(n - self.h_size + 1):
50
+ var_new = np.var(X[i : (i + self.h_size)])
51
+ if var_new < var_best:
52
+ var_best = var_new
53
+ index_best = i
54
+ raw_var = var_best
55
+ raw_loc = np.mean(X[index_best : (index_best + self.h_size)])
56
+ if self.consistency_correction:
57
+ # [Minimum covariance determinant, Mia Hubert & Michiel Debruyne (2009)]
58
+ raw_var = raw_var * (self.h_size / n) / chi2.cdf(chi2.ppf(self.h_size / n, df=1), df=3)
59
+ return raw_var, raw_loc
60
+
61
+ def _reweighting(self, X: np.ndarray):
62
+ distances = (X - self.raw_location_) ** 2 / self.raw_variance_
63
+ mask = distances < chi2.ppf(0.975, df=1)
64
+ loc = np.mean(X[mask])
65
+ var = np.var(X[mask])
66
+ if self.consistency_correction:
67
+ # Croux & Haesbroeck (1999)
68
+ delta = np.sum(mask) / len(X)
69
+ var = var * delta * np.reciprocal(gamma.cdf(chi2.ppf(delta, df=1) / 2, a=3 / 2))
70
+ return var, loc
71
+
72
+ def _set_h_size(self, X: np.ndarray):
73
+ n = len(X)
74
+ if self.h_size is None:
75
+ self.h_size = n // 2 + 1
76
+ elif isinstance(self.h_size, int) and (n / 2 <= self.h_size <= n):
77
+ pass
78
+ elif (isinstance(self.h_size, float) and (0.5 <= self.h_size <= 1)) or self.h_size == 1:
79
+ self.h_size = int(self.h_size * n)
80
+ else:
81
+ raise ValueError(
82
+ f"h_size must be an integer between n/2 and n or a float between 0.5 and 1 "
83
+ f"but received {self.h_size}"
84
+ )
@@ -0,0 +1,143 @@
1
+ import numpy as np
2
+
3
+ from scipy.stats import median_abs_deviation
4
+
5
+ from robpy.univariate.base import RobustScaleEstimator
6
+ from robpy.utils.rho import BaseRho, Huber, TukeyBisquare
7
+ from robpy.univariate.mcd import UnivariateMCDEstimator
8
+
9
+
10
+ class OneStepMEstimator(RobustScaleEstimator):
11
+ def __init__(
12
+ self,
13
+ loc_rho: BaseRho,
14
+ scale_rho: BaseRho,
15
+ delta: float,
16
+ min_abs_scale: float = 1e-12,
17
+ ):
18
+ """
19
+ Implementation of the single-step M-estimator for location and scale
20
+
21
+ Args:
22
+ loc_rho: rho function for scale estimation (e.g. Huber(b=1.5))
23
+ scale_rho: rho function for scale estimation (e.g. Huber(b=2.5))
24
+ delta (float, optional): Consistency factor at normal model depending on b:
25
+ quad(np.minimum(np.abs(x**2), b**2) * norm.pdf(x), -np.inf, np.inf, args=(b))
26
+ min_abs_scale (float, optional): Only if mad is larger than min_abs_scale
27
+ the M estimator will be calculated.
28
+ Defaults to 1e-12.
29
+
30
+ References:
31
+ Rousseeuw, P. J., & Bossche, W. V. D. (2018).
32
+ Detecting deviating data cells. Technometrics, 60(2), 135-145.
33
+ --> loc_rho = TukeyBiWeight(c=3) and scale_rho = Huber(b=2.5)
34
+
35
+ See also r code: https://rdrr.io/cran/cellWise/man/estLocScale.html
36
+
37
+ """
38
+ super().__init__()
39
+ self.loc_rho = loc_rho
40
+ self.scale_rho = scale_rho
41
+ self.delta = delta
42
+ self.min_abs_scale = min_abs_scale
43
+
44
+ def _calculate(self, X: np.ndarray):
45
+ """
46
+ Args:
47
+ X (np.ndarray):
48
+ univariate data
49
+ """
50
+ if np.isnan(X).any():
51
+ raise ValueError("Input data contains NaN values")
52
+ # initial estimates:
53
+ med = np.median(X)
54
+ mad = median_abs_deviation(X, scale="normal")
55
+ safe_mad = 1 if mad < self.min_abs_scale else mad
56
+
57
+ # first location:
58
+ residuals = (X - med) / safe_mad
59
+ mask = np.abs(residuals) > 1e-5
60
+ weights = np.ones_like(residuals)
61
+ weights[mask] = self.loc_rho.psi(residuals[mask]) / residuals[mask]
62
+ mu_new = np.sum(weights * X) / np.sum(weights)
63
+
64
+ # second scale:
65
+ if mad < self.min_abs_scale:
66
+ s_new = 0
67
+ else:
68
+ Xcentered = X - med
69
+ residuals = Xcentered / mad
70
+ s_new = mad * np.sqrt(1 / self.delta * np.mean(self.scale_rho.psi(residuals) ** 2))
71
+
72
+ self.location_ = mu_new
73
+ self.scale_ = s_new
74
+
75
+ return self
76
+
77
+
78
+ class HuberOneStepMEstimator(OneStepMEstimator):
79
+ def __init__(self):
80
+ """
81
+ Implementation of Huber M-estimator with 1 step: location and scale
82
+
83
+ [analoguous to estLocScale {cellWise}: type ="hubhub"
84
+ https://github.com/cran/cellWise/blob/master/src/LocScaleEstimators.cpp]
85
+ """
86
+ super().__init__(loc_rho=Huber(b=1.5), scale_rho=Huber(b=1.5), delta=0.7784655)
87
+
88
+
89
+ class CellwiseOneStepMEstimator(OneStepMEstimator):
90
+ def __init__(self):
91
+ """
92
+ Implementation of the single step M estimator (robLoc and robScale) proposed in
93
+ Rousseeuw, P. J., & Bossche, W. V. D. (2018). In this paper, the location rho function is
94
+ set to `TukeyBiWeight(c=3)` and the scale rho function to `Huber(b=2.5)`
95
+
96
+ References:
97
+ - Rousseeuw, P. J., & Bossche, W. V. D. (2018). Detecting deviating data cells.
98
+ Technometrics, 60(2), 135-145.
99
+ """
100
+ super().__init__(loc_rho=TukeyBisquare(c=3), scale_rho=Huber(b=2.5), delta=0.845)
101
+
102
+
103
+ class OneStepWrappingEstimator(RobustScaleEstimator):
104
+ def __init__(self):
105
+ """
106
+ [analoguous to estLocScale {cellWise}: type ="wrap"
107
+ https://github.com/cran/cellWise/blob/master/src/LocScaleEstimators.cpp]
108
+ """
109
+ super().__init__()
110
+
111
+ def _calculate(self, X: np.array):
112
+ """
113
+ Args:
114
+ X (np.ndarray):
115
+ univariate data
116
+ """
117
+
118
+ # initial estimates: univariate MCD
119
+ initial_estimates = UnivariateMCDEstimator().fit(X)
120
+
121
+ # one step M estimator for location using hyperbolic tangent weight function:
122
+ X_standardized = (X - initial_estimates.location) / initial_estimates.scale
123
+ weights = np.array([self._tanh_weights(val) for val in X_standardized])
124
+ self.location_ = np.sum(weights * X) / np.sum(weights)
125
+
126
+ self.scale_ = initial_estimates.scale
127
+
128
+ def _tanh_weights(self, val: float) -> float:
129
+ b = 1.5
130
+ c = 4
131
+ if np.abs(val) < b:
132
+ return 1.0
133
+ elif np.abs(val) > c:
134
+ return 0.0
135
+ else:
136
+ A = 0.7532528
137
+ B = 0.8430849
138
+ k = 4.1517212
139
+ return (
140
+ np.sqrt(A * (k - 1))
141
+ * np.tanh(0.5 * np.sqrt((k - 1) * B**2 / A) * (c - np.abs(val)))
142
+ / (np.abs(val))
143
+ )
robpy/univariate/qn.py ADDED
@@ -0,0 +1,112 @@
1
+ import numpy as np
2
+
3
+ from robpy.univariate.base import RobustScaleEstimator, LocationOrScaleEstimator
4
+ from robpy.utils.median import weighted_median
5
+
6
+
7
+ class QnEstimator(RobustScaleEstimator):
8
+ def __init__(
9
+ self,
10
+ location_func: LocationOrScaleEstimator = np.median,
11
+ consistency_correction: bool = True,
12
+ finite_correction: bool = True,
13
+ ):
14
+ """
15
+ Implementation of Qn estimator
16
+
17
+ [Time-efficient algorithms for two highly robust estimators of scale,
18
+ Christophe Croux and Peter J. Rousseeuw (1992)]
19
+ [Selecting the k^th element in X+Y and X1+...+Xm,
20
+ Donald B. Johnson and Tetsuo Mizoguchi (1978)]
21
+
22
+ Args:
23
+ location_func (LocationOrScaleEstimator, optional): as the Qn estimator does not
24
+ estimate location, a location function should be explicitly passed.
25
+ consistency_correction (bool, optional):
26
+ boolean indicating if consistency for normality should be applied.
27
+ Defaults to True.
28
+ finite_correction (bool, optional):
29
+ boolean indicating if finite sample correction should be applied.
30
+ Defaults to True.
31
+ """
32
+ super().__init__()
33
+ self.location_func = location_func
34
+ self.consistency_correction = consistency_correction
35
+ self.finite_correction = finite_correction
36
+
37
+ def _calculate(self, X: np.ndarray):
38
+ """
39
+ Args:
40
+ X (np.ndarray):
41
+ univariate data
42
+ """
43
+
44
+ n = len(X)
45
+ h = n // 2 + 1
46
+ k = h * (h - 1) // 2
47
+ y = np.sort(X)
48
+ left = n + 1 - np.arange(n)
49
+ right = np.full(n, n)
50
+ jhelp = n * (n + 1) // 2
51
+ knew = k + jhelp
52
+ nL = jhelp
53
+ nR = n * n
54
+ found = False
55
+
56
+ while (nR - nL) > n and (not found):
57
+ weight = right - left + 1
58
+ jhelp = (left + weight // 2).astype(int)
59
+ work = y - y[n - jhelp]
60
+ trial = weighted_median(work, weight)
61
+ P = np.searchsorted(-np.flip(y), trial - y, "left", np.arange(n))
62
+ Q = np.searchsorted(-np.flip(y), trial - y, "right", np.arange(n)) + 1
63
+ if knew <= np.sum(P):
64
+ right = P
65
+ nR = np.sum(P)
66
+ elif knew > (np.sum(Q) - n):
67
+ left = Q
68
+ nL = np.sum(Q) - n
69
+ else:
70
+ Qn = trial
71
+ found = True
72
+ if not found:
73
+ work = []
74
+ for i in range(1, n):
75
+ if left[i] <= right[i]:
76
+ for jj in range(int(left[i]), int(right[i] + 1)):
77
+ work.append(y[i] - y[n - jj - 1 + 1])
78
+ k = int(knew - nL)
79
+ Qn = np.partition(np.array(work), k - 1)[:k].max()
80
+
81
+ if self.finite_correction:
82
+ dn = _get_small_sample_dn(n)
83
+ Qn = dn * Qn
84
+ if self.consistency_correction:
85
+ c = 2.219144
86
+ Qn = c * Qn
87
+
88
+ self.scale_ = Qn
89
+ self.location_ = self.location_func(X)
90
+
91
+
92
+ def _get_small_sample_dn(n: int):
93
+ """
94
+ Calculates the correction factor for the Qn estimator
95
+ at small samples [Time-efficient algorithms for two highly robust estimators of scale,
96
+ Christophe Croux and Peter J. Rousseeuw (1992)].
97
+ """
98
+ DNDICT = {
99
+ 2: 0.399,
100
+ 3: 0.994,
101
+ 4: 0.512,
102
+ 5: 0.844,
103
+ 6: 0.611,
104
+ 7: 0.857,
105
+ 8: 0.669,
106
+ 9: 0.872,
107
+ }
108
+ if n <= 9:
109
+ return DNDICT.get(n)
110
+ elif n % 2 != 0:
111
+ return n / (n + 1.4)
112
+ return n / (n + 3.8)
@@ -0,0 +1,63 @@
1
+ import numpy as np
2
+
3
+ from robpy.univariate.base import RobustScaleEstimator
4
+ from scipy.stats import median_abs_deviation, norm
5
+
6
+
7
+ class TauEstimator(RobustScaleEstimator):
8
+ def __init__(
9
+ self,
10
+ c1: float = 4.5,
11
+ c2: float = 3.0,
12
+ consistency_correction: bool = True,
13
+ ):
14
+ """
15
+ Implementation of tau estimator of scale
16
+
17
+ [Robust Estimates of Location and Dispersion for High-Dimensional Datasets,
18
+ Ricarco A Maronna and Ruben H Zamar (2002)]
19
+
20
+ Args:
21
+ c1 (float, optional):
22
+ constant for the weight function, defaults to 4.5
23
+ c2 (float, optional):
24
+ constant for the rho function, defaults to 3.0
25
+ consistency_correction (bool, optional):
26
+ boolean indicating if consistency for normality should be applied.
27
+ Defaults to True.
28
+ """
29
+ super().__init__()
30
+ self.c1 = c1
31
+ self.c2 = c2
32
+ self.consistency_correction = consistency_correction
33
+
34
+ def _calculate(self, X: np.ndarray):
35
+ """
36
+ Args:
37
+ X (np.ndarray):
38
+ univariate data
39
+ """
40
+ n = len(X)
41
+ sigma0 = median_abs_deviation(X)
42
+ weights = self._weight_function((X - np.median(X)) / sigma0)
43
+ self.location_ = np.sum(X * weights) / np.sum(weights)
44
+ self.scale_ = sigma0 * np.sqrt(
45
+ 1 / n * np.sum(self._rho_function((X - self.location_) / sigma0))
46
+ )
47
+ if self.consistency_correction:
48
+ """
49
+ expectation of rho(X/qnorm(3/4)) for X standard normal
50
+ """
51
+ b = self.c2 * norm.ppf(3 / 4)
52
+ corr = 2 * ((1 - b**2) * norm.cdf(b) - b * norm.pdf(b) + b**2) - 1
53
+ self.scale_ = self.scale_ / np.sqrt(corr)
54
+
55
+ def _weight_function(self, X):
56
+ return np.where(
57
+ np.abs(X) <= self.c1,
58
+ (1 - (X / self.c1) ** 2) ** 2,
59
+ 0.0,
60
+ )
61
+
62
+ def _rho_function(self, X):
63
+ return np.where(X**2 <= self.c2**2, X**2, self.c2**2)
@@ -0,0 +1,24 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+
5
+ def mahalanobis_distance(
6
+ data: np.ndarray | pd.DataFrame, location: np.ndarray, covariance: np.ndarray
7
+ ):
8
+ """
9
+ Calculate the Mahalanobis distance for multiple data vectors.
10
+
11
+ Parameters:
12
+ data (np.ndarray or pd.DataFrame): An array-like object where each row is a data vector.
13
+ location (np.ndarray): the center of the data
14
+ covariance (np.ndarray): the scatter estimator of the data
15
+
16
+ Returns:
17
+ np.ndarray: an array of Mahalanobis distances for each data vector.
18
+ """
19
+ if isinstance(data, pd.DataFrame):
20
+ data = data.values
21
+ cov_inv = np.linalg.inv(covariance)
22
+
23
+ centered_data = data - location.flatten()
24
+ return np.sqrt(np.sum(centered_data.dot(cov_inv) * centered_data, axis=1))