chemotools 0.1.9__tar.gz → 0.1.10__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 (59) hide show
  1. {chemotools-0.1.9 → chemotools-0.1.10}/PKG-INFO +1 -1
  2. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/__init__.py +2 -0
  3. chemotools-0.1.10/chemotools/augmentation/_gaussian_broadening.py +136 -0
  4. chemotools-0.1.10/chemotools/outliers/__init__.py +7 -0
  5. chemotools-0.1.10/chemotools/outliers/_base.py +180 -0
  6. chemotools-0.1.10/chemotools/outliers/_utils.py +91 -0
  7. chemotools-0.1.10/chemotools/outliers/dmodx.py +146 -0
  8. chemotools-0.1.10/chemotools/outliers/hotelling_t2.py +155 -0
  9. chemotools-0.1.10/chemotools/outliers/leverage.py +150 -0
  10. chemotools-0.1.10/chemotools/outliers/q_residuals.py +225 -0
  11. chemotools-0.1.10/chemotools/outliers/studentized_residuals.py +197 -0
  12. {chemotools-0.1.9 → chemotools-0.1.10}/pyproject.toml +1 -1
  13. {chemotools-0.1.9 → chemotools-0.1.10}/LICENSE +0 -0
  14. {chemotools-0.1.9 → chemotools-0.1.10}/README.md +0 -0
  15. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/__init__.py +0 -0
  16. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/_add_noise.py +0 -0
  17. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/_baseline_shift.py +0 -0
  18. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/_fractional_shift.py +0 -0
  19. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/_index_shift.py +0 -0
  20. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/augmentation/_spectrum_scale.py +0 -0
  21. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/__init__.py +0 -0
  22. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_air_pls.py +0 -0
  23. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_ar_pls.py +0 -0
  24. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_constant_baseline_correction.py +0 -0
  25. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_cubic_spline_correction.py +0 -0
  26. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_linear_correction.py +0 -0
  27. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_non_negative.py +0 -0
  28. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_polynomial_correction.py +0 -0
  29. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/baseline/_subtract_reference.py +0 -0
  30. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/__init__.py +0 -0
  31. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/_base.py +0 -0
  32. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/__init__.py +0 -0
  33. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/coffee_labels.csv +0 -0
  34. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/coffee_spectra.csv +0 -0
  35. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/fermentation_hplc.csv +0 -0
  36. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/fermentation_spectra.csv +0 -0
  37. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/train_hplc.csv +0 -0
  38. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/datasets/data/train_spectra.csv +0 -0
  39. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/derivative/__init__.py +0 -0
  40. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/derivative/_norris_william.py +0 -0
  41. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/derivative/_savitzky_golay.py +0 -0
  42. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/feature_selection/__init__.py +0 -0
  43. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/feature_selection/_index_selector.py +0 -0
  44. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/feature_selection/_range_cut.py +0 -0
  45. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scale/__init__.py +0 -0
  46. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scale/_min_max_scaler.py +0 -0
  47. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scale/_norm_scaler.py +0 -0
  48. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scale/_point_scaler.py +0 -0
  49. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scatter/__init__.py +0 -0
  50. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scatter/_extended_multiplicative_scatter_correction.py +0 -0
  51. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scatter/_multiplicative_scatter_correction.py +0 -0
  52. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scatter/_robust_normal_variate.py +0 -0
  53. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/scatter/_standard_normal_variate.py +0 -0
  54. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/smooth/__init__.py +0 -0
  55. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/smooth/_mean_filter.py +0 -0
  56. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/smooth/_median_filter.py +0 -0
  57. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/smooth/_savitzky_golay_filter.py +0 -0
  58. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/smooth/_whittaker_smooth.py +0 -0
  59. {chemotools-0.1.9 → chemotools-0.1.10}/chemotools/utils/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: chemotools
3
- Version: 0.1.9
3
+ Version: 0.1.10
4
4
  Summary: chemotools: A Python Package that Integrates Chemometrics and scikit-learn
5
5
  License: MIT
6
6
  Author: Pau Cabaneros
@@ -1,6 +1,7 @@
1
1
  from ._add_noise import AddNoise
2
2
  from ._baseline_shift import BaselineShift
3
3
  from ._fractional_shift import FractionalShift
4
+ from ._gaussian_broadening import GaussianBroadening
4
5
  from ._index_shift import IndexShift
5
6
  from ._spectrum_scale import SpectrumScale
6
7
 
@@ -9,6 +10,7 @@ __all__ = [
9
10
  "AddNoise",
10
11
  "BaselineShift",
11
12
  "FractionalShift",
13
+ "GaussianBroadening",
12
14
  "IndexShift",
13
15
  "SpectrumScale",
14
16
  ]
@@ -0,0 +1,136 @@
1
+ from typing import Literal, Optional
2
+ import numpy as np
3
+ from scipy.ndimage import gaussian_filter1d
4
+ from sklearn.base import BaseEstimator, TransformerMixin, OneToOneFeatureMixin
5
+ from sklearn.utils.validation import check_is_fitted, validate_data
6
+
7
+
8
+ class GaussianBroadening(TransformerMixin, OneToOneFeatureMixin, BaseEstimator):
9
+ """
10
+ Transform spectral data by broadening peaks using Gaussian convolution.
11
+
12
+ This transformer applies Gaussian smoothing to broaden peaks in spectral data.
13
+ For each signal, a random sigma is chosen between 0 and the specified sigma value.
14
+
15
+ Parameters
16
+ ----------
17
+ sigma : float, default=1.0
18
+ Maximum standard deviation for the Gaussian kernel.
19
+ The actual sigma used will be randomly chosen between 0 and this value.
20
+
21
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, default='reflect'
22
+ The mode parameter determines how the input array is extended when
23
+ the filter overlaps a border. Default is 'reflect'.
24
+
25
+ pad_value : float, default=0.0
26
+ Value to fill past edges of input if mode is 'constant'.
27
+
28
+ random_state : int, optional, default=None
29
+ Random state for reproducible sigma selection.
30
+
31
+ truncate : float, default=4.0
32
+ Truncate the filter at this many standard deviations.
33
+ Larger values increase computation time but improve accuracy.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ sigma: float = 1.0,
39
+ mode: Literal["reflect", "constant", "nearest", "mirror", "wrap"] = "reflect",
40
+ pad_value: float = 0.0,
41
+ random_state: Optional[int] = None,
42
+ truncate: float = 4.0,
43
+ ):
44
+ self.sigma = sigma
45
+ self.mode = mode
46
+ self.pad_value = pad_value
47
+ self.random_state = random_state
48
+ self.truncate = truncate
49
+
50
+ def fit(self, X: np.ndarray, y=None) -> "GaussianBroadening":
51
+ """
52
+ Fit the transformer to the data (in this case, only validates input).
53
+
54
+ Parameters
55
+ ----------
56
+ X : array-like of shape (n_samples, n_features)
57
+ Input data to validate.
58
+
59
+ y : None
60
+ Ignored.
61
+
62
+ Returns
63
+ -------
64
+ self : GaussianBroadening
65
+ The fitted transformer.
66
+ """
67
+ X = validate_data(
68
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
69
+ )
70
+
71
+ # Validate sigma parameter
72
+ if not isinstance(self.sigma, (int, float)):
73
+ raise ValueError("sigma must be a number")
74
+ if self.sigma < 0:
75
+ raise ValueError("sigma must be non-negative")
76
+
77
+ # Initialize random number generator
78
+ self._rng = np.random.default_rng(self.random_state)
79
+
80
+ return self
81
+
82
+ def transform(self, X: np.ndarray, y=None) -> np.ndarray:
83
+ """
84
+ Apply Gaussian broadening to the input data.
85
+
86
+ Parameters
87
+ ----------
88
+ X : array-like of shape (n_samples, n_features)
89
+ The data to transform.
90
+
91
+ y : None
92
+ Ignored.
93
+
94
+ Returns
95
+ -------
96
+ X_transformed : ndarray of shape (n_samples, n_features)
97
+ The transformed data with broadened peaks.
98
+ """
99
+ check_is_fitted(self, "n_features_in_")
100
+ X_ = validate_data(
101
+ self,
102
+ X,
103
+ y="no_validation",
104
+ ensure_2d=True,
105
+ copy=True,
106
+ reset=False,
107
+ dtype=np.float64,
108
+ )
109
+
110
+ # Transform each sample
111
+ for i, x in enumerate(X_):
112
+ X_[i] = self._broaden_signal(x)
113
+
114
+ return X_
115
+
116
+ def _broaden_signal(self, x: np.ndarray) -> np.ndarray:
117
+ """
118
+ Apply Gaussian broadening to a single signal.
119
+
120
+ Parameters
121
+ ----------
122
+ x : ndarray of shape (n_features,)
123
+ The input signal to broaden.
124
+
125
+ Returns
126
+ -------
127
+ broadened_signal : ndarray of shape (n_features,)
128
+ The broadened signal.
129
+ """
130
+ # Randomly choose sigma between 0 and max sigma
131
+ sigma = self._rng.uniform(0, self.sigma)
132
+
133
+ # Apply Gaussian filter
134
+ return gaussian_filter1d(
135
+ x, sigma=sigma, mode=self.mode, cval=self.pad_value, truncate=self.truncate
136
+ )
@@ -0,0 +1,7 @@
1
+ from .dmodx import DModX
2
+ from .hotelling_t2 import HotellingT2
3
+ from .q_residuals import QResiduals
4
+ from .leverage import Leverage
5
+ from .studentized_residuals import StudentizedResiduals
6
+
7
+ __all__ = ["DModX", "HotellingT2", "QResiduals", "Leverage", "StudentizedResiduals"]
@@ -0,0 +1,180 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Union, Optional
3
+
4
+ import numpy as np
5
+
6
+ from sklearn.base import BaseEstimator, OutlierMixin
7
+ from sklearn.decomposition._base import _BasePCA
8
+ from sklearn.cross_decomposition._pls import _PLS
9
+ from sklearn.pipeline import Pipeline
10
+ from sklearn.utils.validation import check_is_fitted
11
+
12
+ from ._utils import validate_confidence, validate_and_extract_model
13
+
14
+ ModelTypes = Union[_BasePCA, _PLS]
15
+
16
+
17
+ class _ModelResidualsBase(ABC, BaseEstimator, OutlierMixin):
18
+ """Base class for model outlier calculations.
19
+
20
+ Implements statistical calculations for outlier detection in dimensionality
21
+ reduction models like PCA and PLS.
22
+
23
+ Parameters
24
+ ----------
25
+ model : Union[ModelTypes, Pipeline]
26
+ A fitted _BasePCA or _PLS models or Pipeline ending with such a model
27
+ confidence : float
28
+ Confidence level for statistical calculations (between 0 and 1)
29
+
30
+ Attributes
31
+ ----------
32
+ model_ : ModelTypes
33
+ The fitted model of type _BasePCA or _PLS
34
+
35
+ preprocessing_ : Optional[Pipeline]
36
+ Preprocessing steps before the model
37
+
38
+ n_features_in_ : int
39
+ Number of features in the input data
40
+
41
+ n_components_ : int
42
+ Number of components in the model
43
+
44
+ n_samples_ : int
45
+ Number of samples used to train the model
46
+
47
+ critical_value_ : float
48
+ The calculated critical value for outlier detection
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ model: Union[ModelTypes, Pipeline],
54
+ confidence: float,
55
+ ) -> None:
56
+ (
57
+ self.model_,
58
+ self.preprocessing_,
59
+ self.n_features_in_,
60
+ self.n_components_,
61
+ self.n_samples_,
62
+ ) = validate_and_extract_model(model)
63
+ self.confidence = validate_confidence(confidence)
64
+
65
+ def fit_predict_residuals(
66
+ self, X: np.ndarray, y: Optional[np.ndarray] = None
67
+ ) -> np.ndarray:
68
+ """Fit the model to the input data and calculate the residuals.
69
+
70
+ Parameters
71
+ ----------
72
+ X : array-like of shape (n_samples, n_features)
73
+ Input data
74
+
75
+ y : array-like of shape (n_samples,), default=None
76
+ Target values
77
+
78
+ Returns
79
+ -------
80
+ ndarray of shape (n_samples,)
81
+ The residuals of the model
82
+ """
83
+ self.fit(X, y)
84
+ return self.predict_residuals(X, y, validate=True)
85
+
86
+ @abstractmethod
87
+ def predict_residuals(
88
+ self, X: np.ndarray, y: Optional[np.ndarray], validate: bool
89
+ ) -> np.ndarray:
90
+ """Calculate the residuals of the model.
91
+
92
+ Returns
93
+ -------
94
+ ndarray of shape (n_samples,)
95
+ The residuals of the model
96
+ """
97
+
98
+ @abstractmethod
99
+ def _calculate_critical_value(self, X: Optional[np.ndarray]) -> float:
100
+ """Calculate the critical value for outlier detection.
101
+
102
+ Returns
103
+ -------
104
+ float
105
+ The calculated critical value for outlier detection
106
+ """
107
+
108
+
109
+ class _ModelDiagnosticsBase(ABC):
110
+ """Base class for model diagnostics methods. This does not implement outlier detection algorithms,
111
+ but rather implements methods that are used to assess trained models.
112
+
113
+ Parameters
114
+ ----------
115
+ model : Union[ModelTypes, Pipeline]
116
+ A fitted PCA/PLS model or Pipeline ending with such a model
117
+
118
+ Attributes
119
+ ----------
120
+ model_ : ModelTypes
121
+ The fitted model of type _BasePCA or _PLS
122
+
123
+ preprocessing_ : Optional[Pipeline]
124
+ Preprocessing steps before the model
125
+
126
+ """
127
+
128
+ def __init__(self, model: Union[ModelTypes, Pipeline]):
129
+ self.model_, self.preprocessing_ = self._validate_and_extract_model(model)
130
+
131
+ def _validate_and_extract_model(self, model):
132
+ """Validate and extract the model and preprocessing steps.
133
+
134
+ Parameters
135
+ ----------
136
+ model : Union[ModelTypes, Pipeline]
137
+ A fitted PCA/PLS model or Pipeline ending with such a model
138
+
139
+ Returns
140
+ -------
141
+ Tuple[ModelTypes, Optional[Pipeline]]
142
+ The extracted model and preprocessing steps
143
+
144
+ Raises
145
+ ------
146
+ ValueError
147
+ If the model is not of type _BasePCA or _PLS or a Pipeline ending with one of these types or if the model is not fitted
148
+ """
149
+ if isinstance(model, Pipeline):
150
+ preprocessing = model[:-1]
151
+ model = model[-1]
152
+ else:
153
+ preprocessing = None
154
+
155
+ if isinstance(model, (_BasePCA, _PLS)):
156
+ check_is_fitted(model)
157
+ else:
158
+ raise ValueError(
159
+ "Model not a valid model. Must be of base type _BasePCA or _PLS or a Pipeline ending with one of these types."
160
+ )
161
+ check_is_fitted(model)
162
+ return model, preprocessing
163
+
164
+ @abstractmethod
165
+ def predict(self, X: np.ndarray, y: Optional[np.ndarray]) -> np.ndarray:
166
+ """Predict the output of the model.
167
+
168
+ Parameters
169
+ ----------
170
+ X : array-like of shape (n_samples, n_features)
171
+ Input data
172
+
173
+ y : array-like of shape (n_samples,), default=None
174
+ Target values
175
+
176
+ Returns
177
+ -------
178
+ ndarray of shape (n_samples,)
179
+ Predicted values
180
+ """
@@ -0,0 +1,91 @@
1
+ from typing import Optional, Tuple, Union
2
+
3
+ from sklearn.cross_decomposition._pls import _PLS
4
+ from sklearn.decomposition._base import _BasePCA
5
+ from sklearn.pipeline import Pipeline
6
+ from sklearn.utils.validation import check_is_fitted
7
+
8
+ ModelTypes = Union[_BasePCA, _PLS]
9
+
10
+
11
+ def get_model_parameters(model: ModelTypes) -> Tuple[int, int, int]:
12
+ """
13
+ Get the number of features, components and samples from a model with PLS or PCA. types.
14
+
15
+ Parameters
16
+ ----------
17
+ model : ModelType
18
+ A fitted model of type _BasePCA or _PLS
19
+
20
+ Returns
21
+ -------
22
+ Tuple[int, int, int]
23
+ The number of features, components and samples in the model
24
+ """
25
+ if isinstance(model, _BasePCA):
26
+ return model.n_features_in_, model.n_components_, model.n_samples_
27
+ elif isinstance(model, _PLS):
28
+ return model.n_features_in_, model.n_components, len(model.x_scores_)
29
+ else:
30
+ raise ValueError(
31
+ "Model not a valid model. Must be of base type _BasePCA or _PLS or a Pipeline ending with one of these types."
32
+ )
33
+
34
+
35
+ def validate_confidence(confidence: float) -> float:
36
+ """Validate parameters using sklearn conventions.
37
+
38
+ Parameters
39
+ ----------
40
+ confidence : float
41
+ Confidence level for statistical calculations (between 0 and 1)
42
+
43
+ Returns
44
+ -------
45
+ float
46
+ The validated confidence level
47
+
48
+ Raises
49
+ ------
50
+ ValueError
51
+ If confidence is not between 0 and 1
52
+ """
53
+ if not 0 < confidence < 1:
54
+ raise ValueError("Confidence must be between 0 and 1")
55
+ return confidence
56
+
57
+
58
+ def validate_and_extract_model(
59
+ model: Union[ModelTypes, Pipeline],
60
+ ) -> Tuple[ModelTypes, Optional[Pipeline], int, int, int]:
61
+ """Validate and extract the model and preprocessing steps.
62
+
63
+ Parameters
64
+ ----------
65
+ model : Union[ModelTypes, Pipeline]
66
+ A fitted PCA/PLS model or Pipeline ending with such a model
67
+
68
+ Returns
69
+ -------
70
+ Tuple[ModelTypes, Optional[Pipeline]]
71
+ The extracted model and preprocessing steps
72
+
73
+ Raises
74
+ ------
75
+ ValueError
76
+ If the model is not of type _BasePCA or _PLS or a Pipeline ending with one of these types or if the model is not fitted
77
+ """
78
+ if isinstance(model, Pipeline):
79
+ preprocessing = model[:-1]
80
+ model = model[-1]
81
+ else:
82
+ preprocessing = None
83
+
84
+ if not isinstance(model, (_BasePCA, _PLS)):
85
+ raise ValueError(
86
+ "Model not a valid model. Must be of base type _BasePCA or _PLS or a Pipeline ending with one of these types."
87
+ )
88
+
89
+ check_is_fitted(model)
90
+ n_features_in, n_components, n_samples = get_model_parameters(model)
91
+ return model, preprocessing, n_features_in, n_components, n_samples
@@ -0,0 +1,146 @@
1
+ from typing import Optional, Union
2
+ import numpy as np
3
+
4
+ from sklearn.pipeline import Pipeline
5
+ from sklearn.utils.validation import validate_data, check_is_fitted
6
+ from scipy.stats import f as f_distribution
7
+
8
+
9
+ from ._base import _ModelResidualsBase, ModelTypes
10
+
11
+
12
+ class DModX(_ModelResidualsBase):
13
+ """Calculate Distance to Model (DModX) statistics.
14
+
15
+ DModX measures the distance between an observation and the model plane
16
+ in the X-space, useful for detecting outliers.
17
+
18
+ Parameters
19
+ ----------
20
+ model : Union[ModelType, Pipeline]
21
+ A fitted PCA/PLS model or Pipeline ending with such a model
22
+
23
+ confidence : float, default=0.95
24
+ Confidence level for statistical calculations (between 0 and 1)
25
+
26
+ Attributes
27
+ ----------
28
+ model_ : ModelType
29
+ The fitted model of type _BasePCA or _PLS
30
+
31
+ preprocessing_ : Optional[Pipeline]
32
+ Preprocessing steps before the model
33
+
34
+ n_features_in_ : int
35
+ Number of features in the input data
36
+
37
+ n_components_ : int
38
+ Number of components in the model
39
+
40
+ n_samples_ : int
41
+ Number of samples used to train the model
42
+
43
+ critical_value_ : float
44
+ The calculated critical value for outlier detection
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ model: Union[ModelTypes, Pipeline],
50
+ confidence: float = 0.95,
51
+ ) -> None:
52
+ super().__init__(model, confidence)
53
+
54
+ def fit(self, X: np.ndarray, y: Optional[np.ndarray] = None) -> "DModX":
55
+ """
56
+ Fit the model to the input data.
57
+
58
+ This step calculates the critical value for the outlier detection. In the DmodX method,
59
+ the critical value is not depend on the input data but on the model parameters.
60
+ """
61
+ X = validate_data(
62
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
63
+ )
64
+
65
+ self.critical_value_ = self._calculate_critical_value()
66
+ return self
67
+
68
+ def predict(self, X: np.ndarray) -> np.ndarray:
69
+ """Identify outliers in the input data.
70
+
71
+ Parameters
72
+ ----------
73
+ X : array-like of shape (n_samples, n_features)
74
+ Input data
75
+
76
+ Returns
77
+ -------
78
+ ndarray of shape (n_samples,)
79
+ Boolean array indicating outliers
80
+ """
81
+ # Check the estimator has been fitted
82
+ check_is_fitted(self, ["critical_value_"])
83
+
84
+ # Validate the input data
85
+ X = validate_data(
86
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
87
+ )
88
+
89
+ # Calculate outliers based on the DModX statistics
90
+ dmodx_values = self.predict_residuals(X, validate=False)
91
+ return np.where(dmodx_values > self.critical_value_, -1, 1)
92
+
93
+ def predict_residuals(
94
+ self, X: np.ndarray, y: Optional[np.ndarray] = None, validate: bool = True
95
+ ) -> np.ndarray:
96
+ """Calculate DModX statistics for input data.
97
+
98
+ Parameters
99
+ ----------
100
+ X : array-like of shape (n_samples, n_features)
101
+ Input data
102
+
103
+ validate : bool, default=True
104
+ Whether to validate the input data
105
+
106
+ Returns
107
+ -------
108
+ ndarray of shape (n_samples,)
109
+ DModX statistics for each sample
110
+ """
111
+ # Check the estimator has been fitted
112
+ check_is_fitted(self, ["critical_value_"])
113
+
114
+ # Validate the input data
115
+ if validate:
116
+ X = validate_data(
117
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
118
+ )
119
+
120
+ # Apply preprocessing if available
121
+ if self.preprocessing_:
122
+ X = self.preprocessing_.transform(X)
123
+
124
+ # Calculate the DModX statistics
125
+ X_transformed = self.model_.transform(X)
126
+ X_reconstructed = self.model_.inverse_transform(X_transformed)
127
+ squared_errors = np.sum((X - X_reconstructed) ** 2, axis=1)
128
+
129
+ return np.sqrt(squared_errors / (self.n_features_in_ - self.n_components_))
130
+
131
+ def _calculate_critical_value(self, X: Optional[np.ndarray] = None) -> float:
132
+ """Calculate F-distribution based critical value.
133
+
134
+ Returns
135
+ -------
136
+ float
137
+ The critical value for outlier detection
138
+ """
139
+
140
+ dof_numerator = self.n_features_in_ - self.n_components_
141
+ dof_denominator = self.n_features_in_ - self.n_components_ - 1
142
+
143
+ upper_control_limit = f_distribution.ppf(
144
+ self.confidence, dof_numerator, dof_denominator
145
+ )
146
+ return np.sqrt(upper_control_limit)