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,95 @@
1
+ import numpy as np
2
+ from scipy.stats import median_abs_deviation, chi2
3
+
4
+ from robpy.utils.distance import mahalanobis_distance
5
+ from robpy.covariance.base import RobustCovarianceEstimator
6
+ from robpy.univariate import LocationOrScaleEstimator
7
+
8
+
9
+ class OGKEstimator(RobustCovarianceEstimator):
10
+ def __init__(
11
+ self,
12
+ *,
13
+ store_precision=True,
14
+ assume_centered=False,
15
+ location_estimator: LocationOrScaleEstimator = np.median,
16
+ scale_estimator: LocationOrScaleEstimator = median_abs_deviation,
17
+ n_iterations: int = 2,
18
+ reweighting: bool = False,
19
+ reweighting_beta: float = 0.9
20
+ ):
21
+ """Implementation of the Orthogonalized Gnanadesikan-Kettenring estimator for location
22
+ dispersion proposed in Maronna, R. A., & Zamar, R. H. (2002)
23
+
24
+ Args:
25
+ store_precision (boolean, optional): whether to store the precision matrix
26
+ assume_centered (boolean, optional): whether the data is already centered
27
+ location_estimator (LocationOrScaleEstimator, optional): function to estimate the
28
+ location of the data, should accept an array like input as first value and a named
29
+ argument axis
30
+ scale_estimator (LocationOrScaleEstimator, optional): function to estimate the scale
31
+ of the data, should accept an array like input as first value and a named argument
32
+ axis
33
+ n_iterations (int, optional): number of iteration for orthogonalization step
34
+ reweighting (boolean, optional): whether to apply reweighting at the end
35
+ (i.e. calculating regular location and covariance after filtering outliers based on
36
+ Mahalanobis distance using OGK estimates)
37
+ reweighting_beta (float, optional): quantile of chi2 distribution to use as cutoff for
38
+ reweighting
39
+
40
+ References:
41
+ Maronna, R. A., & Zamar, R. H. (2002).
42
+ Robust Estimates of Location and Dispersion for High-Dimensional Datasets.
43
+ Technometrics, 44(4), 307–317. http://www.jstor.org/stable/1271538
44
+
45
+ """
46
+ super().__init__(store_precision=store_precision, assume_centered=assume_centered)
47
+ self.location_estimator = location_estimator
48
+ self.scale_estimator = scale_estimator
49
+ self.n_iterations = n_iterations
50
+ self.reweighting = reweighting
51
+ self.reweighting_beta = reweighting_beta
52
+
53
+ def calculate_covariance(self, X) -> np.ndarray:
54
+ """Calculate location and covariance with the algorithm described in Maronna & Zamar (2002).
55
+ Covariance is returned, location is overwritten.
56
+ """
57
+ p = X.shape[1]
58
+ Z = np.copy(X)
59
+ DE = []
60
+ for _ in range(self.n_iterations):
61
+ s = np.array(self.scale_estimator(Z, axis=0))
62
+ D = np.diag(s)
63
+ Dinv = np.diag(1.0 / s)
64
+ Y = Z @ Dinv # (n x p)
65
+ U = np.ones(shape=(p, p))
66
+ # Loop over pairs of variables, lower triangle suffises as U is symmetric
67
+ for i in range(p):
68
+ for j in range(i):
69
+ scale_sum = self.scale_estimator(Y[:, i] + Y[:, j])
70
+ scale_diff = self.scale_estimator(Y[:, i] - Y[:, j])
71
+ cor = (scale_sum**2 - scale_diff**2) / (scale_sum**2 + scale_diff**2)
72
+ U[i, j] = U[j, i] = cor
73
+ _, E = np.linalg.eigh(U) # (p x p)
74
+ E = E[:, ::-1]
75
+ Z = Y @ E # (n x p)
76
+ DE.append(D @ E)
77
+ cov_X = np.diag(np.power(self.scale_estimator(Z, axis=0), 2)) # (p x p)
78
+ mu_X = self.location_estimator(Z, axis=0) # (p, )
79
+
80
+ for mat in reversed(DE):
81
+ mu_X = mat @ mu_X.reshape(-1, 1)
82
+ cov_X = mat @ cov_X @ mat.T
83
+
84
+ mu_X = mu_X.flatten()
85
+ if self.reweighting:
86
+ mahalanobis = mahalanobis_distance(X, location=mu_X, covariance=cov_X)
87
+ cutoff = np.sqrt(chi2.ppf(self.reweighting_beta, p) / chi2.ppf(0.5, p)) * np.median(
88
+ mahalanobis
89
+ ) # mahalanobis is the sqrt distance, so we need to take the sqrt of the chi2 quantiles
90
+ mask = mahalanobis < cutoff
91
+ cov_X = np.cov(X[mask], rowvar=False)
92
+ mu_X = np.mean(X[mask], axis=0)
93
+ self.location_ = mu_X.flatten()
94
+
95
+ return cov_X
@@ -0,0 +1,31 @@
1
+ import numpy as np
2
+
3
+
4
+ def truncated_covariance(cov: np.ndarray, min_eigenvalue: float) -> np.ndarray:
5
+ """Modifies the covariance such that all eigenvalues are at least as large as the
6
+ given minimum value.
7
+
8
+ Parameters:
9
+ - cov: An np.ndarray representing the current covariance matrix.
10
+ - min_eigenvalue: A float indicating what the minimal eigenvalue allowed eigenvalue.
11
+
12
+ Returns:
13
+ - a new covariance estimate.
14
+ """
15
+ eigvals, eigvecs = np.linalg.eigh(0.5 * (cov + cov.T))
16
+ eigvals_idx = np.argsort(eigvals)[::-1]
17
+ eigvals[eigvals < min_eigenvalue] = min_eigenvalue
18
+ return eigvecs[:, eigvals_idx] @ np.diag(eigvals[eigvals_idx]) @ eigvecs[:, eigvals_idx].T
19
+
20
+
21
+ def covariance_to_correlation(cov: np.ndarray) -> np.ndarray:
22
+ """Converts a covariance matrix to a correlation matrix
23
+
24
+ Parameters:
25
+ - cov: An np.ndarray representing the current covariance matrix.
26
+
27
+ Returns:
28
+ - the estimate for the corresponding correlation matrix.
29
+ """
30
+ stds = np.sqrt(np.diag(cov))
31
+ return cov / np.outer(stds, stds)
@@ -0,0 +1,38 @@
1
+ import numpy as np
2
+
3
+ from robpy.utils.general import inverse_submatrix
4
+
5
+
6
+ def objective_function(
7
+ X: np.ndarray, W: np.ndarray, location: np.array, cov: np.ndarray, cov_inv: np.ndarray
8
+ ) -> float:
9
+ """Calculates the value of the objective function in equation (8) of the CellMCD paper without
10
+ the penalty for a certain X, W, location, covariance and the inverse covariance
11
+ [Raymaekers and Rousseeuw, The Cellwise Minimum Covariance Determinant Estimator, 2023,
12
+ Journal of the American Statistical Association]
13
+
14
+ Arguments:
15
+ - X (np.ndarray): the data
16
+ - W (np.ndarray): the matrix W describing which cells are currently flagged
17
+ - location (np.array): the current location estimate
18
+ - cov (np.ndarray): the current covariance estimate
19
+ - cov_inv (np.ndarray): the inverse of the current covariance estimate
20
+ """
21
+
22
+ objective = 0
23
+ unique_rows = np.unique(W, axis=0)
24
+ for w in unique_rows:
25
+ row_idx_w = np.where(np.all(W == w, axis=1))[0]
26
+ w_ones = np.where(w)[0]
27
+
28
+ subset_location = np.array(location)[w_ones]
29
+ subset_cov = cov[np.ix_(w_ones, w_ones)]
30
+ subset_cov_inv = inverse_submatrix(cov, cov_inv, w_ones)
31
+
32
+ subset_X = X[row_idx_w][:, w_ones] - subset_location
33
+ partial_MD = np.sum(subset_X.dot(subset_cov_inv) * subset_X, axis=1)
34
+ objective = objective + np.sum(
35
+ partial_MD + np.linalg.slogdet(subset_cov)[1] + np.log(2 * np.pi) * len(w_ones)
36
+ )
37
+
38
+ return objective
@@ -0,0 +1,96 @@
1
+ import numpy as np
2
+
3
+ from matplotlib.axes import Axes
4
+ from scipy.stats import chi2
5
+ from robpy.utils.distance import mahalanobis_distance
6
+ from robpy.univariate.onestep_m import OneStepWrappingEstimator
7
+
8
+
9
+ def annote_outliers(
10
+ ax: Axes,
11
+ row_names,
12
+ x: np.array,
13
+ y: np.array,
14
+ h_thresholds: tuple[float, float],
15
+ v_thresholds: tuple[float, float] = None,
16
+ ):
17
+ """Label outlying points (x,y) in a plot with their case name if they exceed a vertical
18
+ or hoizontal threshold.
19
+
20
+ Arguments:
21
+ - ax (Axes): the plot
22
+ - row_names (list of strings): list containing the names of the cases/rows
23
+ - x (np.array): x-coordinates of the points
24
+ - y (np.array): y-coordinates of the points
25
+ - h_thresholds (list[float, float]): horizontal thresholds (lower and upper)
26
+ - v_thresholds (list[float, float], optional): vertical thresholds (left and right)"""
27
+
28
+ for i, (xi, yi) in enumerate(zip(x, y)):
29
+ h_outlier = (yi < h_thresholds[0]) or (yi > h_thresholds[1])
30
+ v_outlier = (v_thresholds is not None) and (
31
+ (xi < v_thresholds[0]) or (xi > v_thresholds[1])
32
+ )
33
+ if h_outlier or v_outlier:
34
+ ax.text(xi, yi, row_names[i], fontsize=9, ha="center", va="bottom")
35
+
36
+
37
+ def annote_outliers_ellipse(
38
+ ax: Axes,
39
+ row_names,
40
+ location: np.array,
41
+ covariance: np.ndarray,
42
+ variable: int,
43
+ second_variable: int,
44
+ x: np.array,
45
+ y: np.array,
46
+ quantile: float = 0.99,
47
+ ):
48
+ """Label outlying points (x,y) with their case name if they are outside the tolerance ellipse
49
+
50
+ - ax (Axes): the plot
51
+ - row_names (list of strings): list containing the names of the cases/rows
52
+ - location (np.array): location estimate of the data
53
+ - covariance (np.ndarray): covariance estimate of the data
54
+ - variable (integer): index of the first variable
55
+ - second variable (integer): index of the second variable
56
+ - x (np.array): x-coordinates of the points
57
+ - y (np.array): y-coordinates of the points
58
+ - quantile (float, optional): Cutoff value to flag cells.
59
+ """
60
+ mask = mahalanobis_distance(
61
+ np.column_stack((x, y)),
62
+ location[[variable, second_variable]],
63
+ covariance=covariance[np.ix_([variable, second_variable], [variable, second_variable])],
64
+ ) > np.sqrt(chi2.ppf(quantile, 2))
65
+ for xi, yi, name in zip(x[mask], y[mask], [row_names[i] for i in np.where(mask)[0]]):
66
+ ax.text(xi, yi, name, fontsize=9, ha="center", va="bottom")
67
+
68
+
69
+ def draw_ellipse(cov: np.ndarray, center: np.array, ax: Axes, quantile: float):
70
+ """Get the ellipse for bivariate data given the covariance matrix (for the shape) and the
71
+ location (for the center)."""
72
+
73
+ eigenvalues, eigenvectors = np.linalg.eigh(cov)
74
+ shape = eigenvectors @ np.diag(np.sqrt(eigenvalues)) @ eigenvectors.T # orthogonalize
75
+ angles = np.linspace(0, 2 * np.pi, 200 + 1)
76
+ xy = np.column_stack((np.cos(angles), np.sin(angles)))
77
+ radius = np.sqrt(chi2.ppf(quantile, 2))
78
+ ellipse = radius * xy @ shape + center
79
+ ax.plot(ellipse[:, 0], ellipse[:, 1], linewidth=3, color="darkgray")
80
+
81
+
82
+ def get_thresholds(cutoff: float, x: np.array) -> tuple[float, float]:
83
+ scaler = OneStepWrappingEstimator().fit(x, ignore_nan=True)
84
+ return (scaler.location - cutoff * scaler.scale, scaler.location + cutoff * scaler.scale)
85
+
86
+
87
+ def draw_threshold_lines(
88
+ ax: Axes,
89
+ h_thresholds: list[float, float],
90
+ v_thresholds: list[float, float] | None,
91
+ ):
92
+ for h in h_thresholds:
93
+ ax.axhline(h, color="grey", linestyle="--")
94
+ if v_thresholds is not None:
95
+ for v in v_thresholds:
96
+ ax.axvline(v, color="grey", linestyle="--")
@@ -0,0 +1,72 @@
1
+ import numpy as np
2
+
3
+ from robpy.preprocessing.utils import wrapping_transformation
4
+ from robpy.covariance.base import RobustCovarianceEstimator
5
+
6
+
7
+ class WrappingCovarianceEstimator(RobustCovarianceEstimator):
8
+ """Covariance estimator based on the wrapping function proposed in
9
+ Jakob Raymaekers & Peter J. Rousseeuw (2021)
10
+
11
+ The wrapping transformation is defined as follows:
12
+
13
+ .. math::
14
+
15
+ \\Psi_{b, c}(z) =
16
+ \\begin{cases}
17
+ z & if \\ 0 \\leq |z| < b \\\\
18
+ q_1 \\tanh\\left(q_2 (c - |z|)\\right) \\mathrm{sign}(z) & if \\ b \\leq |z| \\leq c \\\\
19
+ 0 & if \\ c < |z|
20
+ \\end{cases}
21
+
22
+ Data is first scaled using median and MAD before applying the transformation.
23
+
24
+ The (standard) covariance is subsequently estimated on the rescaled data
25
+ Cov(X) = Cov(Median(X) + MAD(X) * phi(X - Median(X) / MAD(X)))
26
+
27
+ References:
28
+ - Jakob Raymaekers & Peter J. Rousseeuw (2021)
29
+ Fast Robust Correlation for High-Dimensional Data,
30
+ Technometrics, 63:2, 184-198, DOI: 10.1080/00401706.2019.1677270
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ b: float = 1.5,
36
+ c: float = 4.0,
37
+ q1: float = 1.540793,
38
+ q2: float = 0.8622731,
39
+ rescale: bool = True,
40
+ store_precision: bool = True,
41
+ assume_centered: bool = False,
42
+ ):
43
+ """
44
+ Args:
45
+ X: data to be transformed, must have shape (N, D)
46
+ b: lower cutoff
47
+ c: upper cutoff
48
+ q1, q2: transformation parameters (see formula)
49
+ rescale: whether to rescale the wrapped data so the robust location and scale
50
+ of the transformed data are the same as the original data
51
+ """
52
+ super().__init__(store_precision=store_precision, assume_centered=assume_centered)
53
+ self.b = b
54
+ self.c = c
55
+ self.q1 = q1
56
+ self.q2 = q2
57
+ self.rescale = rescale
58
+
59
+ def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
60
+ """Calculate the covariance matrix of the data X after applying the wrapping transformation
61
+
62
+ Args:
63
+ X: data to calculate the covariance matrix of, must have shape (N, D)
64
+
65
+ Returns:
66
+ robust covariance matrix of X
67
+ """
68
+ X_transformed = wrapping_transformation(
69
+ X, b=self.b, c=self.c, q1=self.q1, q2=self.q2, rescale=self.rescale
70
+ )
71
+ self.correlation_ = np.corrcoef(X_transformed, rowvar=False)
72
+ return np.cov(X_transformed, rowvar=False)
@@ -0,0 +1,4 @@
1
+ """ Module that contains convenience functions for loading commonly used datasets.
2
+ """
3
+
4
+ from robpy.datasets.base import load_telephone, load_stars, load_animals, load_topgear, load_glass