chemotools 0.1.8__py3-none-any.whl → 0.1.10__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.
@@ -0,0 +1,155 @@
1
+ from typing import Optional, Union
2
+ import numpy as np
3
+
4
+ from sklearn.cross_decomposition._pls import _PLS
5
+ from sklearn.decomposition._base import _BasePCA
6
+ from sklearn.pipeline import Pipeline
7
+ from sklearn.utils.validation import validate_data, check_is_fitted
8
+ from scipy.stats import f as f_distribution
9
+
10
+ from ._base import _ModelResidualsBase, ModelTypes
11
+
12
+
13
+ class HotellingT2(_ModelResidualsBase):
14
+ """
15
+ Calculate Hotelling's T-squared statistics for PCA or PLS like models.
16
+
17
+ Parameters
18
+ ----------
19
+ model : Union[ModelType, Pipeline]
20
+ A fitted PCA/PLS model or Pipeline ending with such a model
21
+
22
+ confidence : float, default=0.95
23
+ Confidence level for statistical calculations (between 0 and 1)
24
+
25
+ Attributes
26
+ ----------
27
+ model_ : ModelType
28
+ The fitted model of type _BasePCA or _PLS
29
+
30
+ preprocessing_ : Optional[Pipeline]
31
+ Preprocessing steps before the model
32
+
33
+ n_features_in_ : int
34
+ Number of features in the input data
35
+
36
+ n_components_ : int
37
+ Number of components in the model
38
+
39
+ n_samples_ : int
40
+ Number of samples used to train the model
41
+
42
+ critical_value_ : float
43
+ The calculated critical value for outlier detection
44
+
45
+ References
46
+ ----------
47
+ Johan A. Westerhuis, Stephen P. Gurden, Age K. Smilde (2001) Generalized contribution plots in multivariate statistical process
48
+ monitoring Chemometrics and Intelligent Laboratory Systems 51 2000 95–114
49
+ """
50
+
51
+ def __init__(
52
+ self, model: Union[ModelTypes, Pipeline], confidence: float = 0.95
53
+ ) -> None:
54
+ super().__init__(model, confidence)
55
+
56
+ def fit(self, X: np.ndarray, y: Optional[np.ndarray] = None) -> "HotellingT2":
57
+ """
58
+ Fit the model to the input data.
59
+
60
+ This step calculates the critical value for the outlier detection. In the DmodX method,
61
+ the critical value is not depend on the input data but on the model parameters.
62
+ """
63
+ X = validate_data(
64
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
65
+ )
66
+
67
+ self.critical_value_ = self._calculate_critical_value()
68
+ return self
69
+
70
+ def predict(self, X: np.ndarray) -> np.ndarray:
71
+ """Identify outliers in the input data.
72
+
73
+ Parameters
74
+ ----------
75
+ X : array-like of shape (n_samples, n_features)
76
+ Input data
77
+
78
+ Returns
79
+ -------
80
+ ndarray of shape (n_samples,)
81
+ Boolean array indicating outliers
82
+ """
83
+ # Check the estimator has been fitted
84
+ check_is_fitted(self, ["critical_value_"])
85
+
86
+ # Validate the input data
87
+ X = validate_data(
88
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
89
+ )
90
+
91
+ # Calculate the Hotelling's T-squared statistics
92
+ hotelling_t2_values = self.predict_residuals(X, y=None, validate=False)
93
+ return np.where(hotelling_t2_values > self.critical_value_, -1, 1)
94
+
95
+ def predict_residuals(
96
+ self, X: np.ndarray, y: Optional[np.ndarray], validate: bool = True
97
+ ) -> np.ndarray:
98
+ """Calculate Hotelling's T-squared statistics for input data.
99
+
100
+ Parameters
101
+ ----------
102
+ X : array-like of shape (n_samples, n_features)
103
+ Input data
104
+
105
+ Returns
106
+ -------
107
+ ndarray of shape (n_samples,)
108
+ Hotellin's T-squared statistics for each sample
109
+ """
110
+ # Check the estimator has been fitted
111
+ check_is_fitted(self, ["critical_value_"])
112
+
113
+ # Validate the input data
114
+ if validate:
115
+ X = validate_data(
116
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
117
+ )
118
+
119
+ # Apply preprocessing steps
120
+ if self.preprocessing_:
121
+ X = self.preprocessing_.transform(X)
122
+
123
+ # Calculate the Hotelling's T-squared statistics
124
+ if isinstance(self.model_, _BasePCA):
125
+ # For PCA-like models
126
+ variances = self.model_.explained_variance_
127
+
128
+ if isinstance(self.model_, _PLS):
129
+ # For PLS-like models
130
+ variances = np.var(self.model_.x_scores_, axis=0)
131
+
132
+ # Equivalent to X @ model.components_.T for _BasePCA and X @ model.x_rotations_ for _PLS
133
+ X_transformed = self.model_.transform(X)
134
+
135
+ return np.sum((X_transformed**2) / variances, axis=1)
136
+
137
+ def _calculate_critical_value(self, X: Optional[np.ndarray] = None) -> float:
138
+ """
139
+ Calculate the critical value for the Hotelling's T-squared statistics.
140
+
141
+ Returns
142
+ -------
143
+ float
144
+ The critical value for the Hotelling's T-squared statistics
145
+ """
146
+
147
+ critical_value = f_distribution.ppf(
148
+ self.confidence, self.n_components_, self.n_samples_ - self.n_components_
149
+ )
150
+ return (
151
+ critical_value
152
+ * self.n_components_
153
+ * (self.n_samples_ - 1)
154
+ / (self.n_samples_ - self.n_components_)
155
+ )
@@ -0,0 +1,150 @@
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
+
7
+
8
+ from ._base import _ModelResidualsBase, ModelTypes
9
+
10
+
11
+ class Leverage(_ModelResidualsBase):
12
+ """
13
+ Calculate the leverage of the training samples on the latent space of a PCA or PLS models.
14
+ This method allows to detect datapoints with high leverage in the model.
15
+
16
+ Parameters
17
+ ----------
18
+ model : Union[ModelType, Pipeline]
19
+ A fitted PCA/PLS model or Pipeline ending with such a model
20
+
21
+ Attributes
22
+ ----------
23
+ model_ : ModelType
24
+ The fitted model of type _BasePCA or _PLS
25
+
26
+ preprocessing_ : Optional[Pipeline]
27
+ Preprocessing steps before the model
28
+
29
+ References
30
+ ----------
31
+
32
+ """
33
+
34
+ def __init__(
35
+ self, model: Union[ModelTypes, Pipeline], confidence: float = 0.95
36
+ ) -> None:
37
+ super().__init__(model, confidence)
38
+
39
+ def fit(self, X: np.ndarray, y: Optional[np.ndarray] = None) -> "Leverage":
40
+ """
41
+ Fit the model to the input data.
42
+
43
+ Parameters
44
+
45
+ """
46
+ X = validate_data(
47
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
48
+ )
49
+
50
+ if self.preprocessing_:
51
+ X = self.preprocessing_.fit_transform(X)
52
+
53
+ # Compute the critical threshold
54
+ self.critical_value_ = self._calculate_critical_value(X)
55
+
56
+ return self
57
+
58
+ def predict(self, X: np.ndarray, y: Optional[np.ndarray] = None) -> np.ndarray:
59
+ """Calculate Leverage for training data on the model.
60
+
61
+ Parameters
62
+ ----------
63
+ X : array-like of shape (n_samples, n_features)
64
+ Input data
65
+
66
+ Returns
67
+ -------
68
+ ndarray of shape (n_samples,)
69
+ Bool with samples with a leverage above the critical value
70
+ """
71
+ # Check the estimator has been fitted
72
+ check_is_fitted(self, ["critical_value_"])
73
+
74
+ # Validate the input data
75
+ X = validate_data(
76
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
77
+ )
78
+
79
+ # Preprocess the data
80
+ if self.preprocessing_:
81
+ X = self.preprocessing_.transform(X)
82
+
83
+ # Calculate outliers based on samples with too high leverage
84
+ leverage = calculate_leverage(self.model_, X)
85
+ return np.where(leverage > self.critical_value_, -1, 1)
86
+
87
+ def predict_residuals(
88
+ self, X: np.ndarray, y: Optional[np.ndarray], validate: bool = True
89
+ ) -> np.ndarray:
90
+ """Calculate the leverage of the samples.
91
+
92
+ Parameters
93
+ ----------
94
+ X : array-like of shape (n_samples, n_features)
95
+ Input data
96
+
97
+ Returns
98
+ -------
99
+ np.ndarray
100
+ Leverage of the samples
101
+ """
102
+ # Check the estimator has been fitted
103
+ check_is_fitted(self, ["critical_value_"])
104
+
105
+ # Validate the input data
106
+ if validate:
107
+ X = validate_data(self, X, ensure_2d=True, dtype=np.float64)
108
+
109
+ # Apply preprocessing if available
110
+ if self.preprocessing_:
111
+ X = self.preprocessing_.transform(X)
112
+
113
+ # Calculate the leverage
114
+ return calculate_leverage(self.model_, X)
115
+
116
+ def _calculate_critical_value(self, X: Optional[np.ndarray]) -> float:
117
+ """Calculate the critical value for outlier detection using the percentile outlier method."""
118
+
119
+ # Calculate the leverage of the samples
120
+ leverage = calculate_leverage(self.model_, X)
121
+
122
+ # Calculate the critical value
123
+ return np.percentile(leverage, self.confidence * 100)
124
+
125
+
126
+ def calculate_leverage(model: ModelTypes, X: Optional[np.ndarray]) -> np.ndarray:
127
+ """
128
+ Calculate the leverage of the training samples in a PLS/PCA-like model.
129
+
130
+ Parameters
131
+ ----------
132
+ model : Union[_BasePCA, _PLS]
133
+ A fitted PCA/PLS model
134
+
135
+ X : np.ndarray
136
+ Preprocessed input data
137
+
138
+ Returns
139
+ -------
140
+ np.ndarray
141
+ Leverage of the samples
142
+ """
143
+
144
+ X_transformed = model.transform(X)
145
+
146
+ X_hat = (
147
+ X_transformed @ np.linalg.inv(X_transformed.T @ X_transformed) @ X_transformed.T
148
+ )
149
+
150
+ return np.diag(X_hat)
@@ -0,0 +1,225 @@
1
+ from typing import Optional, Literal, Union
2
+
3
+ import numpy as np
4
+
5
+ from scipy.stats import norm, chi2
6
+ from sklearn.pipeline import Pipeline
7
+ from sklearn.utils.validation import validate_data, check_is_fitted
8
+
9
+ from ._base import _ModelResidualsBase, ModelTypes
10
+
11
+
12
+ class QResiduals(_ModelResidualsBase):
13
+ """
14
+ Calculate Q residuals (Squared Prediction Error - SPE) for PCA or PLS models.
15
+
16
+ Parameters
17
+ ----------
18
+ model : Union[ModelType, Pipeline]
19
+ A fitted PCA/PLS model or Pipeline ending with such a model.
20
+
21
+ confidence : float, default=0.95
22
+ Confidence level for statistical calculations (between 0 and 1).
23
+
24
+ method : str, default="chi-square"
25
+ The method used to compute the confidence threshold for Q residuals.
26
+ Options:
27
+ - "chi-square" : Uses mean and standard deviation to approximate Q residuals threshold.
28
+ - "jackson-mudholkar" : Uses eigenvalue-based analytical approximation.
29
+ - "percentile" : Uses empirical percentile threshold.
30
+
31
+ Attributes
32
+ ----------
33
+ model_ : ModelType
34
+ The fitted model of type _BasePCA or _PLS.
35
+
36
+ preprocessing_ : Optional[Pipeline]
37
+ Preprocessing steps before the model.
38
+
39
+ n_features_in_ : int
40
+ Number of features in the input data.
41
+
42
+ n_components_ : int
43
+ Number of components in the model.
44
+
45
+ n_samples_ : int
46
+ Number of samples used to train the model.
47
+
48
+ critical_value_ : float
49
+ The calculated critical value for outlier detection.
50
+
51
+ References
52
+ ----------
53
+ Johan A. Westerhuis, Stephen P. Gurden, Age K. Smilde (2001) Generalized contribution plots in multivariate statistical process
54
+ monitoring Chemometrics and Intelligent Laboratory Systems 51 2000 95–114
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ model: Union[ModelTypes, Pipeline],
60
+ confidence: float = 0.95,
61
+ method: Literal["chi-square", "jackson-mudholkar", "percentile"] = "percentile",
62
+ ) -> None:
63
+ self.method = method
64
+ super().__init__(model, confidence)
65
+
66
+ def fit(self, X: np.ndarray, y: Optional[np.ndarray] = None) -> "QResiduals":
67
+ """
68
+ Fit the Q Residuals model by computing residuals from the training set.
69
+
70
+ Parameters
71
+ ----------
72
+ X : array-like of shape (n_samples, n_features)
73
+ Training data.
74
+
75
+ Returns
76
+ -------
77
+ self : object
78
+ Fitted instance of QResiduals.
79
+ """
80
+ X = validate_data(self, X, ensure_2d=True, dtype=np.float64)
81
+
82
+ if self.preprocessing_:
83
+ X = self.preprocessing_.fit_transform(X)
84
+
85
+ # Compute the critical threshold using the chosen method
86
+ self.critical_value_ = self._calculate_critical_value(X)
87
+
88
+ return self
89
+
90
+ def predict(self, X: np.ndarray) -> np.ndarray:
91
+ """Identify outliers in the input data based on Q residuals threshold.
92
+
93
+ Parameters
94
+ ----------
95
+ X : array-like of shape (n_samples, n_features)
96
+ Input data.
97
+
98
+ Returns
99
+ -------
100
+ ndarray of shape (n_samples,)
101
+ Boolean array indicating outliers (-1 for outliers, 1 for normal data).
102
+ """
103
+ # Check the estimator has been fitted
104
+ check_is_fitted(self, ["critical_value_"])
105
+
106
+ # Validate the input data
107
+ X = validate_data(
108
+ self, X, y="no_validation", ensure_2d=True, reset=True, dtype=np.float64
109
+ )
110
+
111
+ # Calculate outliers based on the Q residuals
112
+ Q_residuals = self.predict_residuals(X, validate=False)
113
+ return np.where(Q_residuals > self.critical_value_, -1, 1)
114
+
115
+ def predict_residuals(
116
+ self, X: np.ndarray, y: Optional[np.ndarray] = None, validate: bool = True
117
+ ) -> np.ndarray:
118
+ """Calculate Q residuals (Squared Prediction Error - SPE) for input data.
119
+
120
+ Parameters
121
+ ----------
122
+ X : array-like of shape (n_samples, n_features)
123
+ Input data.
124
+
125
+ validate : bool, default=True
126
+ Whether to validate the input data.
127
+
128
+ Returns
129
+ -------
130
+ ndarray of shape (n_samples,)
131
+ Q residuals for each sample.
132
+ """
133
+ # Check the estimator has been fitted
134
+ check_is_fitted(self, ["critical_value_"])
135
+
136
+ # Validate the input data
137
+ if validate:
138
+ X = validate_data(self, X, ensure_2d=True, dtype=np.float64)
139
+
140
+ # Apply preprocessing if available
141
+ if self.preprocessing_:
142
+ X = self.preprocessing_.transform(X)
143
+
144
+ # Compute reconstruction error (Q residuals)
145
+ X_transformed = self.model_.transform(X)
146
+ X_reconstructed = self.model_.inverse_transform(X_transformed)
147
+ Q_residuals = np.sum((X - X_reconstructed) ** 2, axis=1)
148
+
149
+ return Q_residuals
150
+
151
+ def _calculate_critical_value(
152
+ self,
153
+ X: Optional[np.ndarray] = None,
154
+ ) -> float:
155
+ """Calculate the critical value for outlier detection.
156
+
157
+ Parameters
158
+ ----------
159
+ X : array-like of shape (n_samples, n_features)
160
+ Input data.
161
+
162
+ X_reconstructed : array-like of shape (n_samples, n_features)
163
+ Reconstructed input data.
164
+
165
+ method : str Literal["chi-square", "jackson-mudholkar", "percentile"]
166
+ The method used to compute the confidence threshold for Q residuals.
167
+
168
+ Returns
169
+ -------
170
+ float
171
+ The calculated critical value for outlier detection.
172
+
173
+ """
174
+ # Compute Q residuals for training data
175
+ X_transformed = self.model_.transform(X)
176
+ X_reconstructed = self.model_.inverse_transform(X_transformed)
177
+ residuals = X - X_reconstructed
178
+
179
+ if self.method == "chi-square":
180
+ return self._chi_square_threshold(residuals)
181
+ elif self.method == "jackson-mudholkar":
182
+ return self._jackson_mudholkar_threshold(residuals)
183
+ elif self.method == "percentile":
184
+ Q_residuals = np.sum((residuals) ** 2, axis=1)
185
+ return self._percentile_threshold(Q_residuals)
186
+ else:
187
+ raise ValueError(
188
+ "Invalid method. Choose from 'chi-square', 'jackson-mudholkar', or 'percentile'."
189
+ )
190
+
191
+ def _chi_square_threshold(self, residuals: np.ndarray) -> float:
192
+ """Compute Q residual threshold using Chi-Square Approximation."""
193
+ eigenvalues = np.linalg.trace(np.cov(residuals.T))
194
+
195
+ theta_1 = np.sum(eigenvalues)
196
+ theta_2 = np.sum(eigenvalues**2)
197
+ # Degrees of freedom approximation
198
+ g = theta_2 / theta_1
199
+ h = (2 * theta_1**2) / theta_2
200
+
201
+ # Compute chi-square critical value at given confidence level
202
+ chi_critical = chi2.ppf(self.confidence, df=h)
203
+
204
+ # Compute final Q residual threshold
205
+ return g * chi_critical
206
+
207
+ def _jackson_mudholkar_threshold(self, residuals: np.ndarray) -> float:
208
+ """Compute Q residual threshold using Jackson & Mudholkar’s analytical method."""
209
+
210
+ eigenvalues = np.linalg.trace(np.cov(residuals.T))
211
+ theta_1 = np.sum(eigenvalues)
212
+ theta_2 = np.sum(eigenvalues**2)
213
+ theta_3 = np.sum(eigenvalues**3)
214
+ z_alpha = norm.ppf(self.confidence)
215
+
216
+ h0 = 1 - (2 * theta_1 * theta_3) / (3 * theta_2**2)
217
+
218
+ term1 = theta_2 * h0 * (1 - h0) / theta_1**2
219
+ term2 = np.sqrt(z_alpha * 2 * theta_2 * h0**2) / theta_1
220
+
221
+ return theta_1 * (1 - term1 + term2) ** (1 / h0)
222
+
223
+ def _percentile_threshold(self, Q_residuals: np.ndarray) -> float:
224
+ """Compute Q residual threshold using the empirical percentile method."""
225
+ return np.percentile(Q_residuals, self.confidence * 100)