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,591 @@
1
+ import numpy as np
2
+ import logging
3
+ from sklearn.base import (
4
+ BaseEstimator,
5
+ OneToOneFeatureMixin,
6
+ TransformerMixin,
7
+ )
8
+ from typing import Literal
9
+ from robpy.utils.rho import TukeyBisquare
10
+ from scipy.stats import median_abs_deviation, norm, chi2
11
+ from scipy.optimize import minimize_scalar
12
+ from robpy.univariate import HuberOneStepMEstimator
13
+
14
+
15
+ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
16
+ def __init__(
17
+ self,
18
+ method: Literal["boxcox", "yeojohnson", "auto"] = "yeojohnson",
19
+ standardize: bool = True,
20
+ lambda_range: tuple[float, float] = (-4.0, 6.0),
21
+ quantile: float = 0.99,
22
+ nsteps: int = 2,
23
+ ):
24
+ """
25
+ Apply a robust power transformation using reweighted maximum likelihood to transform the
26
+ features closer to normality. Uses the Box-Cox or the Yeo-Johnson transformation.
27
+
28
+ Args:
29
+ method (Literal str, optional): method used for the power transformation.
30
+ Can be "boxcox" for Box-Cox, "yeojohnson" for Yeo-Johnson, or "auto"
31
+ for best objective solution. Box-Cox can only be used for strictly
32
+ positive features. Defaults to "auto".
33
+ standardize (boolean, optional): whether to standardize the features before and after
34
+ the power transformation. Defaults to True.
35
+ quantile (float, optional): quantile used to calculate the weights. Defaults to 0.99.
36
+ nsteps (int, optional): number of steps used in the reweighted maximum likelihood.
37
+ Defaults to 2.
38
+ """
39
+ self.method = method
40
+ self.standardize = standardize
41
+ self.lambda_range = list(lambda_range)
42
+ self.quantile = quantile
43
+ self.nsteps = nsteps
44
+ self.logger = logging.getLogger("RobustPowerTransformer")
45
+
46
+ def fit(self, x: np.ndarray):
47
+ """Calculates lambda, the transformation parameter depending on the method.
48
+
49
+ Args:
50
+ x (np.array): data.
51
+ """
52
+
53
+ self._get_method(x)
54
+ x_sorted = np.sort(x)
55
+
56
+ if self.method in ["boxcox", "auto"]:
57
+ lambda_boxcox, mu_rew_boxcox, sd_rew_boxcox, scale_boxcox = self._fit_boxcox(x_sorted)
58
+ if self.method == "auto":
59
+ crit_val_boxcox = self._robnormality(x, "boxcox", lambda_boxcox)
60
+
61
+ if self.method in ["yeojohnson", "auto"]:
62
+ (
63
+ lambda_yeojohnson,
64
+ mu_rew_yeojohnson,
65
+ sd_rew_yeojohnson,
66
+ loc_yeojohnson,
67
+ scale_yeojohnson,
68
+ ) = self._fit_yeojohnson(x_sorted)
69
+ if self.method == "auto":
70
+ crit_val_yeojohnson = self._robnormality(x, "yeojohnson", lambda_yeojohnson)
71
+
72
+ if self.method == "auto":
73
+ if crit_val_boxcox < crit_val_yeojohnson:
74
+ self.method = "boxcox"
75
+ else:
76
+ self.method = "yeojohnson"
77
+
78
+ if self.method == "boxcox":
79
+ if self.standardize:
80
+ self.scale_pre = scale_boxcox
81
+ self.location_post = mu_rew_boxcox
82
+ self.scale_post = sd_rew_boxcox
83
+ self.lambda_rew = lambda_boxcox
84
+ else: # yeojohnson
85
+ if self.standardize:
86
+ self.location_pre = loc_yeojohnson
87
+ self.scale_pre = scale_yeojohnson
88
+ self.location_post = mu_rew_yeojohnson
89
+ self.scale_post = sd_rew_yeojohnson
90
+ self.lambda_rew = lambda_yeojohnson
91
+
92
+ return self
93
+
94
+ def transform(self, x: np.ndarray) -> np.ndarray:
95
+ """Transforms the data using the calculated lambda estimate and the corresponding method.
96
+
97
+ Args:
98
+ x (np.array): data.
99
+ """
100
+
101
+ if self.method == "boxcox":
102
+ if np.min(x) <= 0:
103
+ raise ValueError(
104
+ "The data is not strictly positive. Box-Cox transformation "
105
+ "cannot be applied."
106
+ )
107
+ if self.standardize:
108
+ x = x / self.scale_pre
109
+ x = self._transf_boxcox(x, self.lambda_rew)[0]
110
+ if self.standardize:
111
+ x = (x - self.location_post) / self.scale_post
112
+ else: # yeojohnson
113
+ if self.standardize:
114
+ x = (x - self.location_pre) / self.scale_pre
115
+ x = self._transf_yeojohnson(x, self.lambda_rew)[0]
116
+ if self.standardize:
117
+ x = (x - self.location_post) / self.scale_post
118
+
119
+ return x
120
+
121
+ def inverse_transform(self, x: np.ndarray) -> np.ndarray:
122
+ """Transforms the data back using inverse Yeo-Johnson/Box-cox, the previously fitted lambda
123
+ estimate and the corresponding method are used.
124
+
125
+ Args:
126
+ x (np.array): data.
127
+ """
128
+
129
+ if self.method == "boxcox":
130
+ if self.standardize:
131
+ x = x * self.scale_post + self.location_post
132
+ x = self._handle_bounds(x)
133
+ x = self._inv_transf_boxcox(x, self.lambda_rew)
134
+ if self.standardize:
135
+ x = x * self.scale_pre
136
+
137
+ else: # yeojohnson
138
+ if self.standardize:
139
+ x = x * self.scale_post + self.location_post
140
+ x = self._handle_bounds(x)
141
+ x = self._inv_transf_yeojohnson(x, self.lambda_rew)
142
+ if self.standardize:
143
+ x = x * self.scale_pre + self.location_pre
144
+
145
+ return x
146
+
147
+ def _fit_boxcox(self, x: np.ndarray):
148
+ """fits the Box-Cox power transformation
149
+
150
+ Args:
151
+ x (np.array): data"""
152
+ lambdarange = self.lambda_range
153
+ converged = False
154
+ while not converged:
155
+ if self.standardize:
156
+ scale_boxcox = np.median(x)
157
+ x = x / scale_boxcox
158
+ else:
159
+ scale_boxcox = None
160
+ lambda_raw = self._calculate_lambda_0(x, "boxcox_rect", lambdarange)
161
+ lambda_rew, mu_rew_boxcox, sd_rew_boxcox = self._reweighted_max_likelihood_robust(
162
+ x,
163
+ lambda_raw,
164
+ "boxcox",
165
+ lambdarange,
166
+ self.quantile,
167
+ self.nsteps,
168
+ )
169
+ converged = np.min(np.abs(lambda_rew - lambdarange)) > np.diff(lambdarange) * 0.05
170
+ if not converged:
171
+ lambdarange = 1 + (lambdarange - 1) * (
172
+ 1 + (abs(lambda_rew - lambdarange) == min(abs(lambda_rew - lambdarange)))
173
+ )
174
+
175
+ return lambda_rew, mu_rew_boxcox, sd_rew_boxcox, scale_boxcox
176
+
177
+ def _fit_yeojohnson(self, x: np.ndarray):
178
+ """fits the Yeo-Johnson power transformation
179
+
180
+ Args:
181
+ x (np.array): data"""
182
+ lambdarange = self.lambda_range
183
+ converged = False
184
+ while not converged:
185
+ if self.standardize:
186
+ loc_yeojohnson = np.median(x)
187
+ scale_yeojohnson = median_abs_deviation(x, scale="normal")
188
+ x = (x - loc_yeojohnson) / scale_yeojohnson
189
+ else:
190
+ loc_yeojohnson, scale_yeojohnson = None, None
191
+ lambda_raw = self._calculate_lambda_0(x, "yeojohnson_rect", lambdarange)
192
+ (
193
+ lambda_rew,
194
+ mu_rew_yeojohnson,
195
+ sd_rew_yeojohnson,
196
+ ) = self._reweighted_max_likelihood_robust(
197
+ x,
198
+ lambda_raw,
199
+ "yeojohnson",
200
+ lambdarange,
201
+ self.quantile,
202
+ self.nsteps,
203
+ )
204
+ converged = np.min(np.abs(lambda_rew - lambdarange)) > np.diff(lambdarange) * 0.05
205
+ if not converged:
206
+ lambdarange = 1 + (lambdarange - 1) * (
207
+ 1 + (abs(lambda_rew - lambdarange) == min(abs(lambda_rew - lambdarange)))
208
+ )
209
+
210
+ return lambda_rew, mu_rew_yeojohnson, sd_rew_yeojohnson, loc_yeojohnson, scale_yeojohnson
211
+
212
+ def _calculate_bounds(self):
213
+ """Calculates the bounds of the range of the power transformation"""
214
+
215
+ lower_bound, upper_bound = None, None
216
+
217
+ if self.method == "boxcox" and self.lambda_rew > 0.0:
218
+ lower_bound = -1.0 / np.abs(self.lambda_rew)
219
+ elif self.method == "boxcox" and self.lambda_rew < 0.0:
220
+ upper_bound = 1.0 / np.abs(self.lambda_rew)
221
+ elif self.method == "yeojohnson" and self.lambda_rew > 2.0:
222
+ lower_bound = -1.0 / np.abs(self.lambda_rew - 2.0)
223
+ elif self.method == "yeojohnson" and self.lambda_rew < 0.0:
224
+ upper_bound = 1.0 / np.abs(self.lambda_rew)
225
+
226
+ return lower_bound, upper_bound
227
+
228
+ def _handle_bounds(self, x: np.ndarray):
229
+ lower_bound, upper_bound = self._calculate_bounds()
230
+
231
+ if lower_bound is not None and np.min(x) < lower_bound:
232
+ new_bound = 0.95 * lower_bound
233
+ self.logger.info(
234
+ f"Some (standardized) values in x are below the range of the {self.method} "
235
+ f"transformation. These values were replaced by {new_bound} so they "
236
+ "can be transformed back."
237
+ )
238
+ x = np.where(x < lower_bound, new_bound, x)
239
+
240
+ if upper_bound is not None and np.max(x) > upper_bound:
241
+ new_bound = 0.95 * upper_bound
242
+ self.logger.info(
243
+ f"Some (standardized) values in x are above the range of the {self.method} "
244
+ f"transformation. These values were replaced by {new_bound} so they "
245
+ "can be transformed back."
246
+ )
247
+ x = np.where(x > upper_bound, new_bound, x)
248
+
249
+ return x
250
+
251
+ def _transf_boxcox_rectified(
252
+ self, x: np.ndarray, my_lambda: float, standardize_too: bool = False
253
+ ):
254
+ """Rectified BoxCox transformation"""
255
+
256
+ if np.min(x) <= 0:
257
+ raise ValueError("Data values should be strictly positive for a BoxCox transformation.")
258
+ xt = np.zeros_like(x)
259
+
260
+ if my_lambda == 1.0:
261
+ xt = x - 1.0
262
+ else:
263
+ changepoint = self._get_rectified_boxcox_changepoint(x, my_lambda)
264
+
265
+ if my_lambda > 1.0:
266
+ mask = x < changepoint
267
+ else:
268
+ mask = x > changepoint
269
+ if my_lambda == 0:
270
+ xt[~mask] = np.log(x[~mask])
271
+ changepoint_transf = np.log(changepoint)
272
+ xt[mask] = changepoint_transf + (x[mask] - changepoint) / changepoint
273
+ else:
274
+ xt[~mask] = (x[~mask] ** my_lambda - 1) / my_lambda
275
+ changepoint_transf = (changepoint**my_lambda - 1) / my_lambda
276
+ xt[mask] = changepoint_transf + (x[mask] - changepoint) * changepoint ** (
277
+ my_lambda - 1
278
+ )
279
+
280
+ if standardize_too:
281
+ loc_scale = HuberOneStepMEstimator().fit(xt)
282
+ zt = (xt - loc_scale.location) / loc_scale.scale
283
+ else:
284
+ zt = None
285
+
286
+ return xt, zt
287
+
288
+ def _get_rectified_boxcox_changepoint(
289
+ self, x: np.ndarray, my_lambda: float, factor: float = 1.5, eps: float = 1e-5
290
+ ) -> float:
291
+ """Get C_u or C_l for the rectified BoxCox transform"""
292
+ n = len(x)
293
+ Q1 = x[int(np.ceil(n / 4.0) - 1.0)]
294
+ Q3 = x[int(n - np.ceil(n / 4.0))]
295
+
296
+ if my_lambda < 1:
297
+ changepoint = self._transf_boxcox(Q3, my_lambda)[0] * factor
298
+ elif my_lambda > 1:
299
+ changepoint = self._transf_boxcox(Q1, my_lambda)[0] * factor
300
+ else:
301
+ raise ValueError("There is no changepoint for lambda equals 1.")
302
+
303
+ if my_lambda < 0.0:
304
+ changepoint = min(changepoint, np.abs(1.0 / my_lambda) - eps)
305
+ elif my_lambda > 0.0:
306
+ changepoint = max(changepoint, -1.0 / my_lambda + eps)
307
+
308
+ changepoint = self._inv_transf_boxcox(changepoint, my_lambda)
309
+ changepoint = min(max(changepoint, x[0]), x[n - 1])
310
+
311
+ return changepoint
312
+
313
+ def _transf_boxcox(self, x: np.ndarray, my_lambda: float, standardize_too: bool = False):
314
+ """Classical BoxCox transformation"""
315
+ if np.min(x) <= 0:
316
+ raise ValueError("Data values should be strictly positive for a BoxCox transformation.")
317
+ if my_lambda == 0:
318
+ xt = np.log(x)
319
+ else:
320
+ xt = (x**my_lambda - 1) / my_lambda
321
+
322
+ if standardize_too:
323
+ loc_scale = HuberOneStepMEstimator().fit(xt)
324
+ zt = (xt - loc_scale.location) / loc_scale.scale
325
+ else:
326
+ zt = None
327
+
328
+ return xt, zt
329
+
330
+ def _transf_yeojohnson(self, x: np.ndarray, my_lambda: float, standardize_too: bool = False):
331
+ """Classical Yeo-Johnson transformation"""
332
+
333
+ positive_mask = x >= 0.0
334
+ xt = np.zeros_like(x)
335
+
336
+ if my_lambda == 0.0:
337
+ xt[positive_mask] = np.log(1.0 + x[positive_mask])
338
+ xt[~positive_mask] = -((1 - x[~positive_mask]) ** (2 - my_lambda) - 1) / (2 - my_lambda)
339
+ elif my_lambda == 2.0:
340
+ xt[positive_mask] = ((1 + x[positive_mask]) ** my_lambda - 1) / my_lambda
341
+ xt[~positive_mask] = -np.log(1 - x[~positive_mask])
342
+ else:
343
+ xt[positive_mask] = ((1 + x[positive_mask]) ** my_lambda - 1) / my_lambda
344
+ xt[~positive_mask] = -((1 - x[~positive_mask]) ** (2 - my_lambda) - 1) / (2 - my_lambda)
345
+
346
+ if standardize_too:
347
+ loc_scale = HuberOneStepMEstimator().fit(xt)
348
+ zt = (xt - loc_scale.location) / loc_scale.scale
349
+ else:
350
+ zt = None
351
+
352
+ return xt, zt
353
+
354
+ def _transf_yeojohnson_rectified(
355
+ self, x: np.ndarray, my_lambda: float, standardize_too: bool = False
356
+ ):
357
+ """Rectified Yeo-Johnson transformation"""
358
+
359
+ xt = np.zeros_like(x)
360
+
361
+ if my_lambda == 1.0:
362
+ xt = x
363
+
364
+ else:
365
+ changepoint = self._get_rectified_yeojohnson_changepoint(x, my_lambda)
366
+ positive_mask = x >= 0.0
367
+ negative_mask = x < 0.0
368
+
369
+ if my_lambda > 1.0:
370
+ mask_lower = x < changepoint
371
+ mask_upper = (changepoint <= x) & (x < 0)
372
+ xt[positive_mask] = ((1 + x[positive_mask]) ** my_lambda - 1.0) / my_lambda
373
+ if my_lambda == 2:
374
+ xt[mask_upper] = -np.log(1 - x[mask_upper])
375
+ xt[mask_lower] = -np.log(1 - changepoint) + (
376
+ x[mask_lower] - changepoint
377
+ ) * 1 / (1 - changepoint)
378
+ else:
379
+ xt[mask_upper] = -((1 - x[mask_upper]) ** (2 - my_lambda) - 1) / (2 - my_lambda)
380
+ changepoint_transf = self._transf_yeojohnson(changepoint, my_lambda)[0]
381
+ xt[mask_lower] = changepoint_transf + (x[mask_lower] - changepoint) * (
382
+ 1 + np.abs(changepoint)
383
+ ) ** (1 - my_lambda)
384
+ else:
385
+ mask_upper = x > changepoint
386
+ mask_lower = (x >= 0) & (x <= changepoint)
387
+ xt[negative_mask] = -((1 - x[negative_mask]) ** (2 - my_lambda) - 1) / (
388
+ 2 - my_lambda
389
+ )
390
+ if my_lambda == 0.0:
391
+ xt[mask_lower] = np.log(1 + x[mask_lower])
392
+ xt[mask_upper] = np.log(1 + changepoint) + (x[mask_upper] - changepoint) * 1 / (
393
+ 1 + changepoint
394
+ )
395
+ else:
396
+ xt[mask_lower] = ((1 + x[mask_lower]) ** my_lambda - 1) / my_lambda
397
+ changepoint_transf = self._transf_yeojohnson(changepoint, my_lambda)[0]
398
+ xt[mask_upper] = changepoint_transf + (x[mask_upper] - changepoint) * (
399
+ 1 + np.abs(changepoint)
400
+ ) ** (my_lambda - 1)
401
+
402
+ if standardize_too:
403
+ loc_scale = HuberOneStepMEstimator().fit(xt)
404
+ zt = (xt - loc_scale.location) / loc_scale.scale
405
+ else:
406
+ zt = None
407
+
408
+ return xt, zt
409
+
410
+ def _get_rectified_yeojohnson_changepoint(
411
+ self, x: np.ndarray, my_lambda: float, factor: float = 1.5, eps: float = 1e-5
412
+ ) -> float:
413
+ """Get C_u or C_l for the rectified BoxCox transform"""
414
+ n = len(x)
415
+ Q1 = x[int(np.ceil(n / 4.0) - 1.0)]
416
+ Q3 = x[int(n - np.ceil(n / 4.0))]
417
+
418
+ if my_lambda < 1:
419
+ changepoint = self._transf_yeojohnson(Q3, my_lambda)[0] * factor
420
+ elif my_lambda > 1:
421
+ changepoint = self._transf_yeojohnson(Q1, my_lambda)[0] * factor
422
+ else:
423
+ raise ValueError("There is no changepoint for lambda equals 1.")
424
+
425
+ if my_lambda < 0.0:
426
+ changepoint = min(changepoint, np.abs(1.0 / my_lambda) - eps)
427
+ elif my_lambda > 2.0:
428
+ changepoint = max(changepoint, (1.0 / (2 - my_lambda)) + eps)
429
+
430
+ changepoint = self._inv_transf_yeojohnson(changepoint, my_lambda)
431
+ changepoint = min(max(changepoint, x[0]), x[n - 1])
432
+
433
+ return changepoint
434
+
435
+ def _inv_transf_boxcox(self, x: np.ndarray, my_lambda: float) -> np.ndarray:
436
+ """Classical BoxCox transformation inversed"""
437
+ if my_lambda == 0:
438
+ xt = np.exp(x)
439
+ else:
440
+ xt = (x * my_lambda + 1) ** (1.0 / my_lambda)
441
+ return xt
442
+
443
+ def _inv_transf_yeojohnson(self, x: np.ndarray, my_lambda: float) -> np.ndarray:
444
+ """Classical Yeo-Johnson transformation inversed"""
445
+
446
+ positive_mask = x >= 0.0
447
+ xt = np.zeros_like(x)
448
+
449
+ if my_lambda == 0.0:
450
+ xt[positive_mask] = np.exp(x[positive_mask]) - 1.0
451
+ xt[~positive_mask] = 1.0 - (1 + (my_lambda - 2) * x[~positive_mask]) ** (
452
+ 1 / (2 - my_lambda)
453
+ )
454
+ elif my_lambda == 2.0:
455
+ xt[positive_mask] = (my_lambda * x[positive_mask] + 1) ** (1 / my_lambda) - 1
456
+ xt[~positive_mask] = 1 - np.exp(-x[~positive_mask])
457
+ else:
458
+ xt[positive_mask] = (my_lambda * x[positive_mask] + 1) ** (1 / my_lambda) - 1
459
+ xt[~positive_mask] = 1.0 - (1 + (my_lambda - 2) * x[~positive_mask]) ** (
460
+ 1 / (2 - my_lambda)
461
+ )
462
+
463
+ return xt
464
+
465
+ def _robnormality(
466
+ self,
467
+ x: np.ndarray,
468
+ transf: Literal["boxcox_rect", "yeojohnson_rect", "boxcox", "yeojohnson"],
469
+ my_lambda: float,
470
+ ) -> float:
471
+ """Objective function of Equation (5) in Raymaekers & Rousseeuw (2021)
472
+ Transforming variables to central normality
473
+ """
474
+
475
+ if not np.all(np.diff(x) >= 0):
476
+ x = np.sort(x)
477
+
478
+ if transf == "boxcox_rect":
479
+ x = self._transf_boxcox_rectified(x, my_lambda)[0]
480
+ elif transf == "yeojohnson_rect":
481
+ x = self._transf_yeojohnson_rectified(x, my_lambda)[0]
482
+ elif transf == "boxcox":
483
+ x = self._transf_boxcox(x, my_lambda)[0]
484
+ elif transf == "yeojohnson":
485
+ x = self._transf_yeojohnson(x, my_lambda)[0]
486
+ else:
487
+ raise NotImplementedError("Other transformations not yet implemented.")
488
+
489
+ x = x[~np.isnan(x)]
490
+ n = len(x)
491
+
492
+ loc_scale = HuberOneStepMEstimator().fit(x)
493
+ x = (x - loc_scale.location) / np.where(loc_scale.scale == 0, 1, loc_scale.scale)
494
+
495
+ theo_quantile = norm.ppf((np.arange(1, n + 1) - 1 / 3) / (n + 1 / 3))
496
+ obj = TukeyBisquare(c=0.5).rho(x - theo_quantile)
497
+ crit = np.sum(obj)
498
+
499
+ return crit
500
+
501
+ def _calculate_lambda_0(
502
+ self,
503
+ x: np.ndarray,
504
+ transf: Literal["boxcox_rect", "yeojohnson_rect"] = "boxcox_rect",
505
+ lambdarange: list[float] = [-4.0, 6.0],
506
+ ):
507
+ """Computes the initial estimate for lambda by optimizing the objective function."""
508
+ lambda_0 = minimize_scalar(
509
+ lambda lambdatemp: self._robnormality(x, transf, lambdatemp),
510
+ bounds=lambdarange,
511
+ method="bounded",
512
+ )
513
+
514
+ return lambda_0.x
515
+
516
+ def _reweighted_max_likelihood_robust(
517
+ self,
518
+ x: np.ndarray,
519
+ lambda_raw: float,
520
+ transf: Literal["boxcox", "yeojohnson"],
521
+ lambdarange: list[float] = [-4.0, 6.0],
522
+ quantile: float = 0.99,
523
+ nsteps: int = 2,
524
+ ):
525
+ """Computes the reweighted estimate for lambda by performing reweighted ML."""
526
+
527
+ if transf == "boxcox":
528
+ zt = self._transf_boxcox_rectified(x, lambda_raw, standardize_too=True)[1]
529
+ elif transf == "yeojohnson":
530
+ zt = self._transf_yeojohnson_rectified(x, lambda_raw, standardize_too=True)[1]
531
+
532
+ for _ in range(nsteps):
533
+ w = np.abs(zt) <= np.sqrt(chi2.ppf(quantile, 1))
534
+ lambda_rew = self._estimate_max_likelihood(x[w], transf, lambdarange)
535
+ if transf == "boxcox":
536
+ xt = self._transf_boxcox(x, lambda_rew, standardize_too=False)[0]
537
+ elif transf == "yeojohnson":
538
+ xt = self._transf_yeojohnson(x, lambda_rew, standardize_too=False)[0]
539
+ zt = (xt - np.mean(xt)) / np.std(xt)
540
+
541
+ mu_rew = np.mean(xt[w])
542
+ sd_rew = np.std(xt[w])
543
+
544
+ return lambda_rew, mu_rew, sd_rew
545
+
546
+ def _estimate_max_likelihood(
547
+ self,
548
+ x: np.ndarray,
549
+ transf: Literal["boxcox", "yeojohnson"],
550
+ lambdarange: list[float] = [-4.0, 6.0],
551
+ ):
552
+ """Computes an estimate for lambda by using ML."""
553
+ n = len(x)
554
+
555
+ if transf == "boxcox":
556
+
557
+ def obj_func(lambdatemp):
558
+ x_bc = self._transf_boxcox(x, lambdatemp)[0]
559
+ mu = np.mean(x_bc)
560
+ sigma2 = np.mean((x_bc - mu) ** 2)
561
+ return (n / 2) * np.log(sigma2) - (lambdatemp - 1) * np.sum(np.log(x))
562
+
563
+ elif transf == "yeojohnson":
564
+
565
+ def obj_func(lambdatemp):
566
+ x_yj = self._transf_yeojohnson(x, lambdatemp)[0]
567
+ mu = np.mean(x_yj)
568
+ sigma2 = np.mean((x_yj - mu) ** 2)
569
+ return (n / 2) * np.log(sigma2) - (lambdatemp - 1) * np.sum(
570
+ np.sign(x) * np.log(1 + np.abs(x))
571
+ )
572
+
573
+ else:
574
+ raise NotImplementedError("Wrong transformation.")
575
+
576
+ lambda_est = minimize_scalar(obj_func, bounds=lambdarange, method="bounded").x
577
+
578
+ return lambda_est
579
+
580
+ def _get_method(self, x: np.ndarray):
581
+ if self.method == "boxcox":
582
+ if np.min(x) <= 0:
583
+ raise ValueError("The data is not strictly positive. Box-Cox cannot be applied.")
584
+ elif self.method == "auto":
585
+ if np.min(x) <= 0:
586
+ self.method = "yeojohnson"
587
+ elif self.method != "yeojohnson":
588
+ raise ValueError(
589
+ 'The only supported methods of transformation are "boxcox", "yeojohnson" or "auto".'
590
+ )
591
+ return self
@@ -0,0 +1,63 @@
1
+ import numpy as np
2
+
3
+ from typing import Callable
4
+ from scipy.stats import median_abs_deviation
5
+
6
+
7
+ def wrapping_transformation(
8
+ X: np.ndarray,
9
+ b: float = 1.5,
10
+ c: float = 4.0,
11
+ q1: float = 1.540793,
12
+ q2: float = 0.8622731,
13
+ rescale: bool = False,
14
+ location_estimator: Callable[[np.ndarray, int], np.ndarray] = np.median,
15
+ scale_estimator: Callable[[np.ndarray, int], np.ndarray] = median_abs_deviation,
16
+ ) -> np.ndarray:
17
+ """
18
+ Implementation of wrapping using this transformation function:
19
+
20
+ .. math::
21
+
22
+ \\Psi_{b, c}(z) =
23
+ \\begin{cases}
24
+ z & if \\ 0 \\leq |z| < b \\\\
25
+ q_1 \\tanh\\left(q_2 (c - |z|)\\right) \\mathrm{sign}(z) & if \\ b \\leq |z| \\leq c \\\\
26
+ 0 & if \\ c < |z|
27
+ \\end{cases}
28
+
29
+ Args:
30
+ X: data to be transformed, must have shape (N, D)
31
+ b: lower cutoff
32
+ c: upper cutoff
33
+ q1, q2: transformation parameters (see formula)
34
+ rescale: whether to rescale the wrapped data so the robust location and scale
35
+ of the transformed data are the same as the original data
36
+ locations: location estimates of the columns of X (optional)
37
+ scales: scale estimates of the columns of X (optional)
38
+
39
+ Returns:
40
+ transformed data
41
+ """
42
+ locations = location_estimator(X, axis=0)
43
+ scales = scale_estimator(X, axis=0)
44
+ scales_no_zero = np.where(scales == 0, 1, scales)
45
+
46
+ z = (X - locations) / scales_no_zero
47
+
48
+ z_wrapped = np.where(
49
+ np.abs(z) < b,
50
+ z,
51
+ np.where(np.abs(z) <= c, q1 * np.tanh(q2 * (c - np.abs(z))) * np.sign(z), 0),
52
+ )
53
+ if rescale:
54
+ z_wrapped_mean = np.mean(z_wrapped, axis=0)
55
+ z_wrapped_std = np.std(z_wrapped, axis=0)
56
+ z_wrapped_std_no_zero = np.where(z_wrapped_std == 0, 1, z_wrapped_std)
57
+ return (
58
+ z_wrapped * (scales / z_wrapped_std_no_zero)
59
+ + locations
60
+ - (z_wrapped_mean * (scales / z_wrapped_std_no_zero))
61
+ )
62
+ else:
63
+ return z_wrapped * scales + locations
@@ -0,0 +1,3 @@
1
+ from robpy.regression.lts import FastLTSRegressor
2
+ from robpy.regression.mm_estimator import MMEstimator
3
+ from robpy.regression.s_estimator import SEstimator