robpy 0.1.1__tar.gz → 0.2.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 (62) hide show
  1. {robpy-0.1.1 → robpy-0.2.0}/PKG-INFO +1 -1
  2. {robpy-0.1.1 → robpy-0.2.0}/pyproject.toml +1 -1
  3. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/cellmcd.py +121 -124
  4. robpy-0.2.0/robpy/covariance/initial_ddcw.py +141 -0
  5. robpy-0.2.0/robpy/outliers/ddc.py +647 -0
  6. {robpy-0.1.1 → robpy-0.2.0}/robpy/preprocessing/transfo.py +242 -142
  7. {robpy-0.1.1 → robpy-0.2.0}/robpy/regression/__init__.py +1 -0
  8. robpy-0.2.0/robpy/regression/cell_lts.py +670 -0
  9. robpy-0.2.0/robpy/univariate/_cellwise.py +338 -0
  10. robpy-0.2.0/robpy/univariate/onestep_m.py +166 -0
  11. robpy-0.1.1/robpy/covariance/initial_ddcw.py +0 -138
  12. robpy-0.1.1/robpy/outliers/ddc.py +0 -431
  13. robpy-0.1.1/robpy/univariate/onestep_m.py +0 -137
  14. {robpy-0.1.1 → robpy-0.2.0}/LICENSE +0 -0
  15. {robpy-0.1.1 → robpy-0.2.0}/README.rst +0 -0
  16. {robpy-0.1.1 → robpy-0.2.0}/robpy/__init__.py +0 -0
  17. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/__init__.py +0 -0
  18. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/base.py +0 -0
  19. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/kendall.py +0 -0
  20. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/mcd.py +0 -0
  21. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/ogk.py +0 -0
  22. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/utils/alter_covariance.py +0 -0
  23. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/utils/cellmcd_utils.py +0 -0
  24. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/utils/cellmcd_visualization_utils.py +0 -0
  25. {robpy-0.1.1 → robpy-0.2.0}/robpy/covariance/wrapping.py +0 -0
  26. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/__init__.py +0 -0
  27. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/base.py +0 -0
  28. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/data/animals.csv +0 -0
  29. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/data/glass.csv +0 -0
  30. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/data/stars.csv +0 -0
  31. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/data/telephone.csv +0 -0
  32. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/data/topgear.csv +0 -0
  33. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/descr/animals.rst +0 -0
  34. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/descr/glass.rst +0 -0
  35. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/descr/stars.rst +0 -0
  36. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/descr/telephone.rst +0 -0
  37. {robpy-0.1.1 → robpy-0.2.0}/robpy/datasets/descr/topgear.rst +0 -0
  38. {robpy-0.1.1 → robpy-0.2.0}/robpy/outliers/__init__.py +0 -0
  39. {robpy-0.1.1 → robpy-0.2.0}/robpy/pca/__init__.py +0 -0
  40. {robpy-0.1.1 → robpy-0.2.0}/robpy/pca/base.py +0 -0
  41. {robpy-0.1.1 → robpy-0.2.0}/robpy/pca/robpca.py +0 -0
  42. {robpy-0.1.1 → robpy-0.2.0}/robpy/pca/spca.py +0 -0
  43. {robpy-0.1.1 → robpy-0.2.0}/robpy/preprocessing/__init__.py +0 -0
  44. {robpy-0.1.1 → robpy-0.2.0}/robpy/preprocessing/data_cleaner.py +0 -0
  45. {robpy-0.1.1 → robpy-0.2.0}/robpy/preprocessing/scaling.py +0 -0
  46. {robpy-0.1.1 → robpy-0.2.0}/robpy/preprocessing/utils.py +0 -0
  47. {robpy-0.1.1 → robpy-0.2.0}/robpy/regression/base.py +0 -0
  48. {robpy-0.1.1 → robpy-0.2.0}/robpy/regression/lts.py +0 -0
  49. {robpy-0.1.1 → robpy-0.2.0}/robpy/regression/mm.py +0 -0
  50. {robpy-0.1.1 → robpy-0.2.0}/robpy/regression/s.py +0 -0
  51. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/__init__.py +0 -0
  52. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/adjusted_boxplot.py +0 -0
  53. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/base.py +0 -0
  54. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/mcd.py +0 -0
  55. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/qn.py +0 -0
  56. {robpy-0.1.1 → robpy-0.2.0}/robpy/univariate/tau.py +0 -0
  57. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/distance.py +0 -0
  58. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/general.py +0 -0
  59. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/logging.py +0 -0
  60. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/median.py +0 -0
  61. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/outlyingness.py +0 -0
  62. {robpy-0.1.1 → robpy-0.2.0}/robpy/utils/rho.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: robpy
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary:
5
5
  License-File: LICENSE
6
6
  Author: Thomas Servotte
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "robpy"
3
- version = "0.1.1" # versioning is done by poetry-dynamic-versioning
3
+ version = "0.2.0" # versioning is done by poetry-dynamic-versioning
4
4
  description = ""
5
5
  authors = ["Thomas Servotte <servottethomas@gmail.com>", "Sarah Leyder <sarah.leyder@uantwerpen.be>"]
6
6
  readme = "README.rst"
@@ -7,10 +7,9 @@ import matplotlib.pyplot as plt
7
7
 
8
8
  from scipy.stats import chi2, median_abs_deviation
9
9
  from typing import Literal, Optional
10
- from robpy.covariance.utils.alter_covariance import truncated_covariance
10
+ from robpy.covariance.utils.alter_covariance import covariance_to_correlation
11
11
  from robpy.covariance.base import RobustCovariance
12
12
  from robpy.utils.logging import get_logger
13
- from robpy.covariance.utils.cellmcd_utils import objective_function
14
13
  from robpy.utils.general import inverse_submatrix
15
14
  from robpy.covariance.utils.cellmcd_visualization_utils import (
16
15
  annote_outliers,
@@ -25,6 +24,15 @@ from robpy.covariance.initial_ddcw import InitialDDCW
25
24
  from sklearn.exceptions import NotFittedError
26
25
 
27
26
 
27
+ def _truncate_eigenvalues_svd(sigma: np.ndarray, min_eigenvalue: float):
28
+ """Symmetrize sigma and raise its singular values to at least min_eigenvalue; return the
29
+ result and its inverse (``truncEig`` in the C++ code of cellWise)."""
30
+ sigma = 0.5 * (sigma + sigma.T)
31
+ U, s, _ = np.linalg.svd(sigma)
32
+ s = np.maximum(s, min_eigenvalue)
33
+ return (U * s) @ U.T, (U / s) @ U.T
34
+
35
+
28
36
  class CellMCD(RobustCovariance):
29
37
  def __init__(
30
38
  self,
@@ -34,16 +42,21 @@ class CellMCD(RobustCovariance):
34
42
  crit: float = 1e-4,
35
43
  max_c_steps: int = 100,
36
44
  min_eigenvalue: float = 1e-4,
45
+ fixed_center: bool = False,
37
46
  verbosity: int = logging.WARNING,
38
47
  ):
39
48
  """
40
49
  Cell MCD estimator based on the algorithm proposed in Raymaekers, J., & Rousseeuw, P. J.
41
- (2024).
50
+ (2024), following the function ``cellMCD`` of the R package cellWise (version 2.5.7):
51
+ the data are standardized with ``estLocScale(type = "wrap")``, the initial estimate is
52
+ ``DDCWcov`` (see :class:`InitialDDCW`), and C-steps are taken until the covariance matrix
53
+ of the standardized data changes by less than ``crit``. The data checks of
54
+ ``cellWise::checkDataSet`` are not applied.
42
55
 
43
56
  Args:
44
57
  alpha (float, optional):
45
- Percentage indicating how many cells must remain unflagged in each column.
46
- Must lie within 0.5 to 1.0. Defaults to 0.75.
58
+ Percentage indicating how many cells must remain unflagged in each column
59
+ (h = ceil(alpha * n)). Must lie within 0.5 to 1.0. Defaults to 0.75.
47
60
  quantile (float, optional):
48
61
  Cutoff value to flag cells.
49
62
  Defaults to 0.99.
@@ -58,10 +71,18 @@ class CellMCD(RobustCovariance):
58
71
  Lower bound on the minimum eigenvalue of the covariance estimator
59
72
  on the standardized data. Should be at least 1e-6.
60
73
  Defaults to 1e-4.
74
+ fixed_center (bool, optional):
75
+ If True, the center is fixed at 0 and only the covariance (around 0) is
76
+ estimated (``fixedCenter`` in cellWise). This is used for symmetrized data, e.g.
77
+ pairwise differences of observations. Defaults to False.
61
78
 
62
79
  Attributes (after fit):
63
- location_ (np.ndarray): Robust location estimate.
64
- covariance_ (np.ndarray): Robust covariance estimate.
80
+ location_ (np.ndarray): Robust location estimate (0 with ``fixed_center``).
81
+ covariance_ (np.ndarray): Robust covariance estimate, as ``S`` in cellWise: the
82
+ correlation matrix of the cellMCD estimate, rescaled with the robust scales of
83
+ the initial standardization.
84
+ raw_covariance_ (np.ndarray): The cellMCD covariance estimate itself, as ``raw.S`` in
85
+ cellWise.
65
86
  cellwise_outliers_ (np.ndarray): Boolean array of shape (n_samples, n_features), True
66
87
  for a cell of the training data that is flagged as outlying. Missing cells are
67
88
  False.
@@ -69,7 +90,10 @@ class CellMCD(RobustCovariance):
69
90
  flagged or missing cell (so W == 0 also includes the missing cells).
70
91
  predictions, conditional_stds, residuals, X_imputed (np.ndarray): Per-cell
71
92
  predictions given the unflagged cells of the same row, their conditional standard
72
- deviations, the standardized residuals and the imputed training data.
93
+ deviations, the standardized residuals (observed value minus prediction, divided
94
+ by the conditional standard deviation) and the imputed training data, as
95
+ ``preds``, ``csds``, ``Zres`` and ``Ximp`` in cellWise.
96
+ n_c_steps_ (int): Number of C-steps taken.
73
97
 
74
98
  Use `predict` and `impute` to flag and impute cells of new data.
75
99
 
@@ -85,48 +109,45 @@ class CellMCD(RobustCovariance):
85
109
  self.crit = crit
86
110
  self.max_c_steps = max_c_steps
87
111
  self.min_eigenvalue = min_eigenvalue
112
+ self.fixed_center = fixed_center
88
113
  self.logger = get_logger("CellMCD", level=verbosity)
89
114
  self.verbosity = verbosity
90
115
 
91
116
  def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
92
- # check that alpha creates a h-subset larger than [n/2]+1
93
- n = X.shape[0]
94
- if 0.5 <= self.alpha <= 1:
95
- if self.alpha < (int(n / 2) + 1.0) / n:
96
- self.logger.warning(
97
- f"h = alpha*n is too small and therefore set to [n/2] + 1"
98
- f" ({(int(n / 2) + 1.0) / n})."
99
- )
100
- self.alpha = np.max([self.alpha, (int(n / 2) + 1.0) / n])
101
- else:
117
+ if not 0.5 <= self.alpha <= 1:
102
118
  raise ValueError(f"alpha must a float between 0.5 and 1, but received {self.alpha}.")
119
+ X = np.array(X, dtype=float)
120
+ X[np.isinf(X)] = np.nan
103
121
 
104
- # Step 0: robustly standardize the data
122
+ # Step 0: robustly standardize the data (around 0 with a fixed center)
105
123
  mads = median_abs_deviation(X, nan_policy="omit", axis=0)
106
124
  if np.min(mads) < 1e-8:
107
125
  raise ValueError("At least one variable has an almost zero median absolute deviation.")
108
- scaler = RobustScaler(scale_estimator=OneStepWrapping())
126
+ scaler = RobustScaler(scale_estimator=OneStepWrapping(center=not self.fixed_center))
109
127
  scaler.fit(X, ignore_nan=True)
110
128
  X_scaled = scaler.transform(X)
111
129
 
112
130
  # Step 1: Check that there aren't too many marginal outliers and too many nan's.
113
- # Check that there are enough observations compared to variables.
131
+ # Warn if there are few observations compared to variables.
114
132
  self._check_data(X_scaled)
115
133
 
116
134
  # Step 2: calculate the initial estimates
117
- ddcw = InitialDDCW(alpha=self.alpha, min_eigenvalue=self.min_eigenvalue)
135
+ ddcw = InitialDDCW(
136
+ alpha=self.alpha, min_eigenvalue=self.min_eigenvalue, fixed_center=self.fixed_center
137
+ )
118
138
  ddcw.fit(X_scaled)
119
- initial_location = ddcw.location_
139
+ initial_location = np.zeros(X.shape[1]) if self.fixed_center else ddcw.location_
120
140
  initial_cov = ddcw.covariance_
121
- initial_cov_inv = ddcw.precision_
122
141
  X_scaled[np.abs(X_scaled) > 3] = np.nan
123
142
  q = (
124
- chi2.ppf(self.quantile, 1) - np.log(np.diag(initial_cov_inv)) + np.log(2 * np.pi)
143
+ chi2.ppf(self.quantile, 1)
144
+ - np.log(np.diag(np.linalg.inv(initial_cov)))
145
+ + np.log(2 * np.pi)
125
146
  ) # equation (21)
126
147
 
127
148
  # Step 3: MCD iterations (we work with X_scaled)
128
149
  location, cov, cov_inv, W = self._C_steps_until_convergence(
129
- X_scaled, initial_location, initial_cov, initial_cov_inv, q
150
+ X_scaled, initial_location, initial_cov, q
130
151
  )
131
152
  # Step 4: make prediction
132
153
  predictions, conditional_variances = self._make_predictions(
@@ -134,17 +155,15 @@ class CellMCD(RobustCovariance):
134
155
  )
135
156
 
136
157
  # Step 5: transform back
158
+ scales = scaler.scales_
137
159
  location_scaled, cov_scaled = location, cov
138
- cov = np.diag(scaler.scales_) @ cov @ np.diag(scaler.scales_)
139
- location = scaler.locations_ + location * scaler.scales_
140
- predictions = scaler.locations_ + predictions * scaler.scales_
141
- conditional_stds = np.sqrt(conditional_variances) * scaler.scales_
160
+ raw_cov = np.diag(scales) @ cov @ np.diag(scales)
161
+ location = scaler.locations_ + location * scales
162
+ predictions = scaler.locations_ + predictions * scales
163
+ conditional_stds = np.sqrt(conditional_variances) * scales
142
164
  X_imputed = X.copy()
143
165
  X_imputed[W == 0] = predictions[W == 0]
144
166
  residuals = (X - predictions) / conditional_stds
145
- scaler_residuals = RobustScaler(scale_estimator=OneStepWrapping())
146
- scaler_residuals.fit(residuals, ignore_nan=True)
147
- residuals = residuals / scaler_residuals.scales_
148
167
 
149
168
  # state needed to flag and impute new data (all in the robustly scaled space)
150
169
  self._scaler = scaler
@@ -161,10 +180,11 @@ class CellMCD(RobustCovariance):
161
180
  self.conditional_stds = conditional_stds
162
181
  self.X_imputed = X_imputed
163
182
  self.residuals = residuals
164
- self.covariance_ = cov
183
+ self.raw_covariance_ = raw_cov
165
184
  self.X = X
166
185
 
167
- return cov
186
+ # as ``S`` in cellWise: correlation matrix of the estimate, rescaled with the scales
187
+ return covariance_to_correlation(cov) * np.outer(scales, scales)
168
188
 
169
189
  def predict(self, X: np.ndarray | pd.DataFrame) -> np.ndarray:
170
190
  """Flag the cellwise outliers in (new) data using the fitted location and covariance.
@@ -264,7 +284,7 @@ class CellMCD(RobustCovariance):
264
284
  for _ in range(self.max_c_steps):
265
285
  changed = False
266
286
  for j in self._column_order:
267
- delta = self._calculate_delta(X_scaled, W, sigma, sigma_inv, mu, j)
287
+ delta = CellMCD._calculate_delta(X_scaled, W, sigma, sigma_inv, mu, j)
268
288
  w_new = (delta <= self._q[j]).astype(float)
269
289
  if np.any(w_new != W[:, j]):
270
290
  changed = True
@@ -422,8 +442,9 @@ class CellMCD(RobustCovariance):
422
442
 
423
443
  return fig
424
444
 
445
+ @staticmethod
425
446
  def _make_predictions(
426
- self, X: np.ndarray, sigma: np.ndarray, sigma_inv: np.ndarray, mu: np.ndarray, W: np.ndarray
447
+ X: np.ndarray, sigma: np.ndarray, sigma_inv: np.ndarray, mu: np.ndarray, W: np.ndarray
427
448
  ) -> tuple[np.ndarray, np.ndarray]:
428
449
  """Calculate the predictions of the cells given the other clean cells in the same row."""
429
450
 
@@ -441,7 +462,7 @@ class CellMCD(RobustCovariance):
441
462
  # there are both observed and missing values
442
463
 
443
464
  # predict the missing values
444
- predictions, conditional_variances = self._predict_missing_values(
465
+ predictions, conditional_variances = CellMCD._predict_missing_values(
445
466
  X,
446
467
  predictions,
447
468
  conditional_variances,
@@ -454,7 +475,7 @@ class CellMCD(RobustCovariance):
454
475
  )
455
476
 
456
477
  # predict the observed values
457
- predictions, conditional_variances = self._predict_observed_values(
478
+ predictions, conditional_variances = CellMCD._predict_observed_values(
458
479
  X,
459
480
  predictions,
460
481
  conditional_variances,
@@ -466,12 +487,12 @@ class CellMCD(RobustCovariance):
466
487
  )
467
488
 
468
489
  elif len(missing_col_idx) == 0: # no missings in the w-pattern
469
- predictions, conditional_variances = self._predict_no_missing(
490
+ predictions, conditional_variances = CellMCD._predict_no_missing(
470
491
  X, predictions, conditional_variances, row_idx_w, mu, sigma, sigma_inv
471
492
  )
472
493
 
473
494
  else: # all missings in the w-pattern
474
- predictions, conditional_variances = self._predict_all_missing(
495
+ predictions, conditional_variances = CellMCD._predict_all_missing(
475
496
  predictions, conditional_variances, row_idx_w, mu, sigma
476
497
  )
477
498
 
@@ -482,53 +503,32 @@ class CellMCD(RobustCovariance):
482
503
  X_scaled: np.ndarray,
483
504
  initial_location: np.array,
484
505
  initial_cov: np.ndarray,
485
- initial_cov_inv: np.ndarray,
486
506
  q: np.ndarray,
487
507
  ):
488
- """Perform C-steps (update W, location and covariance) until convergence.
508
+ """Perform C-steps (update W, location and covariance) until the covariance matrix
509
+ changes by less than crit (``iterMCD_cpp`` in cellWise). The covariance matrix is
510
+ symmetrized and its eigenvalues are raised to at least min_eigenvalue after each step.
489
511
 
490
512
  Arguments:
491
513
  - X_scaled (np.ndarray): scaled data
492
514
  - initial_location (np.array): initial location estimate
493
515
  - initial_cov (np.ndarray): initial covariance estimate
494
- - initial_cov_inv (np.ndarray): inverse of the initial covariance estimate
495
516
  - q (np.ndarray): per-column penalties for flagging a cell, equation (21)
496
517
  """
497
518
  n, p = X_scaled.shape
498
-
499
- h = round(self.alpha * n)
500
- initial_W = np.ones([n, p])
501
- initial_W[np.isnan(X_scaled)] = 0
502
- objective_values = np.full(self.max_c_steps + 1, np.nan)
519
+ h = int(np.ceil(self.alpha * n))
520
+ W = np.where(np.isnan(X_scaled), 0.0, 1.0)
521
+ location = np.array(initial_location, dtype=float)
522
+ cov, cov_inv = _truncate_eigenvalues_svd(initial_cov, self.min_eigenvalue)
523
+ convergence_criterion = self.crit + 1.0
503
524
  step = 0
504
- penalty = np.sum(q * np.sum(1 - initial_W, axis=0))
505
- objective_values[step] = (
506
- objective_function(X_scaled, initial_W, initial_location, initial_cov, initial_cov_inv)
507
- + penalty
508
- )
509
- convergence_criteria = 1
510
- W_old = initial_W
511
- location_old = initial_location
512
- cov_old = initial_cov
513
- cov_inv_old = initial_cov_inv
514
- while convergence_criteria > self.crit and step < self.max_c_steps:
515
- W, location, cov = self._C_step(
516
- X_scaled, W_old, location_old, cov_old, cov_inv_old, q, h
517
- )
518
- convergence_criteria = np.max(np.abs(cov - cov_old))
519
- cov = truncated_covariance(cov, self.min_eigenvalue)
520
- cov_inv = np.linalg.inv(cov)
521
- penalty = np.sum(q * np.sum(1 - W, axis=0))
522
- objective_value = objective_function(X_scaled, W, location, cov, cov_inv) + penalty
523
- if objective_value > objective_values[step]:
524
- return location_old, cov_old, cov_inv_old, W_old
525
- step = step + 1
526
- objective_values[step] = objective_value
527
- W_old = W
528
- location_old = location
525
+ while convergence_criterion > self.crit and step < self.max_c_steps:
529
526
  cov_old = cov
530
- cov_inv_old = cov_inv
531
-
527
+ W, location, cov = self._C_step(X_scaled, W, location, cov, cov_inv, q, h)
528
+ cov, cov_inv = _truncate_eigenvalues_svd(cov, self.min_eigenvalue)
529
+ convergence_criterion = np.max(np.abs(cov - cov_old))
530
+ step += 1
531
+ self.n_c_steps_ = step
532
532
  return location, cov, cov_inv, W
533
533
 
534
534
  def _C_step(
@@ -546,39 +546,40 @@ class CellMCD(RobustCovariance):
546
546
  # first update W
547
547
  W = self._update_W(X, W, mu, sigma, sigma_inv, q, h)
548
548
 
549
- # next: update mu & sigma
549
+ # next: one EM step for mu & sigma (mu stays fixed with a fixed center)
550
550
  X_imputed = np.copy(X)
551
551
  bias = np.zeros([p, p])
552
- for i in range(n):
553
- missing_col_idx = np.where(W[i, :] == 0)[0]
554
- observed_col_idx = np.where(W[i, :] == 1)[0]
555
- if len(missing_col_idx) > 0:
556
- if len(missing_col_idx) == p: # if all are missing
557
- X_imputed[i, :] = mu
558
- bias = bias + sigma
559
- else:
560
- sigma_inv_mis_inv = np.linalg.inv(
561
- sigma_inv[np.ix_(missing_col_idx, missing_col_idx)]
562
- )
563
- X_imputed[np.ix_([i], missing_col_idx)] = (
564
- mu[missing_col_idx]
565
- - (
566
- sigma_inv_mis_inv
567
- @ sigma_inv[np.ix_(missing_col_idx, observed_col_idx)]
568
- @ (X[np.ix_([i], observed_col_idx)] - mu[observed_col_idx]).T
569
- ).flatten()
570
- )
571
- bias[np.ix_(missing_col_idx, missing_col_idx)] = (
572
- bias[np.ix_(missing_col_idx, missing_col_idx)] + sigma_inv_mis_inv
573
- )
574
- mu = np.mean(X_imputed, axis=0)
552
+ for w in np.unique(W, axis=0):
553
+ rows = np.flatnonzero(np.all(W == w, axis=1))
554
+ missing = np.flatnonzero(w == 0)
555
+ observed = np.flatnonzero(w == 1)
556
+ if missing.size == 0:
557
+ continue
558
+ if missing.size == p: # all cells of the row are flagged or missing
559
+ X_imputed[rows] = mu
560
+ bias += sigma * rows.size
561
+ continue
562
+ sigma_inv_mis_inv = np.linalg.inv(sigma_inv[np.ix_(missing, missing)])
563
+ bias[np.ix_(missing, missing)] += sigma_inv_mis_inv * rows.size
564
+ X_imputed[np.ix_(rows, missing)] = (
565
+ mu[missing]
566
+ - (
567
+ sigma_inv_mis_inv
568
+ @ sigma_inv[np.ix_(missing, observed)]
569
+ @ (X[np.ix_(rows, observed)] - mu[observed]).T
570
+ ).T
571
+ )
575
572
  bias = bias / n
576
- sigma = np.cov(X_imputed, rowvar=False) * (n - 1) / n + bias
573
+ if self.fixed_center:
574
+ sigma = X_imputed.T @ X_imputed / n + bias
575
+ else:
576
+ mu = np.mean(X_imputed, axis=0)
577
+ sigma = np.cov(X_imputed, rowvar=False, bias=True) + bias
577
578
 
578
579
  return W, mu, sigma
579
580
 
581
+ @staticmethod
580
582
  def _update_W(
581
- self,
582
583
  X: np.ndarray,
583
584
  W: np.ndarray,
584
585
  mu: np.array,
@@ -593,7 +594,7 @@ class CellMCD(RobustCovariance):
593
594
  n = W.shape[0]
594
595
  ordering = np.argsort(np.sum(W, axis=0), kind="stable")
595
596
  for j in ordering:
596
- delta = self._calculate_delta(X, W, sigma, sigma_inv, mu, j)
597
+ delta = CellMCD._calculate_delta(X, W, sigma, sigma_inv, mu, j)
597
598
  good_cells = np.where(delta <= q[j])[0]
598
599
  if len(good_cells) < h: # cannot set less than h cells to 1
599
600
  delta_rank = np.argsort(delta, kind="stable")
@@ -604,8 +605,8 @@ class CellMCD(RobustCovariance):
604
605
 
605
606
  return W
606
607
 
608
+ @staticmethod
607
609
  def _calculate_delta(
608
- self,
609
610
  X: np.ndarray,
610
611
  W: np.ndarray,
611
612
  sigma: np.ndarray,
@@ -657,8 +658,8 @@ class CellMCD(RobustCovariance):
657
658
 
658
659
  return delta
659
660
 
661
+ @staticmethod
660
662
  def _predict_missing_values(
661
- self,
662
663
  X: np.ndarray,
663
664
  predictions: np.ndarray,
664
665
  conditional_variances: np.ndarray,
@@ -691,8 +692,8 @@ class CellMCD(RobustCovariance):
691
692
 
692
693
  return predictions, conditional_variances
693
694
 
695
+ @staticmethod
694
696
  def _predict_observed_values(
695
- self,
696
697
  X: np.ndarray,
697
698
  predictions: np.ndarray,
698
699
  conditional_variances: np.ndarray,
@@ -728,8 +729,8 @@ class CellMCD(RobustCovariance):
728
729
 
729
730
  return predictions, conditional_variances
730
731
 
732
+ @staticmethod
731
733
  def _predict_no_missing(
732
- self,
733
734
  X: np.ndarray,
734
735
  predictions: np.ndarray,
735
736
  conditional_variances: np.ndarray,
@@ -755,8 +756,8 @@ class CellMCD(RobustCovariance):
755
756
 
756
757
  return predictions, conditional_variances
757
758
 
759
+ @staticmethod
758
760
  def _predict_all_missing(
759
- self,
760
761
  predictions: np.ndarray,
761
762
  conditional_variances: np.ndarray,
762
763
  row_idx_w: np.array,
@@ -772,32 +773,28 @@ class CellMCD(RobustCovariance):
772
773
  return predictions, conditional_variances
773
774
 
774
775
  def _check_data(self, X_scaled: np.ndarray):
775
- """Checks that there aren't too many nans or marginal outliers per column. Checks
776
- that there are enough observations.
776
+ """Checks that there aren't too many nans or marginal outliers per column, as cellWise
777
+ does, and warns if there are fewer than 5 cases per variable.
777
778
 
778
779
  Arguments:
779
780
  X_scaled (np.ndarray): robustly standardized data set."""
780
781
 
781
- X = np.copy(X_scaled)
782
-
783
- cutoff = np.sqrt(chi2.ppf(self.quantile, 1))
784
- n_marginal_outliers = np.sum(np.abs(X) > cutoff, axis=0) / X.shape[0]
785
- if np.max(n_marginal_outliers) > 1 - self.alpha:
782
+ cutoff = np.sqrt(chi2.ppf(0.99, 1))
783
+ with np.errstate(invalid="ignore"):
784
+ marginal = np.abs(X_scaled) > cutoff
785
+ if np.max(marginal.sum(axis=0) / X_scaled.shape[0]) > 1 - self.alpha:
786
786
  raise ValueError(
787
787
  f"\nAt least one variable has more than {100 * (1 - self.alpha)}% of "
788
788
  "marginal outliers."
789
789
  )
790
-
791
- X[np.abs(X) > cutoff] = np.nan
792
- n_bad_values = np.isnan(X).sum(axis=0) / X.shape[0]
793
- if np.max(n_bad_values) > 1 - self.alpha:
790
+ if np.max(np.mean(marginal | np.isnan(X_scaled), axis=0)) > 1 - self.alpha:
794
791
  raise ValueError(
795
792
  f"\nAt least one variable has more than {100 * (1 - self.alpha)}% of nan's or "
796
793
  "marginal outliers."
797
794
  )
798
-
799
- if X.shape[0] < 5 * X.shape[1]:
800
- raise ValueError(
801
- "There are not enough observations compared to the number of "
802
- f"variables, n/p = {X.shape[0]/X.shape[1]} < 5."
795
+ if X_scaled.shape[0] < 5 * X_scaled.shape[1]:
796
+ self.logger.warning(
797
+ "There are fewer than 5 cases per dimension in this data set. It is not "
798
+ "recommended to run cellMCD on these data. Consider reducing the number of "
799
+ "variables."
803
800
  )
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy.stats import chi2
8
+
9
+ from robpy.covariance.base import RobustCovariance
10
+ from robpy.covariance.utils.alter_covariance import covariance_to_correlation
11
+ from robpy.outliers.ddc import DDC
12
+ from robpy.univariate import OneStepWrapping
13
+ from robpy.univariate._cellwise import est_loc_scale, wrap
14
+ from robpy.utils.logging import get_logger
15
+
16
+
17
+ def truncate_eigenvalues(cov: np.ndarray, min_eigenvalue: float) -> np.ndarray:
18
+ """Raise the eigenvalues of a symmetric matrix to at least ``min_eigenvalue``, from its
19
+ eigendecomposition (the R function ``truncEig`` of cellWise)."""
20
+ eigvals, eigvecs = np.linalg.eigh(0.5 * (cov + cov.T))
21
+ return eigvecs @ np.diag(np.maximum(eigvals, min_eigenvalue)) @ eigvecs.T
22
+
23
+
24
+ def _wrapped_covariance(Zimp: np.ndarray, min_eigenvalue: float, center: bool) -> np.ndarray:
25
+ """Covariance of the wrapped principal component scores of Zimp, rotated back."""
26
+ eigvals, eigvecs = np.linalg.eigh(np.cov(Zimp, rowvar=False))
27
+ order = np.argsort(eigvals)[::-1]
28
+ eigvals, eigvecs = eigvals[order], eigvecs[:, order]
29
+ eigvecs = eigvecs[:, eigvals >= min_eigenvalue]
30
+ scores = Zimp @ eigvecs
31
+ loc, scale = est_loc_scale(scores, "wrap", center=center)
32
+ scale = np.maximum(scale, min_eigenvalue)
33
+ wrapped = wrap(scores, loc, scale)
34
+ return eigvecs @ np.atleast_2d(np.cov(wrapped, rowvar=False)) @ eigvecs.T
35
+
36
+
37
+ class InitialDDCW(RobustCovariance):
38
+ def __init__(
39
+ self,
40
+ *,
41
+ alpha: float = 0.75,
42
+ min_eigenvalue: float = 1e-4,
43
+ fixed_center: bool = False,
44
+ verbosity: int = logging.WARNING,
45
+ ):
46
+ """
47
+ Calculates the initial robust scatter and location estimates for the CellMCD, described
48
+ in the Supplementary Material to Raymaekers, J., & Rousseeuw, P. J. (2024). This follows
49
+ the function ``DDCWcov`` of the R package cellWise (version 2.5.7):
50
+
51
+ 1. DDC (with ``tolProbCell = 0.9`` and the wrapping standardization) flags cells; in
52
+ columns with more than a fraction 1 - alpha of flagged cells, only the cells with
53
+ the largest absolute standardized residuals are kept flagged. The flagged and missing
54
+ cells are imputed by DDC, and the rows flagged by DDC are left out.
55
+ 2. The covariance of the imputed, standardized data is the back-rotated covariance of
56
+ its wrapped principal component scores (scores standardized around 0).
57
+ 3. Rows that are outlying with respect to that covariance (after clipping the
58
+ standardized data to [-2, 2]) are left out, and step 2 is repeated on the remaining
59
+ rows (now with centered scores). The result is converted to a correlation matrix,
60
+ its eigenvalues are raised to at least ``min_eigenvalue``, and it is rescaled with
61
+ the DDC scales.
62
+
63
+ As in cellWise, step 3 removes no rows when the data contain missing values (their
64
+ Mahalanobis distances are then not available).
65
+
66
+ Parameters:
67
+ alpha (float, optional):
68
+ Percentage indicating how much cells must remain unflagged in each column.
69
+ Must lie within 0.5 to 1.0. Defaults to 0.75.
70
+ min_eigenvalue (float, optional):
71
+ Lower bound on the minimum eigenvalue of the covariance estimator
72
+ on the standardized data. Should be at least 1e-6.
73
+ Defaults to 1e-4.
74
+ fixed_center (bool, optional):
75
+ If True, the center is fixed at 0 (``fixedCenter`` in cellWise) and the DDC
76
+ scales are computed around 0. Defaults to False.
77
+
78
+ References:
79
+ - Raymaekers, J., & Rousseeuw, P. J. (2024). The cellwise minimum covariance determinant
80
+ estimator. Journal of the American Statistical Association, 119(548), 2610-2621.
81
+ """
82
+ super().__init__(store_precision=True, assume_centered=False, nans_allowed=True)
83
+ self.alpha = alpha
84
+ self.min_eigenvalue = min_eigenvalue
85
+ self.fixed_center = fixed_center
86
+ self.logger = get_logger("InitialDDCW", level=verbosity)
87
+ self.verbosity = verbosity
88
+
89
+ def calculate_covariance(self, X: np.ndarray):
90
+ n, p = X.shape
91
+ if not 0.5 <= self.alpha <= 1:
92
+ raise ValueError(f"alpha must a float between 0.5 and 1, but received {self.alpha}.")
93
+ if p > n:
94
+ raise ValueError(
95
+ f"You need at least {p + 1} cases to estimate a nonsingular covariance matrix of "
96
+ f"size {p}, but there are only {n} cases."
97
+ )
98
+ max_col = 1 - self.alpha
99
+
100
+ # DDC with at most a fraction max_col of flagged cells per column
101
+ frame = pd.DataFrame(X)
102
+ ddc = DDC(
103
+ cell_quantile=0.9,
104
+ scale_estimator=OneStepWrapping(),
105
+ center=np.zeros(p) if self.fixed_center else None,
106
+ min_unique_values=0,
107
+ ).fit(frame)
108
+ flags = ddc.cellwise_outliers_.copy()
109
+ for j in np.flatnonzero(flags.sum(axis=0) > max_col * n):
110
+ residuals = np.abs(ddc.standardized_residuals_[:, j])
111
+ order = np.argsort(-np.nan_to_num(residuals, nan=-np.inf), kind="stable")
112
+ flags[:, j] = False
113
+ flags[order[: int(np.floor(max_col * n))], j] = True
114
+ estimates = ddc.rescaled_predictions_
115
+ Ximp = np.where(flags | np.isnan(X), estimates, X)
116
+ loc, scale = ddc.location_, ddc.scale_
117
+ Z = (X - loc) / scale
118
+ Zimp = (Ximp - loc) / scale
119
+
120
+ # first covariance: wrapped scores around 0, without the rows flagged by DDC
121
+ keep = ~ddc.row_outliers_
122
+ cov = _wrapped_covariance(Zimp[keep], self.min_eigenvalue, center=False)
123
+ cov = truncate_eigenvalues(cov, self.min_eigenvalue)
124
+ cov = covariance_to_correlation(cov) * np.outer(scale, scale)
125
+
126
+ # row rule: leave out the rows that are outlying with respect to this covariance
127
+ clipped = np.clip(Z, -2, 2)
128
+ inv = np.linalg.inv(cov)
129
+ distances = np.einsum("ij,jk,ik->i", clipped, inv, clipped)
130
+ if np.isnan(distances).any():
131
+ outlying = np.zeros(n, dtype=bool) # cellWise: median(MDs) is NA
132
+ else:
133
+ outlying = distances / np.median(distances) * chi2.ppf(0.5, p) > chi2.ppf(0.99, p)
134
+
135
+ # final covariance: wrapped centered scores of the remaining rows
136
+ cov = _wrapped_covariance(Zimp[~outlying], self.min_eigenvalue, center=True)
137
+ cov = truncate_eigenvalues(covariance_to_correlation(cov), self.min_eigenvalue)
138
+ cov = cov * np.outer(scale, scale)
139
+
140
+ self.location_ = np.asarray(loc, dtype=float)
141
+ return cov