pyEllipse 0.1.2__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.
- pyellipse-0.1.2/LICENSE +21 -0
- pyellipse-0.1.2/PKG-INFO +313 -0
- pyellipse-0.1.2/README.md +276 -0
- pyellipse-0.1.2/pyEllipse/__init__.py +31 -0
- pyellipse-0.1.2/pyEllipse/confidence_ellipse.py +248 -0
- pyellipse-0.1.2/pyEllipse/hotelling_coordinates.py +164 -0
- pyellipse-0.1.2/pyEllipse/hotelling_parameters.py +221 -0
- pyellipse-0.1.2/pyproject.toml +125 -0
pyellipse-0.1.2/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Christian L. Goueguel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pyellipse-0.1.2/PKG-INFO
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyEllipse
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Tools for creating and analyzing confidence ellipses, including Hotelling's T-squared ellipses for multivariate statistical analysis and data visualization.
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: statistics,confidence-ellipse,hotelling,multivariate,visualization
|
|
8
|
+
Author: Christian L. Goueguel
|
|
9
|
+
Author-email: christian.goueguel@gmail.com
|
|
10
|
+
Requires-Python: >=3.9,<3.13
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
22
|
+
Provides-Extra: all
|
|
23
|
+
Provides-Extra: plotting
|
|
24
|
+
Requires-Dist: matplotlib (>=3.7.0,<4.0.0)
|
|
25
|
+
Requires-Dist: numpy (>=1.24.0,<2.0.0)
|
|
26
|
+
Requires-Dist: pandas (>=2.0.0,<3.0.0)
|
|
27
|
+
Requires-Dist: plotly (>=5.14.0,<6.0.0) ; extra == "plotting" or extra == "all"
|
|
28
|
+
Requires-Dist: scikit-learn (>=1.3.0,<2.0.0)
|
|
29
|
+
Requires-Dist: scipy (>=1.11.0,<2.0.0)
|
|
30
|
+
Requires-Dist: seaborn (>=0.12.0,<0.13.0) ; extra == "plotting" or extra == "all"
|
|
31
|
+
Project-URL: Bug Tracker, https://github.com/ChristianGoueguel/pyEllipse/issues
|
|
32
|
+
Project-URL: Documentation, https://christiangoueguel.github.io/pyEllipse
|
|
33
|
+
Project-URL: Homepage, https://github.com/ChristianGoueguel/pyEllipse
|
|
34
|
+
Project-URL: Repository, https://github.com/ChristianGoueguel/pyEllipse
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# pyEllipse
|
|
38
|
+
|
|
39
|
+
A Python package for computing Hotelling's T² statistics and generating confidence ellipse/ellipsoid coordinates for multivariate data analysis and visualization.
|
|
40
|
+
|
|
41
|
+
[](https://badge.fury.io/py/pyellipse)
|
|
42
|
+
[](https://pypi.org/project/pyellipse/)
|
|
43
|
+
[](https://github.com/ChristianGoueguel/pyEllipse/blob/main/LICENSE)
|
|
44
|
+

|
|
45
|
+

|
|
46
|
+

|
|
47
|
+

|
|
48
|
+

|
|
49
|
+

|
|
50
|
+
|
|
51
|
+
## Overview
|
|
52
|
+
|
|
53
|
+
`pyEllipse` provides three main functions for analyzing multivariate data:
|
|
54
|
+
|
|
55
|
+
1. __`hotelling_parameters`__ - Calculate Hotelling's T² statistics and ellipse parameters
|
|
56
|
+
2. __`hotelling_coordinates`__ - Generate Hotelling's ellipse/ellipsoid coordinates from PCA/PLS scores
|
|
57
|
+
3. __`confidence_ellipse`__ - Compute confidence ellipse/ellipsoid coordinates from raw data with grouping support
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install pyEllipse
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Usage Examples
|
|
66
|
+
|
|
67
|
+
### Example 1: Hotelling's T² statistic and confidence ellipse from PCA Scores
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import numpy as np
|
|
71
|
+
import pandas as pd
|
|
72
|
+
import matplotlib.pyplot as plt
|
|
73
|
+
plt.style.use('bmh')
|
|
74
|
+
from mpl_toolkits.mplot3d import Axes3D
|
|
75
|
+
from sklearn.preprocessing import StandardScaler
|
|
76
|
+
from sklearn.decomposition import PCA
|
|
77
|
+
from pathlib import Path
|
|
78
|
+
from pyEllipse import hotelling_parameters, hotelling_coordinates, confidence_ellipse
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
def load_wine_data():
|
|
83
|
+
"""Load wine dataset and add cultivar labels"""
|
|
84
|
+
wine_df = pd.read_csv('data/wine.csv')
|
|
85
|
+
|
|
86
|
+
# Add cultivar labels based on standard Wine dataset structure
|
|
87
|
+
cultivar = []
|
|
88
|
+
for i in range(len(wine_df)):
|
|
89
|
+
if i < 59:
|
|
90
|
+
cultivar.append('Cultivar 1')
|
|
91
|
+
elif i < 130:
|
|
92
|
+
cultivar.append('Cultivar 2')
|
|
93
|
+
else:
|
|
94
|
+
cultivar.append('Cultivar 3')
|
|
95
|
+
|
|
96
|
+
wine_df['Cultivar'] = cultivar
|
|
97
|
+
return wine_df
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
wine_df = load_wine_data()
|
|
102
|
+
X = wine_df.drop('Cultivar', axis=1)
|
|
103
|
+
y = wine_df['Cultivar']
|
|
104
|
+
|
|
105
|
+
# Perform PCA
|
|
106
|
+
pca = PCA()
|
|
107
|
+
SS = StandardScaler()
|
|
108
|
+
X = SS.fit_transform(X)
|
|
109
|
+
pca_scores = pca.fit_transform(X)
|
|
110
|
+
explained_var = pca.explained_variance_ratio_
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
plt.style.use('bmh')
|
|
115
|
+
# Calculate T² statistics
|
|
116
|
+
results = hotelling_parameters(pca_scores, k=2)
|
|
117
|
+
t2 = results['Tsquared'].values
|
|
118
|
+
|
|
119
|
+
# Generate ellipse coordinates for plotting
|
|
120
|
+
ellipse_95 = hotelling_coordinates(pca_scores, pcx=1, pcy=2, conf_limit=0.95)
|
|
121
|
+
ellipse_99 = hotelling_coordinates(pca_scores, pcx=1, pcy=2, conf_limit=0.99)
|
|
122
|
+
|
|
123
|
+
# Plot the PCA scores with Hotelling's T² ellipse
|
|
124
|
+
plt.figure(figsize=(8, 6))
|
|
125
|
+
scatter = plt.scatter(
|
|
126
|
+
pca_scores[:, 0], pca_scores[:, 1],
|
|
127
|
+
c=t2, cmap='jet', alpha=0.85, s=70, label='Wine samples'
|
|
128
|
+
)
|
|
129
|
+
cbar = plt.colorbar(scatter)
|
|
130
|
+
cbar.set_label('Hotelling T² Statistic', rotation=270, labelpad=20)
|
|
131
|
+
|
|
132
|
+
plt.plot(ellipse_95['x'], ellipse_95['y'], 'r-', linewidth=1, label='95% Confidence level')
|
|
133
|
+
plt.plot(ellipse_99['x'], ellipse_99['y'], 'k-', linewidth=1, label='99% Confidence level')
|
|
134
|
+
plt.xlim(-1000, 1000)
|
|
135
|
+
plt.ylim(-50, 60)
|
|
136
|
+
plt.xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
137
|
+
plt.ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
138
|
+
plt.title("Hotelling's T² Ellipse from PCA Scores", fontsize=16, pad=10, fontweight='bold')
|
|
139
|
+
plt.legend(
|
|
140
|
+
loc='upper left', fontsize=10, frameon=True, framealpha=0.9,
|
|
141
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
142
|
+
)
|
|
143
|
+
plt.show()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+

|
|
147
|
+
|
|
148
|
+
### Example 2: Grouped Confidence Ellipses
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
wine_df['PC1'] = pca_scores[:, 0]
|
|
152
|
+
wine_df['PC2'] = pca_scores[:, 1]
|
|
153
|
+
|
|
154
|
+
colors = ['red', 'blue', 'green']
|
|
155
|
+
cultivars = wine_df['Cultivar'].unique()
|
|
156
|
+
color_map = {cultivar: color for cultivar, color in zip(cultivars, colors)}
|
|
157
|
+
point_colors = wine_df['Cultivar'].map(color_map)
|
|
158
|
+
|
|
159
|
+
# Plott PCA scores with confidence ellipses for each cultivar
|
|
160
|
+
plt.figure(figsize=(8, 6))
|
|
161
|
+
|
|
162
|
+
for i, cultivar in enumerate(cultivars):
|
|
163
|
+
mask = wine_df['Cultivar'] == cultivar
|
|
164
|
+
plt.scatter(
|
|
165
|
+
wine_df.loc[mask, 'PC1'], wine_df.loc[mask, 'PC2'], # type: ignore
|
|
166
|
+
c=colors[i], alpha=0.6, s=70, label=cultivar
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
ellipse_coords = confidence_ellipse(
|
|
170
|
+
data=wine_df,
|
|
171
|
+
x='PC1',
|
|
172
|
+
y='PC2',
|
|
173
|
+
group_by='Cultivar',
|
|
174
|
+
conf_level=0.95,
|
|
175
|
+
robust=True,
|
|
176
|
+
distribution='hotelling'
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
for i, cultivar in enumerate(cultivars):
|
|
180
|
+
ellipse_data = ellipse_coords[ellipse_coords['Cultivar'] == cultivar]
|
|
181
|
+
plt.plot(
|
|
182
|
+
ellipse_data['x'], ellipse_data['y'],
|
|
183
|
+
color=colors[i], linewidth=1, linestyle='-', label=f'{cultivar} (95% CI)'
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
plt.xlim(-1000, 1000)
|
|
187
|
+
plt.ylim(-50, 60)
|
|
188
|
+
plt.xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
189
|
+
plt.ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
190
|
+
plt.title("PCA Scores with Cultivar Group Confidence Ellipses", fontsize=16, pad=10, fontweight='bold')
|
|
191
|
+
plt.legend(
|
|
192
|
+
loc='upper left', fontsize=10, frameon=True, framealpha=0.9,
|
|
193
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
194
|
+
)
|
|
195
|
+
plt.show()
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+

|
|
199
|
+
|
|
200
|
+
### Example 3: Grouped 3D Confidence Ellipsoids
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
wine_df['PC1'] = pca_scores[:, 0]
|
|
204
|
+
wine_df['PC2'] = pca_scores[:, 1]
|
|
205
|
+
wine_df['PC3'] = pca_scores[:, 2]
|
|
206
|
+
|
|
207
|
+
colors = ['red', 'blue', 'green']
|
|
208
|
+
light_colors = ['lightcoral', 'lightblue', 'lightgreen']
|
|
209
|
+
cultivars = wine_df['Cultivar'].unique()
|
|
210
|
+
|
|
211
|
+
ellipse_coords = confidence_ellipse(
|
|
212
|
+
data=wine_df,
|
|
213
|
+
x='PC1',
|
|
214
|
+
y='PC2',
|
|
215
|
+
z='PC3',
|
|
216
|
+
group_by='Cultivar',
|
|
217
|
+
conf_level=0.95,
|
|
218
|
+
robust=True,
|
|
219
|
+
distribution='hotelling'
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
fig = plt.figure(figsize=(10, 6), facecolor='white')
|
|
223
|
+
ax = fig.add_subplot(111, projection='3d', facecolor='white')
|
|
224
|
+
|
|
225
|
+
for i, cultivar in enumerate(cultivars):
|
|
226
|
+
mask = wine_df['Cultivar'] == cultivar
|
|
227
|
+
ax.scatter(
|
|
228
|
+
wine_df.loc[mask, 'PC1'],
|
|
229
|
+
wine_df.loc[mask, 'PC2'],
|
|
230
|
+
wine_df.loc[mask, 'PC3'], # type: ignore
|
|
231
|
+
c=colors[i],
|
|
232
|
+
alpha=0.8,
|
|
233
|
+
s=50,
|
|
234
|
+
label=cultivar,
|
|
235
|
+
edgecolors='black',
|
|
236
|
+
linewidth=0.5
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
ellipse_data = ellipse_coords[ellipse_coords['Cultivar'] == cultivar]
|
|
240
|
+
n_points = int(np.sqrt(len(ellipse_data)))
|
|
241
|
+
|
|
242
|
+
x_2d = ellipse_data['x'].values.reshape(n_points, -1)
|
|
243
|
+
y_2d = ellipse_data['y'].values.reshape(n_points, -1)
|
|
244
|
+
z_2d = ellipse_data['z'].values.reshape(n_points, -1)
|
|
245
|
+
|
|
246
|
+
ax.plot_surface(
|
|
247
|
+
x_2d,
|
|
248
|
+
y_2d,
|
|
249
|
+
z_2d,
|
|
250
|
+
color=light_colors[i],
|
|
251
|
+
alpha=0.4,
|
|
252
|
+
linewidth=0,
|
|
253
|
+
antialiased=True
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
ax.set_xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=12, labelpad=5, fontweight='bold')
|
|
257
|
+
ax.set_ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=12, labelpad=5, fontweight='bold')
|
|
258
|
+
ax.set_zlabel(f'PC3 ({explained_var[2]*100:.2f}%)', fontsize=12, labelpad=1, fontweight='bold')
|
|
259
|
+
ax.set_title('3D PCA Scores with 95% Confidence Ellipsoids', fontsize=16, fontweight='bold')
|
|
260
|
+
ax.legend(
|
|
261
|
+
loc='upper right', fontsize=10, frameon=True, framealpha=0.9,
|
|
262
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
263
|
+
)
|
|
264
|
+
ax.grid(True, alpha=0.3, color='gray')
|
|
265
|
+
ax.view_init(elev=20, azim=65)
|
|
266
|
+
plt.tight_layout()
|
|
267
|
+
plt.show()
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+

|
|
271
|
+
|
|
272
|
+
## Key Differences Between Functions
|
|
273
|
+
|
|
274
|
+
| Feature | `hotelling_parameters` | `hotelling_coordinates` | `confidence_ellipse` |
|
|
275
|
+
|---------|----------------|-----------------|---------------------|
|
|
276
|
+
| __Input__ | Component scores | Component scores | Raw data |
|
|
277
|
+
| __Purpose__ | T² statistics | Plot coordinates | Plot coordinates |
|
|
278
|
+
| __Grouping__ | -- | -- | Yes |
|
|
279
|
+
| __Robust__ | -- | -- | Yes |
|
|
280
|
+
| __2D/3D__ | 2D only for ellipse params | Both | Both |
|
|
281
|
+
| __Distribution__ | Hotelling only | Hotelling only | Normal or Hotelling |
|
|
282
|
+
| __Use Case__ | Outlier detection, QC | Visualizing PCA | Exploratory data analysis |
|
|
283
|
+
|
|
284
|
+
## When to Use Each Function
|
|
285
|
+
|
|
286
|
+
### Use `hotelling_parameters` when:
|
|
287
|
+
|
|
288
|
+
- You need T² statistics for outlier detection
|
|
289
|
+
- You want confidence cutoff values
|
|
290
|
+
- You're performing quality control or process monitoring
|
|
291
|
+
- You need ellipse parameters (semi-axes lengths)
|
|
292
|
+
|
|
293
|
+
### Use `hotelling_coordinates` when:
|
|
294
|
+
|
|
295
|
+
- You have PCA/PLS component scores
|
|
296
|
+
- You want to visualize confidence regions on score plots
|
|
297
|
+
- You need precise control over which components to plot
|
|
298
|
+
- You're creating publication-quality figures from multivariate models
|
|
299
|
+
|
|
300
|
+
### Use `confidence_ellipse` when:
|
|
301
|
+
|
|
302
|
+
- You're working with raw data (not scores)
|
|
303
|
+
- You need to compare multiple groups
|
|
304
|
+
- You want robust estimation for outlier-resistant analysis
|
|
305
|
+
- You need flexibility in distribution choice (normal vs Hotelling)
|
|
306
|
+
|
|
307
|
+
## References
|
|
308
|
+
|
|
309
|
+
1. Hotelling, H. (1931). The generalization of Student's ratio. *Annals of Mathematical Statistics*, 2(3), 360-378.
|
|
310
|
+
2. Brereton, R. G. (2016). Hotelling's T-squared distribution, its relationship to the F distribution and its use in multivariate space. *Journal of Chemometrics*, 30(1), 18-21.
|
|
311
|
+
3. Raymaekers, J., & Rousseeuw, P. J. (2019). Fast robust correlation for high dimensional data. *Technometrics*, 63(2), 184-198.
|
|
312
|
+
4. Jackson, J. E. (1991). *A User's Guide to Principal Components*. Wiley.
|
|
313
|
+
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# pyEllipse
|
|
2
|
+
|
|
3
|
+
A Python package for computing Hotelling's T² statistics and generating confidence ellipse/ellipsoid coordinates for multivariate data analysis and visualization.
|
|
4
|
+
|
|
5
|
+
[](https://badge.fury.io/py/pyellipse)
|
|
6
|
+
[](https://pypi.org/project/pyellipse/)
|
|
7
|
+
[](https://github.com/ChristianGoueguel/pyEllipse/blob/main/LICENSE)
|
|
8
|
+

|
|
9
|
+

|
|
10
|
+

|
|
11
|
+

|
|
12
|
+

|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
## Overview
|
|
16
|
+
|
|
17
|
+
`pyEllipse` provides three main functions for analyzing multivariate data:
|
|
18
|
+
|
|
19
|
+
1. __`hotelling_parameters`__ - Calculate Hotelling's T² statistics and ellipse parameters
|
|
20
|
+
2. __`hotelling_coordinates`__ - Generate Hotelling's ellipse/ellipsoid coordinates from PCA/PLS scores
|
|
21
|
+
3. __`confidence_ellipse`__ - Compute confidence ellipse/ellipsoid coordinates from raw data with grouping support
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install pyEllipse
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage Examples
|
|
30
|
+
|
|
31
|
+
### Example 1: Hotelling's T² statistic and confidence ellipse from PCA Scores
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import numpy as np
|
|
35
|
+
import pandas as pd
|
|
36
|
+
import matplotlib.pyplot as plt
|
|
37
|
+
plt.style.use('bmh')
|
|
38
|
+
from mpl_toolkits.mplot3d import Axes3D
|
|
39
|
+
from sklearn.preprocessing import StandardScaler
|
|
40
|
+
from sklearn.decomposition import PCA
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from pyEllipse import hotelling_parameters, hotelling_coordinates, confidence_ellipse
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
def load_wine_data():
|
|
47
|
+
"""Load wine dataset and add cultivar labels"""
|
|
48
|
+
wine_df = pd.read_csv('data/wine.csv')
|
|
49
|
+
|
|
50
|
+
# Add cultivar labels based on standard Wine dataset structure
|
|
51
|
+
cultivar = []
|
|
52
|
+
for i in range(len(wine_df)):
|
|
53
|
+
if i < 59:
|
|
54
|
+
cultivar.append('Cultivar 1')
|
|
55
|
+
elif i < 130:
|
|
56
|
+
cultivar.append('Cultivar 2')
|
|
57
|
+
else:
|
|
58
|
+
cultivar.append('Cultivar 3')
|
|
59
|
+
|
|
60
|
+
wine_df['Cultivar'] = cultivar
|
|
61
|
+
return wine_df
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
wine_df = load_wine_data()
|
|
66
|
+
X = wine_df.drop('Cultivar', axis=1)
|
|
67
|
+
y = wine_df['Cultivar']
|
|
68
|
+
|
|
69
|
+
# Perform PCA
|
|
70
|
+
pca = PCA()
|
|
71
|
+
SS = StandardScaler()
|
|
72
|
+
X = SS.fit_transform(X)
|
|
73
|
+
pca_scores = pca.fit_transform(X)
|
|
74
|
+
explained_var = pca.explained_variance_ratio_
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
plt.style.use('bmh')
|
|
79
|
+
# Calculate T² statistics
|
|
80
|
+
results = hotelling_parameters(pca_scores, k=2)
|
|
81
|
+
t2 = results['Tsquared'].values
|
|
82
|
+
|
|
83
|
+
# Generate ellipse coordinates for plotting
|
|
84
|
+
ellipse_95 = hotelling_coordinates(pca_scores, pcx=1, pcy=2, conf_limit=0.95)
|
|
85
|
+
ellipse_99 = hotelling_coordinates(pca_scores, pcx=1, pcy=2, conf_limit=0.99)
|
|
86
|
+
|
|
87
|
+
# Plot the PCA scores with Hotelling's T² ellipse
|
|
88
|
+
plt.figure(figsize=(8, 6))
|
|
89
|
+
scatter = plt.scatter(
|
|
90
|
+
pca_scores[:, 0], pca_scores[:, 1],
|
|
91
|
+
c=t2, cmap='jet', alpha=0.85, s=70, label='Wine samples'
|
|
92
|
+
)
|
|
93
|
+
cbar = plt.colorbar(scatter)
|
|
94
|
+
cbar.set_label('Hotelling T² Statistic', rotation=270, labelpad=20)
|
|
95
|
+
|
|
96
|
+
plt.plot(ellipse_95['x'], ellipse_95['y'], 'r-', linewidth=1, label='95% Confidence level')
|
|
97
|
+
plt.plot(ellipse_99['x'], ellipse_99['y'], 'k-', linewidth=1, label='99% Confidence level')
|
|
98
|
+
plt.xlim(-1000, 1000)
|
|
99
|
+
plt.ylim(-50, 60)
|
|
100
|
+
plt.xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
101
|
+
plt.ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
102
|
+
plt.title("Hotelling's T² Ellipse from PCA Scores", fontsize=16, pad=10, fontweight='bold')
|
|
103
|
+
plt.legend(
|
|
104
|
+
loc='upper left', fontsize=10, frameon=True, framealpha=0.9,
|
|
105
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
106
|
+
)
|
|
107
|
+
plt.show()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+

|
|
111
|
+
|
|
112
|
+
### Example 2: Grouped Confidence Ellipses
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
wine_df['PC1'] = pca_scores[:, 0]
|
|
116
|
+
wine_df['PC2'] = pca_scores[:, 1]
|
|
117
|
+
|
|
118
|
+
colors = ['red', 'blue', 'green']
|
|
119
|
+
cultivars = wine_df['Cultivar'].unique()
|
|
120
|
+
color_map = {cultivar: color for cultivar, color in zip(cultivars, colors)}
|
|
121
|
+
point_colors = wine_df['Cultivar'].map(color_map)
|
|
122
|
+
|
|
123
|
+
# Plott PCA scores with confidence ellipses for each cultivar
|
|
124
|
+
plt.figure(figsize=(8, 6))
|
|
125
|
+
|
|
126
|
+
for i, cultivar in enumerate(cultivars):
|
|
127
|
+
mask = wine_df['Cultivar'] == cultivar
|
|
128
|
+
plt.scatter(
|
|
129
|
+
wine_df.loc[mask, 'PC1'], wine_df.loc[mask, 'PC2'], # type: ignore
|
|
130
|
+
c=colors[i], alpha=0.6, s=70, label=cultivar
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
ellipse_coords = confidence_ellipse(
|
|
134
|
+
data=wine_df,
|
|
135
|
+
x='PC1',
|
|
136
|
+
y='PC2',
|
|
137
|
+
group_by='Cultivar',
|
|
138
|
+
conf_level=0.95,
|
|
139
|
+
robust=True,
|
|
140
|
+
distribution='hotelling'
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
for i, cultivar in enumerate(cultivars):
|
|
144
|
+
ellipse_data = ellipse_coords[ellipse_coords['Cultivar'] == cultivar]
|
|
145
|
+
plt.plot(
|
|
146
|
+
ellipse_data['x'], ellipse_data['y'],
|
|
147
|
+
color=colors[i], linewidth=1, linestyle='-', label=f'{cultivar} (95% CI)'
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
plt.xlim(-1000, 1000)
|
|
151
|
+
plt.ylim(-50, 60)
|
|
152
|
+
plt.xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
153
|
+
plt.ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=14, labelpad=10, fontweight='bold')
|
|
154
|
+
plt.title("PCA Scores with Cultivar Group Confidence Ellipses", fontsize=16, pad=10, fontweight='bold')
|
|
155
|
+
plt.legend(
|
|
156
|
+
loc='upper left', fontsize=10, frameon=True, framealpha=0.9,
|
|
157
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
158
|
+
)
|
|
159
|
+
plt.show()
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+

|
|
163
|
+
|
|
164
|
+
### Example 3: Grouped 3D Confidence Ellipsoids
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
wine_df['PC1'] = pca_scores[:, 0]
|
|
168
|
+
wine_df['PC2'] = pca_scores[:, 1]
|
|
169
|
+
wine_df['PC3'] = pca_scores[:, 2]
|
|
170
|
+
|
|
171
|
+
colors = ['red', 'blue', 'green']
|
|
172
|
+
light_colors = ['lightcoral', 'lightblue', 'lightgreen']
|
|
173
|
+
cultivars = wine_df['Cultivar'].unique()
|
|
174
|
+
|
|
175
|
+
ellipse_coords = confidence_ellipse(
|
|
176
|
+
data=wine_df,
|
|
177
|
+
x='PC1',
|
|
178
|
+
y='PC2',
|
|
179
|
+
z='PC3',
|
|
180
|
+
group_by='Cultivar',
|
|
181
|
+
conf_level=0.95,
|
|
182
|
+
robust=True,
|
|
183
|
+
distribution='hotelling'
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
fig = plt.figure(figsize=(10, 6), facecolor='white')
|
|
187
|
+
ax = fig.add_subplot(111, projection='3d', facecolor='white')
|
|
188
|
+
|
|
189
|
+
for i, cultivar in enumerate(cultivars):
|
|
190
|
+
mask = wine_df['Cultivar'] == cultivar
|
|
191
|
+
ax.scatter(
|
|
192
|
+
wine_df.loc[mask, 'PC1'],
|
|
193
|
+
wine_df.loc[mask, 'PC2'],
|
|
194
|
+
wine_df.loc[mask, 'PC3'], # type: ignore
|
|
195
|
+
c=colors[i],
|
|
196
|
+
alpha=0.8,
|
|
197
|
+
s=50,
|
|
198
|
+
label=cultivar,
|
|
199
|
+
edgecolors='black',
|
|
200
|
+
linewidth=0.5
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
ellipse_data = ellipse_coords[ellipse_coords['Cultivar'] == cultivar]
|
|
204
|
+
n_points = int(np.sqrt(len(ellipse_data)))
|
|
205
|
+
|
|
206
|
+
x_2d = ellipse_data['x'].values.reshape(n_points, -1)
|
|
207
|
+
y_2d = ellipse_data['y'].values.reshape(n_points, -1)
|
|
208
|
+
z_2d = ellipse_data['z'].values.reshape(n_points, -1)
|
|
209
|
+
|
|
210
|
+
ax.plot_surface(
|
|
211
|
+
x_2d,
|
|
212
|
+
y_2d,
|
|
213
|
+
z_2d,
|
|
214
|
+
color=light_colors[i],
|
|
215
|
+
alpha=0.4,
|
|
216
|
+
linewidth=0,
|
|
217
|
+
antialiased=True
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
ax.set_xlabel(f'PC1 ({explained_var[0]*100:.2f}%)', fontsize=12, labelpad=5, fontweight='bold')
|
|
221
|
+
ax.set_ylabel(f'PC2 ({explained_var[1]*100:.2f}%)', fontsize=12, labelpad=5, fontweight='bold')
|
|
222
|
+
ax.set_zlabel(f'PC3 ({explained_var[2]*100:.2f}%)', fontsize=12, labelpad=1, fontweight='bold')
|
|
223
|
+
ax.set_title('3D PCA Scores with 95% Confidence Ellipsoids', fontsize=16, fontweight='bold')
|
|
224
|
+
ax.legend(
|
|
225
|
+
loc='upper right', fontsize=10, frameon=True, framealpha=0.9,
|
|
226
|
+
edgecolor='black', shadow=True, facecolor='white', borderpad=1
|
|
227
|
+
)
|
|
228
|
+
ax.grid(True, alpha=0.3, color='gray')
|
|
229
|
+
ax.view_init(elev=20, azim=65)
|
|
230
|
+
plt.tight_layout()
|
|
231
|
+
plt.show()
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+

|
|
235
|
+
|
|
236
|
+
## Key Differences Between Functions
|
|
237
|
+
|
|
238
|
+
| Feature | `hotelling_parameters` | `hotelling_coordinates` | `confidence_ellipse` |
|
|
239
|
+
|---------|----------------|-----------------|---------------------|
|
|
240
|
+
| __Input__ | Component scores | Component scores | Raw data |
|
|
241
|
+
| __Purpose__ | T² statistics | Plot coordinates | Plot coordinates |
|
|
242
|
+
| __Grouping__ | -- | -- | Yes |
|
|
243
|
+
| __Robust__ | -- | -- | Yes |
|
|
244
|
+
| __2D/3D__ | 2D only for ellipse params | Both | Both |
|
|
245
|
+
| __Distribution__ | Hotelling only | Hotelling only | Normal or Hotelling |
|
|
246
|
+
| __Use Case__ | Outlier detection, QC | Visualizing PCA | Exploratory data analysis |
|
|
247
|
+
|
|
248
|
+
## When to Use Each Function
|
|
249
|
+
|
|
250
|
+
### Use `hotelling_parameters` when:
|
|
251
|
+
|
|
252
|
+
- You need T² statistics for outlier detection
|
|
253
|
+
- You want confidence cutoff values
|
|
254
|
+
- You're performing quality control or process monitoring
|
|
255
|
+
- You need ellipse parameters (semi-axes lengths)
|
|
256
|
+
|
|
257
|
+
### Use `hotelling_coordinates` when:
|
|
258
|
+
|
|
259
|
+
- You have PCA/PLS component scores
|
|
260
|
+
- You want to visualize confidence regions on score plots
|
|
261
|
+
- You need precise control over which components to plot
|
|
262
|
+
- You're creating publication-quality figures from multivariate models
|
|
263
|
+
|
|
264
|
+
### Use `confidence_ellipse` when:
|
|
265
|
+
|
|
266
|
+
- You're working with raw data (not scores)
|
|
267
|
+
- You need to compare multiple groups
|
|
268
|
+
- You want robust estimation for outlier-resistant analysis
|
|
269
|
+
- You need flexibility in distribution choice (normal vs Hotelling)
|
|
270
|
+
|
|
271
|
+
## References
|
|
272
|
+
|
|
273
|
+
1. Hotelling, H. (1931). The generalization of Student's ratio. *Annals of Mathematical Statistics*, 2(3), 360-378.
|
|
274
|
+
2. Brereton, R. G. (2016). Hotelling's T-squared distribution, its relationship to the F distribution and its use in multivariate space. *Journal of Chemometrics*, 30(1), 18-21.
|
|
275
|
+
3. Raymaekers, J., & Rousseeuw, P. J. (2019). Fast robust correlation for high dimensional data. *Technometrics*, 63(2), 184-198.
|
|
276
|
+
4. Jackson, J. E. (1991). *A User's Guide to Principal Components*. Wiley.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
**Statistical confidence ellipses and Hotelling's T-squared statistic**
|
|
3
|
+
|
|
4
|
+
The pyEllipse library provides robust computational tools for generating and analyzing
|
|
5
|
+
confidence ellipses and ellipsoids in multivariate datasets. Built on rigorous statistical
|
|
6
|
+
foundations, it supports both classical normal-based confidence regions and Hotelling's
|
|
7
|
+
T-squared ellipses, delivering robust uncertainty quantification for small samples, outlier
|
|
8
|
+
detection, process control, and high-dimensional data exploration.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
# Import main functions with their proper names
|
|
12
|
+
from .hotelling_parameters import hotelling_parameters
|
|
13
|
+
from .hotelling_coordinates import hotelling_coordinates
|
|
14
|
+
from .confidence_ellipse import confidence_ellipse
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"hotelling_parameters",
|
|
18
|
+
"hotelling_coordinates",
|
|
19
|
+
"confidence_ellipse",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
# Library metadata
|
|
23
|
+
__title__ = "pyEllipse"
|
|
24
|
+
__description__ = "Statistical confidence ellipses and Hotelling's T-squared ellipses"
|
|
25
|
+
__url__ = "https://github.com/ChristianGoueguel/pyEllipse"
|
|
26
|
+
__license__ = "MIT"
|
|
27
|
+
__version__ = "0.1.1"
|
|
28
|
+
__author__ = "Christian L. Goueguel"
|
|
29
|
+
__maintainer__ = "Christian L. Goueguel"
|
|
30
|
+
__credits__ = ["Christian L. Goueguel"]
|
|
31
|
+
__email__ = "christian.goueguel@gmail.com"
|