statstudio 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.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1218 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import statsmodels.formula.api as _smf
|
|
9
|
+
from scipy import stats as _scipy_stats
|
|
10
|
+
|
|
11
|
+
from statstudio.stats.results import AnalysisResult
|
|
12
|
+
|
|
13
|
+
_A2 = {
|
|
14
|
+
2: 1.880, 3: 1.023, 4: 0.729, 5: 0.577, 6: 0.483, 7: 0.419, 8: 0.373, 9: 0.337,
|
|
15
|
+
10: 0.308, 11: 0.285, 12: 0.266, 13: 0.249, 14: 0.235, 15: 0.223, 16: 0.212,
|
|
16
|
+
17: 0.203, 18: 0.194, 19: 0.187, 20: 0.180, 21: 0.173, 22: 0.167, 23: 0.162,
|
|
17
|
+
24: 0.157, 25: 0.153,
|
|
18
|
+
}
|
|
19
|
+
_D3 = {
|
|
20
|
+
2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.0, 7: 0.076, 8: 0.136, 9: 0.184, 10: 0.223,
|
|
21
|
+
11: 0.256, 12: 0.283, 13: 0.307, 14: 0.328, 15: 0.347, 16: 0.363, 17: 0.378,
|
|
22
|
+
18: 0.391, 19: 0.403, 20: 0.415, 21: 0.425, 22: 0.434, 23: 0.443, 24: 0.451, 25: 0.459,
|
|
23
|
+
}
|
|
24
|
+
_D4 = {
|
|
25
|
+
2: 3.267, 3: 2.574, 4: 2.282, 5: 2.114, 6: 2.004, 7: 1.924, 8: 1.864, 9: 1.816,
|
|
26
|
+
10: 1.777, 11: 1.744, 12: 1.717, 13: 1.693, 14: 1.672, 15: 1.653, 16: 1.637,
|
|
27
|
+
17: 1.622, 18: 1.608, 19: 1.597, 20: 1.585, 21: 1.575, 22: 1.566, 23: 1.557,
|
|
28
|
+
24: 1.548, 25: 1.541,
|
|
29
|
+
}
|
|
30
|
+
_D2 = {
|
|
31
|
+
2: 1.128, 3: 1.693, 4: 2.059, 5: 2.326, 6: 2.534, 7: 2.704, 8: 2.847, 9: 2.970,
|
|
32
|
+
10: 3.078, 11: 3.173, 12: 3.258, 13: 3.336, 14: 3.407, 15: 3.472, 16: 3.532,
|
|
33
|
+
17: 3.588, 18: 3.640, 19: 3.689, 20: 3.735, 21: 3.778, 22: 3.819, 23: 3.858,
|
|
34
|
+
24: 3.895, 25: 3.931,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def control_chart(
|
|
39
|
+
df: pd.DataFrame,
|
|
40
|
+
column: str,
|
|
41
|
+
subgroup: str | None = None,
|
|
42
|
+
chart: str = "individuals",
|
|
43
|
+
) -> AnalysisResult:
|
|
44
|
+
if column not in df.columns:
|
|
45
|
+
raise KeyError(column)
|
|
46
|
+
frame = df.loc[:, [column] + ([subgroup] if subgroup else [])].copy()
|
|
47
|
+
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
|
48
|
+
frame = frame.dropna(subset=[column])
|
|
49
|
+
if len(frame) < 2:
|
|
50
|
+
raise ValueError("At least two observations are required.")
|
|
51
|
+
if chart == "xbar_r" and subgroup and subgroup in frame.columns:
|
|
52
|
+
groups = frame.groupby(subgroup, sort=False)[column]
|
|
53
|
+
means = groups.mean()
|
|
54
|
+
ranges = groups.max() - groups.min()
|
|
55
|
+
sizes = groups.count().astype(int)
|
|
56
|
+
if (sizes < 2).any() or (sizes > 25).any():
|
|
57
|
+
raise ValueError("X-bar/R charts require subgroup sizes between 2 and 25.")
|
|
58
|
+
xbarbar = float((means * sizes).sum() / sizes.sum())
|
|
59
|
+
rbar = float(ranges.mean())
|
|
60
|
+
a2 = sizes.map(_A2)
|
|
61
|
+
table = pd.DataFrame(
|
|
62
|
+
{
|
|
63
|
+
"Subgroup": means.index.astype(str),
|
|
64
|
+
"Mean": means.to_numpy(),
|
|
65
|
+
"Range": ranges.to_numpy(),
|
|
66
|
+
"N": sizes.to_numpy(),
|
|
67
|
+
"Xbar Center": xbarbar,
|
|
68
|
+
"Xbar UCL": xbarbar + a2.to_numpy() * rbar,
|
|
69
|
+
"Xbar LCL": xbarbar - a2.to_numpy() * rbar,
|
|
70
|
+
"R Center": rbar,
|
|
71
|
+
"R UCL": (sizes.map(_D4) * rbar).to_numpy(),
|
|
72
|
+
"R LCL": (sizes.map(_D3) * rbar).to_numpy(),
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
result = AnalysisResult(title=f"X-bar / R Chart: {column}", analysis_type="control_chart", params={"column": column, "subgroup": subgroup, "chart": chart})
|
|
76
|
+
result.add_table("Control Chart Data", table)
|
|
77
|
+
result.add_plot("control_chart", {"x": "Subgroup", "value": "Mean", "center": "Xbar Center", "ucl": "Xbar UCL", "lcl": "Xbar LCL"}, title="X-bar Chart", data=table)
|
|
78
|
+
result.add_plot("control_chart", {"x": "Subgroup", "value": "Range", "center": "R Center", "ucl": "R UCL", "lcl": "R LCL"}, title="R Chart", data=table)
|
|
79
|
+
size_label = str(int(sizes.iloc[0])) if sizes.nunique() == 1 else f"{int(sizes.min())}-{int(sizes.max())}"
|
|
80
|
+
result.summary = f"X-bar center {xbarbar:.4g}, R center {rbar:.4g}, subgroup size {size_label}."
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
values = frame[column]
|
|
84
|
+
moving_range = pd.to_numeric(df[column], errors="coerce").diff().abs().reindex(values.index)
|
|
85
|
+
center = float(values.mean())
|
|
86
|
+
mrbar = float(moving_range.dropna().mean())
|
|
87
|
+
sigma = mrbar / _D2[2]
|
|
88
|
+
ucl = center + 3 * sigma
|
|
89
|
+
lcl = center - 3 * sigma
|
|
90
|
+
mr_ucl = _D4[2] * mrbar
|
|
91
|
+
table = pd.DataFrame(
|
|
92
|
+
{
|
|
93
|
+
"Observation": np.arange(1, len(values) + 1),
|
|
94
|
+
"Value": values.to_numpy(),
|
|
95
|
+
"Moving Range": moving_range.to_numpy(),
|
|
96
|
+
"Center": center,
|
|
97
|
+
"UCL": ucl,
|
|
98
|
+
"LCL": lcl,
|
|
99
|
+
"MR Center": mrbar,
|
|
100
|
+
"MR UCL": mr_ucl,
|
|
101
|
+
"MR LCL": 0.0,
|
|
102
|
+
}
|
|
103
|
+
)
|
|
104
|
+
result = AnalysisResult(title=f"Individuals / Moving Range Chart: {column}", analysis_type="control_chart", params={"column": column, "chart": "individuals"})
|
|
105
|
+
result.add_table("Control Chart Data", table)
|
|
106
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "Value", "center": "Center", "ucl": "UCL", "lcl": "LCL"}, title="Individuals Chart", data=table)
|
|
107
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "Moving Range", "center": "MR Center", "ucl": "MR UCL", "lcl": "MR LCL"}, title="Moving Range Chart", data=table)
|
|
108
|
+
result.summary = f"Center {center:.4g}, sigma {sigma:.4g}, UCL {ucl:.4g}, LCL {lcl:.4g}."
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def process_capability(
|
|
113
|
+
df: pd.DataFrame,
|
|
114
|
+
column: str,
|
|
115
|
+
lsl: float | None = None,
|
|
116
|
+
usl: float | None = None,
|
|
117
|
+
target: float | None = None,
|
|
118
|
+
) -> AnalysisResult:
|
|
119
|
+
if column not in df.columns:
|
|
120
|
+
raise KeyError(column)
|
|
121
|
+
raw_values = pd.to_numeric(df[column], errors="coerce")
|
|
122
|
+
values = raw_values.dropna()
|
|
123
|
+
if len(values) < 2:
|
|
124
|
+
raise ValueError("At least two observations are required.")
|
|
125
|
+
mean = float(values.mean())
|
|
126
|
+
std_overall = float(values.std(ddof=1))
|
|
127
|
+
moving_range = raw_values.diff().abs().reindex(values.index).dropna()
|
|
128
|
+
std_within = float(moving_range.mean() / _D2[2]) if len(moving_range) else std_overall
|
|
129
|
+
cp = (usl - lsl) / (6 * std_within) if lsl is not None and usl is not None and std_within else np.nan
|
|
130
|
+
cpu = (usl - mean) / (3 * std_within) if usl is not None and std_within else np.nan
|
|
131
|
+
cpl = (mean - lsl) / (3 * std_within) if lsl is not None and std_within else np.nan
|
|
132
|
+
cpk = min(cpu, cpl) if not (np.isnan(cpu) or np.isnan(cpl)) else np.nan
|
|
133
|
+
pp = (usl - lsl) / (6 * std_overall) if lsl is not None and usl is not None and std_overall else np.nan
|
|
134
|
+
ppu = (usl - mean) / (3 * std_overall) if usl is not None and std_overall else np.nan
|
|
135
|
+
ppl = (mean - lsl) / (3 * std_overall) if lsl is not None and std_overall else np.nan
|
|
136
|
+
ppk = min(ppu, ppl) if not (np.isnan(ppu) or np.isnan(ppl)) else np.nan
|
|
137
|
+
if lsl is not None and usl is not None:
|
|
138
|
+
observed = float(((values >= lsl) & (values <= usl)).mean())
|
|
139
|
+
else:
|
|
140
|
+
observed = np.nan
|
|
141
|
+
table = pd.DataFrame(
|
|
142
|
+
[
|
|
143
|
+
{
|
|
144
|
+
"N": len(values),
|
|
145
|
+
"Mean": mean,
|
|
146
|
+
"Std Dev (Within)": std_within,
|
|
147
|
+
"Std Dev (Overall)": std_overall,
|
|
148
|
+
"LSL": lsl,
|
|
149
|
+
"Target": target,
|
|
150
|
+
"USL": usl,
|
|
151
|
+
"Cp": cp,
|
|
152
|
+
"Cpk": cpk,
|
|
153
|
+
"Pp": pp,
|
|
154
|
+
"Ppk": ppk,
|
|
155
|
+
"Observed Within Spec": observed,
|
|
156
|
+
}
|
|
157
|
+
]
|
|
158
|
+
)
|
|
159
|
+
result = AnalysisResult(title=f"Process Capability: {column}", analysis_type="capability", params={"column": column, "lsl": lsl, "usl": usl, "target": target})
|
|
160
|
+
result.add_table("Capability Indices", table)
|
|
161
|
+
result.add_plot("capability", {"column": column, "lsl": lsl, "usl": usl, "target": target}, title=f"Capability Histogram: {column}", data=df)
|
|
162
|
+
result.summary = f"Cp = {cp:.3g}, Cpk = {cpk:.3g}, Ppk = {ppk:.3g}, N = {len(values)}."
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def pareto_chart(df: pd.DataFrame, column: str, max_categories: int = 30) -> AnalysisResult:
|
|
167
|
+
if column not in df.columns:
|
|
168
|
+
raise KeyError(column)
|
|
169
|
+
counts = df[column].fillna("(missing)").astype(str).value_counts().head(max_categories)
|
|
170
|
+
table = counts.rename_axis("Category").reset_index(name="Count")
|
|
171
|
+
total = counts.sum()
|
|
172
|
+
table["Percent"] = table["Count"] / total * 100
|
|
173
|
+
table["Cumulative Percent"] = table["Percent"].cumsum()
|
|
174
|
+
result = AnalysisResult(title=f"Pareto Chart: {column}", analysis_type="pareto", params={"column": column})
|
|
175
|
+
result.add_table("Pareto Data", table)
|
|
176
|
+
result.add_plot("pareto", {"category": "Category", "count": "Count", "cumulative": "Cumulative Percent"}, title=f"Pareto: {column}", data=table)
|
|
177
|
+
result.summary = f"{len(table)} categories; the top category accounts for {table['Percent'].iloc[0]:.1f}%."
|
|
178
|
+
return result
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# Extended SPC constants -----------------------------------------------------
|
|
182
|
+
_C4 = {
|
|
183
|
+
2: 0.7979, 3: 0.8862, 4: 0.9213, 5: 0.9400, 6: 0.9515, 7: 0.9594, 8: 0.9650,
|
|
184
|
+
9: 0.9693, 10: 0.9727, 11: 0.9754, 12: 0.9776, 13: 0.9794, 14: 0.9810,
|
|
185
|
+
15: 0.9823, 16: 0.9835, 17: 0.9845, 18: 0.9854, 19: 0.9862, 20: 0.9869,
|
|
186
|
+
21: 0.9876, 22: 0.9882, 23: 0.9887, 24: 0.9892, 25: 0.9896,
|
|
187
|
+
}
|
|
188
|
+
_A3 = {
|
|
189
|
+
2: 2.659, 3: 1.954, 4: 1.628, 5: 1.427, 6: 1.287, 7: 1.182, 8: 1.099,
|
|
190
|
+
9: 1.032, 10: 0.975, 11: 0.927, 12: 0.886, 13: 0.850, 14: 0.817, 15: 0.789,
|
|
191
|
+
16: 0.763, 17: 0.739, 18: 0.718, 19: 0.698, 20: 0.680, 21: 0.663, 22: 0.647,
|
|
192
|
+
23: 0.633, 24: 0.619, 25: 0.606,
|
|
193
|
+
}
|
|
194
|
+
_B3 = {
|
|
195
|
+
2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.030, 7: 0.118, 8: 0.185, 9: 0.239, 10: 0.284,
|
|
196
|
+
11: 0.321, 12: 0.354, 13: 0.382, 14: 0.406, 15: 0.428, 16: 0.448, 17: 0.466,
|
|
197
|
+
18: 0.482, 19: 0.497, 20: 0.510, 21: 0.523, 22: 0.534, 23: 0.545, 24: 0.555, 25: 0.565,
|
|
198
|
+
}
|
|
199
|
+
_B4 = {
|
|
200
|
+
2: 3.267, 3: 2.568, 4: 2.266, 5: 2.089, 6: 1.970, 7: 1.882, 8: 1.815, 9: 1.761,
|
|
201
|
+
10: 1.716, 11: 1.679, 12: 1.646, 13: 1.618, 14: 1.594, 15: 1.572, 16: 1.553,
|
|
202
|
+
17: 1.534, 18: 1.518, 19: 1.503, 20: 1.490, 21: 1.477, 22: 1.466, 23: 1.455,
|
|
203
|
+
24: 1.445, 25: 1.435,
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _run_rules(
|
|
210
|
+
values: np.ndarray,
|
|
211
|
+
center: float,
|
|
212
|
+
ucl: float,
|
|
213
|
+
lcl: float,
|
|
214
|
+
rules: int = 8,
|
|
215
|
+
) -> list[str]:
|
|
216
|
+
centers = np.full(len(values), center, dtype=float)
|
|
217
|
+
ucls = np.full(len(values), ucl, dtype=float)
|
|
218
|
+
lcls = np.full(len(values), lcl, dtype=float)
|
|
219
|
+
return _run_rules_arrays(values, centers, ucls, lcls, rules=rules)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _run_rules_arrays(
|
|
223
|
+
values: np.ndarray,
|
|
224
|
+
centers: np.ndarray,
|
|
225
|
+
ucls: np.ndarray,
|
|
226
|
+
lcls: np.ndarray,
|
|
227
|
+
rules: int = 8,
|
|
228
|
+
) -> list[str]:
|
|
229
|
+
values = np.asarray(values, dtype=float)
|
|
230
|
+
centers = np.asarray(centers, dtype=float)
|
|
231
|
+
ucls = np.asarray(ucls, dtype=float)
|
|
232
|
+
lcls = np.asarray(lcls, dtype=float)
|
|
233
|
+
count = len(values)
|
|
234
|
+
status = ["ok"] * count
|
|
235
|
+
if count == 0:
|
|
236
|
+
return status
|
|
237
|
+
sigma = np.where(np.isfinite(ucls - lcls), (ucls - lcls) / 6.0, np.nan)
|
|
238
|
+
sigma = np.where(sigma > 0, sigma, np.nan)
|
|
239
|
+
|
|
240
|
+
def mark(indices: list[int], label: str) -> None:
|
|
241
|
+
for index in indices:
|
|
242
|
+
if 0 <= index < count and status[index] == "ok":
|
|
243
|
+
status[index] = label
|
|
244
|
+
|
|
245
|
+
for index, value in enumerate(values):
|
|
246
|
+
if np.isfinite(value) and (value > ucls[index] or value < lcls[index]):
|
|
247
|
+
status[index] = "out"
|
|
248
|
+
if rules <= 1:
|
|
249
|
+
return status
|
|
250
|
+
|
|
251
|
+
def finite(window: np.ndarray) -> bool:
|
|
252
|
+
return bool(np.all(np.isfinite(window)))
|
|
253
|
+
|
|
254
|
+
for start in range(0, count - 8):
|
|
255
|
+
window = values[start:start + 9]
|
|
256
|
+
sides = window - centers[start:start + 9]
|
|
257
|
+
if finite(window) and (np.all(sides > 0) or np.all(sides < 0)):
|
|
258
|
+
mark(list(range(start, start + 9)), "rule2")
|
|
259
|
+
if rules <= 2:
|
|
260
|
+
return status
|
|
261
|
+
|
|
262
|
+
for start in range(0, count - 5):
|
|
263
|
+
window = values[start:start + 6]
|
|
264
|
+
diffs = np.diff(window)
|
|
265
|
+
if finite(window) and (np.all(diffs > 0) or np.all(diffs < 0)):
|
|
266
|
+
mark(list(range(start, start + 6)), "rule3")
|
|
267
|
+
if rules <= 3:
|
|
268
|
+
return status
|
|
269
|
+
|
|
270
|
+
for start in range(0, count - 13):
|
|
271
|
+
window = values[start:start + 14]
|
|
272
|
+
diffs = np.diff(window)
|
|
273
|
+
if finite(window) and np.all(diffs[1:] * diffs[:-1] < 0):
|
|
274
|
+
mark(list(range(start, start + 14)), "rule4")
|
|
275
|
+
if rules <= 4:
|
|
276
|
+
return status
|
|
277
|
+
|
|
278
|
+
for start in range(0, count - 2):
|
|
279
|
+
window = values[start:start + 3]
|
|
280
|
+
side = window - centers[start:start + 3]
|
|
281
|
+
threshold = 2.0 * sigma[start:start + 3]
|
|
282
|
+
if finite(window) and finite(threshold):
|
|
283
|
+
if np.sum(side > threshold) >= 2 or np.sum(side < -threshold) >= 2:
|
|
284
|
+
mark(list(range(start, start + 3)), "rule5")
|
|
285
|
+
if rules <= 5:
|
|
286
|
+
return status
|
|
287
|
+
|
|
288
|
+
for start in range(0, count - 4):
|
|
289
|
+
window = values[start:start + 5]
|
|
290
|
+
side = window - centers[start:start + 5]
|
|
291
|
+
threshold = sigma[start:start + 5]
|
|
292
|
+
if finite(window) and finite(threshold):
|
|
293
|
+
if np.sum(side > threshold) >= 4 or np.sum(side < -threshold) >= 4:
|
|
294
|
+
mark(list(range(start, start + 5)), "rule6")
|
|
295
|
+
if rules <= 6:
|
|
296
|
+
return status
|
|
297
|
+
|
|
298
|
+
for start in range(0, count - 14):
|
|
299
|
+
window = values[start:start + 15]
|
|
300
|
+
side = window - centers[start:start + 15]
|
|
301
|
+
threshold = sigma[start:start + 15]
|
|
302
|
+
if finite(window) and finite(threshold) and np.all(np.abs(side) < threshold):
|
|
303
|
+
mark(list(range(start, start + 15)), "rule7")
|
|
304
|
+
if rules <= 7:
|
|
305
|
+
return status
|
|
306
|
+
|
|
307
|
+
for start in range(0, count - 7):
|
|
308
|
+
window = values[start:start + 8]
|
|
309
|
+
side = window - centers[start:start + 8]
|
|
310
|
+
threshold = sigma[start:start + 8]
|
|
311
|
+
if finite(window) and finite(threshold):
|
|
312
|
+
if np.all(np.abs(side) > threshold) or np.all(side > threshold) or np.all(side < -threshold):
|
|
313
|
+
mark(list(range(start, start + 8)), "rule8")
|
|
314
|
+
return status
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def spc_chart(
|
|
318
|
+
df: pd.DataFrame,
|
|
319
|
+
column: str,
|
|
320
|
+
chart: str = "imr",
|
|
321
|
+
subgroup: str | None = None,
|
|
322
|
+
sample_size: int | None = None,
|
|
323
|
+
sample_size_column: str | None = None,
|
|
324
|
+
phase: str | None = None,
|
|
325
|
+
rules: int = 8,
|
|
326
|
+
process_target: float | None = None,
|
|
327
|
+
cusum_k: float = 0.5,
|
|
328
|
+
cusum_h: float = 4.0,
|
|
329
|
+
ewma_lambda: float = 0.2,
|
|
330
|
+
) -> AnalysisResult:
|
|
331
|
+
chart = chart.lower()
|
|
332
|
+
if column not in df.columns:
|
|
333
|
+
raise KeyError(column)
|
|
334
|
+
columns = [column] + [c for c in (subgroup, phase, sample_size_column) if c]
|
|
335
|
+
raw = df.loc[:, columns].copy()
|
|
336
|
+
raw[column] = pd.to_numeric(raw[column], errors="coerce")
|
|
337
|
+
raw_series = raw[column]
|
|
338
|
+
frame = raw.dropna(subset=[column])
|
|
339
|
+
if len(frame) < 2:
|
|
340
|
+
raise ValueError("At least two observations are required.")
|
|
341
|
+
result = AnalysisResult(
|
|
342
|
+
title=f"Control Chart ({chart.upper()}): {column}",
|
|
343
|
+
analysis_type="control_chart",
|
|
344
|
+
params={
|
|
345
|
+
"column": column,
|
|
346
|
+
"chart": chart,
|
|
347
|
+
"subgroup": subgroup,
|
|
348
|
+
"sample_size": sample_size,
|
|
349
|
+
"sample_size_column": sample_size_column,
|
|
350
|
+
"phase": phase,
|
|
351
|
+
"rules": rules,
|
|
352
|
+
"process_target": process_target,
|
|
353
|
+
},
|
|
354
|
+
)
|
|
355
|
+
if chart in {"cusum", "ewma"}:
|
|
356
|
+
values = frame[column].reset_index(drop=True).astype(float)
|
|
357
|
+
center = float(process_target if process_target is not None else values.mean())
|
|
358
|
+
moving_range = values.diff().abs().dropna()
|
|
359
|
+
sigma = float(moving_range.mean() / _D2[2]) if len(moving_range) else float(values.std(ddof=1))
|
|
360
|
+
sigma = sigma or float(values.std(ddof=1)) or 1.0
|
|
361
|
+
if chart == "cusum":
|
|
362
|
+
k = max(0.0, float(cusum_k)) * sigma
|
|
363
|
+
h = max(0.1, float(cusum_h)) * sigma
|
|
364
|
+
cplus = np.zeros(len(values))
|
|
365
|
+
cminus = np.zeros(len(values))
|
|
366
|
+
for index, value in enumerate(values):
|
|
367
|
+
previous_plus = cplus[index - 1] if index else 0.0
|
|
368
|
+
previous_minus = cminus[index - 1] if index else 0.0
|
|
369
|
+
cplus[index] = max(0.0, previous_plus + value - center - k)
|
|
370
|
+
cminus[index] = max(0.0, previous_minus + center - k - value)
|
|
371
|
+
table = pd.DataFrame({
|
|
372
|
+
"Observation": np.arange(1, len(values) + 1),
|
|
373
|
+
"Value": values.to_numpy(),
|
|
374
|
+
"C+": cplus,
|
|
375
|
+
"C-": cminus,
|
|
376
|
+
"Center": 0.0,
|
|
377
|
+
"UCL": h,
|
|
378
|
+
"LCL": -h,
|
|
379
|
+
})
|
|
380
|
+
result.add_table("CUSUM Data", table)
|
|
381
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "C+", "center": "Center", "ucl": "UCL", "lcl": "LCL"}, title="CUSUM C+", data=table)
|
|
382
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "C-", "center": "Center", "ucl": "UCL", "lcl": "LCL"}, title="CUSUM C-", data=table)
|
|
383
|
+
result.summary = f"CUSUM target {center:.4g}, k = {cusum_k:.2f} sigma, h = {cusum_h:.2f} sigma."
|
|
384
|
+
return result
|
|
385
|
+
lam = min(max(float(ewma_lambda), 0.01), 1.0)
|
|
386
|
+
z_values = np.zeros(len(values))
|
|
387
|
+
for index, value in enumerate(values):
|
|
388
|
+
previous = z_values[index - 1] if index else center
|
|
389
|
+
z_values[index] = lam * value + (1 - lam) * previous
|
|
390
|
+
ucl = []
|
|
391
|
+
lcl = []
|
|
392
|
+
for index in range(len(values)):
|
|
393
|
+
scale = sigma * math.sqrt(lam / (2 - lam) * (1 - (1 - lam) ** (2 * (index + 1))))
|
|
394
|
+
ucl.append(center + 3 * scale)
|
|
395
|
+
lcl.append(center - 3 * scale)
|
|
396
|
+
table = pd.DataFrame({
|
|
397
|
+
"Observation": np.arange(1, len(values) + 1),
|
|
398
|
+
"Value": values.to_numpy(),
|
|
399
|
+
"EWMA": z_values,
|
|
400
|
+
"Center": center,
|
|
401
|
+
"UCL": ucl,
|
|
402
|
+
"LCL": lcl,
|
|
403
|
+
})
|
|
404
|
+
table["Status"] = _run_rules_arrays(table["EWMA"].to_numpy(dtype=float), table["Center"].to_numpy(dtype=float), table["UCL"].to_numpy(dtype=float), table["LCL"].to_numpy(dtype=float), rules=rules)
|
|
405
|
+
result.add_table("EWMA Data", table)
|
|
406
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "EWMA", "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title="EWMA Chart", data=table)
|
|
407
|
+
result.summary = f"EWMA target {center:.4g}, lambda = {lam:.2f}, sigma = {sigma:.4g}."
|
|
408
|
+
return result
|
|
409
|
+
if chart in {"laney_p", "laney_u"}:
|
|
410
|
+
if sample_size is None:
|
|
411
|
+
raise ValueError("Laney charts require a sample size.")
|
|
412
|
+
counts = frame[column].reset_index(drop=True).astype(float)
|
|
413
|
+
if chart == "laney_p":
|
|
414
|
+
rates = counts / sample_size
|
|
415
|
+
center = float(counts.sum() / (sample_size * len(counts))) if len(counts) else float("nan")
|
|
416
|
+
base_sigma = math.sqrt(max(center * (1 - center), 0.0) / sample_size)
|
|
417
|
+
z_values = pd.Series((rates - center) / base_sigma, dtype=float) if base_sigma else pd.Series(np.zeros(len(rates)), dtype=float)
|
|
418
|
+
sigma_z = float(z_values.std(ddof=1)) if z_values.notna().sum() > 1 else 1.0
|
|
419
|
+
sigma_z = sigma_z if np.isfinite(sigma_z) and sigma_z > 0 else 1.0
|
|
420
|
+
ucl = center + 3 * base_sigma * sigma_z
|
|
421
|
+
lcl = np.maximum(0.0, center - 3 * base_sigma * sigma_z)
|
|
422
|
+
label = "Proportion"
|
|
423
|
+
table = pd.DataFrame({"Observation": np.arange(1, len(rates) + 1), label: rates.to_numpy(), "Center": center, "UCL": ucl, "LCL": lcl})
|
|
424
|
+
else:
|
|
425
|
+
units = sample_size
|
|
426
|
+
rates = counts / units
|
|
427
|
+
center = float(counts.sum() / (units * len(counts))) if len(counts) else float("nan")
|
|
428
|
+
base_sigma = math.sqrt(max(center, 0.0) / units)
|
|
429
|
+
z_values = pd.Series((rates - center) / base_sigma, dtype=float) if base_sigma else pd.Series(np.zeros(len(rates)), dtype=float)
|
|
430
|
+
sigma_z = float(z_values.std(ddof=1)) if z_values.notna().sum() > 1 else 1.0
|
|
431
|
+
sigma_z = sigma_z if np.isfinite(sigma_z) and sigma_z > 0 else 1.0
|
|
432
|
+
ucl = center + 3 * base_sigma * sigma_z
|
|
433
|
+
lcl = np.maximum(0.0, center - 3 * base_sigma * sigma_z)
|
|
434
|
+
label = "Defects per Unit"
|
|
435
|
+
table = pd.DataFrame({"Observation": np.arange(1, len(rates) + 1), label: rates.to_numpy(), "Center": center, "UCL": ucl, "LCL": lcl})
|
|
436
|
+
table["Status"] = _run_rules_arrays(table[label].to_numpy(dtype=float), table["Center"].to_numpy(dtype=float), table["UCL"].to_numpy(dtype=float), table["LCL"].to_numpy(dtype=float), rules=rules)
|
|
437
|
+
result.add_table("Control Chart Data", table)
|
|
438
|
+
laney_label = "P'" if chart == "laney_p" else "U'"
|
|
439
|
+
result.add_plot("control_chart", {"x": "Observation", "value": label, "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title=f"Laney {laney_label} Chart", data=table)
|
|
440
|
+
result.summary = f"Laney chart center {center:.4g}; sigma inflation {sigma_z:.3f}."
|
|
441
|
+
return result
|
|
442
|
+
if chart in {"xbar_r", "xbar_s"} and subgroup and subgroup in frame.columns:
|
|
443
|
+
def phase_statistics(subset: pd.DataFrame) -> pd.DataFrame:
|
|
444
|
+
groups = subset.groupby(subgroup, sort=False)[column]
|
|
445
|
+
means = groups.mean()
|
|
446
|
+
sizes = groups.count().astype(int)
|
|
447
|
+
if (sizes < 2).any() or (sizes > 25).any():
|
|
448
|
+
raise ValueError("X-bar charts require subgroup sizes between 2 and 25.")
|
|
449
|
+
total = float(sizes.sum())
|
|
450
|
+
center = float((means * sizes).sum() / total) if total else float(means.mean())
|
|
451
|
+
if chart == "xbar_r":
|
|
452
|
+
spread = groups.max() - groups.min()
|
|
453
|
+
spread_center = float(spread.dropna().mean())
|
|
454
|
+
sigma = float((spread / sizes.map(_D2)).dropna().mean())
|
|
455
|
+
x_ucl = center + sizes.map(_A2).to_numpy() * spread_center
|
|
456
|
+
x_lcl = center - sizes.map(_A2).to_numpy() * spread_center
|
|
457
|
+
second = {
|
|
458
|
+
"Range": spread.to_numpy(),
|
|
459
|
+
"R Center": spread_center,
|
|
460
|
+
"R UCL": (sizes.map(_D4) * spread_center).to_numpy(),
|
|
461
|
+
"R LCL": (sizes.map(_D3) * spread_center).to_numpy(),
|
|
462
|
+
}
|
|
463
|
+
else:
|
|
464
|
+
spread = groups.std(ddof=1)
|
|
465
|
+
spread_center = float(spread.dropna().mean())
|
|
466
|
+
sigma = float((spread / sizes.map(_C4)).dropna().mean())
|
|
467
|
+
x_ucl = center + sizes.map(_A3).to_numpy() * spread_center
|
|
468
|
+
x_lcl = center - sizes.map(_A3).to_numpy() * spread_center
|
|
469
|
+
second = {
|
|
470
|
+
"Std Dev": spread.to_numpy(),
|
|
471
|
+
"S Center": spread_center,
|
|
472
|
+
"S UCL": (sizes.map(_B4) * spread_center).to_numpy(),
|
|
473
|
+
"S LCL": (sizes.map(_B3) * spread_center).to_numpy(),
|
|
474
|
+
}
|
|
475
|
+
table = pd.DataFrame({
|
|
476
|
+
"Subgroup": means.index.astype(str),
|
|
477
|
+
"Mean": means.to_numpy(),
|
|
478
|
+
"N": sizes.to_numpy(),
|
|
479
|
+
"Center": center,
|
|
480
|
+
"UCL": x_ucl,
|
|
481
|
+
"LCL": x_lcl,
|
|
482
|
+
})
|
|
483
|
+
for key, value in second.items():
|
|
484
|
+
table[key] = value
|
|
485
|
+
table.attrs["sigma"] = sigma
|
|
486
|
+
return table
|
|
487
|
+
|
|
488
|
+
pieces = []
|
|
489
|
+
if phase and phase in frame.columns:
|
|
490
|
+
for phase_value in pd.unique(frame[phase]):
|
|
491
|
+
subset = frame[frame[phase] == phase_value]
|
|
492
|
+
piece = phase_statistics(subset)
|
|
493
|
+
piece.insert(1, "Phase", str(phase_value))
|
|
494
|
+
pieces.append(piece)
|
|
495
|
+
else:
|
|
496
|
+
pieces.append(phase_statistics(frame))
|
|
497
|
+
table = pd.concat(pieces, ignore_index=True)
|
|
498
|
+
sigma_values = [piece.attrs.get("sigma", np.nan) for piece in pieces]
|
|
499
|
+
values = table["Mean"].to_numpy(dtype=float)
|
|
500
|
+
table["Status"] = _run_rules_arrays(
|
|
501
|
+
values,
|
|
502
|
+
table["Center"].to_numpy(dtype=float),
|
|
503
|
+
table["UCL"].to_numpy(dtype=float),
|
|
504
|
+
table["LCL"].to_numpy(dtype=float),
|
|
505
|
+
rules=rules,
|
|
506
|
+
)
|
|
507
|
+
center = float(table["Center"].iloc[0])
|
|
508
|
+
ucl = float(table["UCL"].iloc[0])
|
|
509
|
+
lcl = float(table["LCL"].iloc[0])
|
|
510
|
+
sigma = float(np.nanmean(sigma_values)) if sigma_values else np.nan
|
|
511
|
+
sizes = table["N"].astype(int)
|
|
512
|
+
result.add_table("Control Chart Data", table)
|
|
513
|
+
result.add_plot("control_chart", {"x": "Subgroup", "value": "Mean", "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title=f"X-bar Chart ({chart.upper()})", data=table)
|
|
514
|
+
second_col = "Range" if chart == "xbar_r" else "Std Dev"
|
|
515
|
+
center_col = "R Center" if chart == "xbar_r" else "S Center"
|
|
516
|
+
ucl_col = "R UCL" if chart == "xbar_r" else "S UCL"
|
|
517
|
+
lcl_col = "R LCL" if chart == "xbar_r" else "S LCL"
|
|
518
|
+
result.add_plot("control_chart", {"x": "Subgroup", "value": second_col, "center": center_col, "ucl": ucl_col, "lcl": lcl_col}, title=f"{second_col} Chart", data=table)
|
|
519
|
+
size_label = str(int(sizes.iloc[0])) if sizes.nunique() == 1 else f"{int(sizes.min())}-{int(sizes.max())}"
|
|
520
|
+
result.summary = f"Subgroup size {size_label}; center {center:.4g}, sigma {sigma:.4g}, UCL {ucl:.4g}, LCL {lcl:.4g}."
|
|
521
|
+
return result
|
|
522
|
+
|
|
523
|
+
values_series = frame[column].reset_index(drop=True)
|
|
524
|
+
sizes = None
|
|
525
|
+
if sample_size_column and sample_size_column in frame.columns:
|
|
526
|
+
sizes = pd.to_numeric(frame[sample_size_column].reset_index(drop=True), errors="coerce")
|
|
527
|
+
if sizes.isna().any() or (sizes <= 0).any():
|
|
528
|
+
raise ValueError("Sample-size values must be positive and non-missing.")
|
|
529
|
+
if chart in {"p", "np"}:
|
|
530
|
+
defectives = values_series
|
|
531
|
+
if sizes is None:
|
|
532
|
+
if sample_size is None:
|
|
533
|
+
sample_size = int(values_series.max()) if chart == "np" else None
|
|
534
|
+
if sample_size is None:
|
|
535
|
+
raise ValueError("Attribute charts require a sample size or sample-size column.")
|
|
536
|
+
sizes = pd.Series(float(sample_size), index=defectives.index)
|
|
537
|
+
pbar = float(defectives.sum() / sizes.sum())
|
|
538
|
+
fractions = defectives / sizes
|
|
539
|
+
if chart == "p":
|
|
540
|
+
center = pbar
|
|
541
|
+
centers = np.full(len(fractions), pbar)
|
|
542
|
+
sigmas = np.sqrt(pbar * (1 - pbar) / sizes.to_numpy(dtype=float))
|
|
543
|
+
else:
|
|
544
|
+
centers = pbar * sizes.to_numpy(dtype=float)
|
|
545
|
+
sigmas = np.sqrt(sizes.to_numpy(dtype=float) * pbar * (1 - pbar))
|
|
546
|
+
ucls, lcls = centers + 3 * sigmas, np.maximum(0.0, centers - 3 * sigmas)
|
|
547
|
+
label = "Proportion" if chart == "p" else "Defectives"
|
|
548
|
+
values = fractions.to_numpy() if chart == "p" else defectives.to_numpy()
|
|
549
|
+
table = pd.DataFrame({
|
|
550
|
+
"Observation": np.arange(1, len(fractions) + 1),
|
|
551
|
+
"N": sizes.to_numpy(dtype=float),
|
|
552
|
+
label: values,
|
|
553
|
+
"Center": centers,
|
|
554
|
+
"UCL": ucls,
|
|
555
|
+
"LCL": lcls,
|
|
556
|
+
})
|
|
557
|
+
table["Status"] = _run_rules_arrays(values.astype(float), centers, ucls, lcls, rules=rules)
|
|
558
|
+
result.add_table("Control Chart Data", table)
|
|
559
|
+
result.add_plot("control_chart", {"x": "Observation", "value": label, "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title=f"{chart.upper()} Chart", data=table)
|
|
560
|
+
result.summary = f"{chart.upper()} chart with p-bar {pbar:.4g} over {len(fractions)} samples."
|
|
561
|
+
return result
|
|
562
|
+
if chart in {"c", "u"}:
|
|
563
|
+
counts = values_series
|
|
564
|
+
if chart == "c":
|
|
565
|
+
center = float(counts.mean())
|
|
566
|
+
centers = np.full(len(counts), center)
|
|
567
|
+
ucls, lcls = centers + 3 * np.sqrt(center), np.maximum(0.0, centers - 3 * np.sqrt(center))
|
|
568
|
+
label = "Defects"
|
|
569
|
+
else:
|
|
570
|
+
if sizes is None:
|
|
571
|
+
sizes = pd.Series(float(sample_size or 1), index=counts.index)
|
|
572
|
+
rates = counts / sizes
|
|
573
|
+
center = float(counts.sum() / sizes.sum())
|
|
574
|
+
centers = np.full(len(rates), center)
|
|
575
|
+
sigmas = np.sqrt(center / sizes.to_numpy(dtype=float))
|
|
576
|
+
ucls, lcls = centers + 3 * sigmas, np.maximum(0.0, centers - 3 * sigmas)
|
|
577
|
+
label = "Defects per Unit"
|
|
578
|
+
counts = rates
|
|
579
|
+
table = pd.DataFrame({
|
|
580
|
+
"Observation": np.arange(1, len(counts) + 1),
|
|
581
|
+
"N": sizes.to_numpy(dtype=float) if sizes is not None else np.nan,
|
|
582
|
+
label: counts.to_numpy(),
|
|
583
|
+
"Center": centers,
|
|
584
|
+
"UCL": ucls,
|
|
585
|
+
"LCL": lcls,
|
|
586
|
+
})
|
|
587
|
+
table["Status"] = _run_rules_arrays(table[label].to_numpy(dtype=float), centers, ucls, lcls, rules=rules)
|
|
588
|
+
result.add_table("Control Chart Data", table)
|
|
589
|
+
result.add_plot("control_chart", {"x": "Observation", "value": label, "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title=f"{chart.upper()} Chart", data=table)
|
|
590
|
+
result.summary = f"{chart.upper()} chart center {center:.4g} over {len(counts)} samples."
|
|
591
|
+
return result
|
|
592
|
+
|
|
593
|
+
# Individuals / moving range (optionally with per-phase limits)
|
|
594
|
+
values_series = frame[column]
|
|
595
|
+
moving_range = raw_series.diff().abs().reindex(values_series.index)
|
|
596
|
+
if phase and phase in frame.columns:
|
|
597
|
+
phase_series = frame[phase]
|
|
598
|
+
moving_range = moving_range.where(phase_series.shift() == phase_series)
|
|
599
|
+
centers, ucls, lcls, mr_centers, mr_ucls, mr_lcls = [], [], [], [], [], []
|
|
600
|
+
for phase_value in pd.unique(phase_series):
|
|
601
|
+
mask = (phase_series == phase_value).to_numpy()
|
|
602
|
+
subset = values_series[mask]
|
|
603
|
+
subset_mr = moving_range[mask].dropna()
|
|
604
|
+
phase_center = float(subset.mean())
|
|
605
|
+
phase_mrbar = float(subset_mr.mean()) if len(subset_mr) else 0.0
|
|
606
|
+
phase_sigma = phase_mrbar / _D2[2] if phase_mrbar else float(subset.std(ddof=1) or 0.0)
|
|
607
|
+
count = int(mask.sum())
|
|
608
|
+
centers.extend([phase_center] * count)
|
|
609
|
+
ucls.extend([phase_center + 3 * phase_sigma] * count)
|
|
610
|
+
lcls.extend([phase_center - 3 * phase_sigma] * count)
|
|
611
|
+
mr_centers.extend([phase_mrbar] * count)
|
|
612
|
+
mr_ucls.extend([_D4[2] * phase_mrbar] * count)
|
|
613
|
+
mr_lcls.extend([0.0] * count)
|
|
614
|
+
center_array = np.array(centers)
|
|
615
|
+
ucl_array = np.array(ucls)
|
|
616
|
+
lcl_array = np.array(lcls)
|
|
617
|
+
table = pd.DataFrame({
|
|
618
|
+
"Observation": np.arange(1, len(values_series) + 1),
|
|
619
|
+
"Phase": phase_series.astype(str).to_numpy(),
|
|
620
|
+
"Value": values_series.to_numpy(),
|
|
621
|
+
"Moving Range": moving_range.to_numpy(),
|
|
622
|
+
"Center": center_array, "UCL": ucl_array, "LCL": lcl_array,
|
|
623
|
+
"MR Center": np.array(mr_centers), "MR UCL": np.array(mr_ucls), "MR LCL": np.array(mr_lcls),
|
|
624
|
+
})
|
|
625
|
+
table["Status"] = _run_rules_arrays(table["Value"].to_numpy(dtype=float), center_array, ucl_array, lcl_array, rules=rules)
|
|
626
|
+
center = float(center_array[0])
|
|
627
|
+
ucl = float(ucl_array[0])
|
|
628
|
+
lcl = float(lcl_array[0])
|
|
629
|
+
sigma = (ucl - center) / 3
|
|
630
|
+
else:
|
|
631
|
+
mrbar = float(moving_range.dropna().mean())
|
|
632
|
+
center = float(values_series.mean())
|
|
633
|
+
sigma = mrbar / _D2[2] if mrbar else float(values_series.std(ddof=1))
|
|
634
|
+
ucl, lcl = center + 3 * sigma, center - 3 * sigma
|
|
635
|
+
table = pd.DataFrame({
|
|
636
|
+
"Observation": np.arange(1, len(values_series) + 1),
|
|
637
|
+
"Value": values_series.to_numpy(),
|
|
638
|
+
"Moving Range": moving_range.to_numpy(),
|
|
639
|
+
"Center": center, "UCL": ucl, "LCL": lcl,
|
|
640
|
+
"MR Center": mrbar, "MR UCL": _D4[2] * mrbar, "MR LCL": 0.0,
|
|
641
|
+
})
|
|
642
|
+
table["Status"] = _run_rules(table["Value"].to_numpy(dtype=float), center, ucl, lcl, rules=rules)
|
|
643
|
+
result.add_table("Control Chart Data", table)
|
|
644
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "Value", "center": "Center", "ucl": "UCL", "lcl": "LCL", "status": "Status"}, title="Individuals Chart", data=table)
|
|
645
|
+
result.add_plot("control_chart", {"x": "Observation", "value": "Moving Range", "center": "MR Center", "ucl": "MR UCL", "lcl": "MR LCL"}, title="Moving Range Chart", data=table)
|
|
646
|
+
result.summary = f"Center {center:.4g}, sigma {sigma:.4g}, UCL {ucl:.4g}, LCL {lcl:.4g}."
|
|
647
|
+
return result
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def capability(
|
|
651
|
+
df: pd.DataFrame,
|
|
652
|
+
column: str,
|
|
653
|
+
lsl: float | None = None,
|
|
654
|
+
usl: float | None = None,
|
|
655
|
+
target: float | None = None,
|
|
656
|
+
sigma_method: str = "moving_range",
|
|
657
|
+
subgroup: str | None = None,
|
|
658
|
+
historical_sigma: float | None = None,
|
|
659
|
+
nonnormal: str | None = None,
|
|
660
|
+
confidence: float = 0.95,
|
|
661
|
+
) -> AnalysisResult:
|
|
662
|
+
if column not in df.columns:
|
|
663
|
+
raise KeyError(column)
|
|
664
|
+
raw_values = pd.to_numeric(df[column], errors="coerce")
|
|
665
|
+
values = raw_values.dropna()
|
|
666
|
+
if len(values) < 2:
|
|
667
|
+
raise ValueError("At least two observations are required.")
|
|
668
|
+
if lsl is None and usl is None:
|
|
669
|
+
raise ValueError("Specify at least one specification limit.")
|
|
670
|
+
distribution_name = str(nonnormal or "normal").lower()
|
|
671
|
+
capability_aliases = {"weibull": "weibull_min", "lognormal": "lognorm"}
|
|
672
|
+
distribution_name = capability_aliases.get(distribution_name, distribution_name)
|
|
673
|
+
if distribution_name not in {"normal", "boxcox", "box-cox", "weibull_min", "lognorm", "gamma", "expon", "loglogistic", "logistic"}:
|
|
674
|
+
raise ValueError(f"Unsupported capability distribution: {nonnormal}")
|
|
675
|
+
transformed_lambda = None
|
|
676
|
+
work_values = values.astype(float)
|
|
677
|
+
work_lsl, work_usl, work_target = lsl, usl, target
|
|
678
|
+
if nonnormal and str(nonnormal).lower() in {"boxcox", "box-cox"}:
|
|
679
|
+
if (work_values <= 0).any():
|
|
680
|
+
raise ValueError("Box-Cox capability requires positive response values.")
|
|
681
|
+
transformed, transformed_lambda = _scipy_stats.boxcox(work_values.to_numpy(dtype=float))
|
|
682
|
+
work_values = pd.Series(transformed, index=values.index)
|
|
683
|
+
|
|
684
|
+
def transform_limit(value: float | None) -> float | None:
|
|
685
|
+
if value is None:
|
|
686
|
+
return None
|
|
687
|
+
if value > 0:
|
|
688
|
+
return float(_scipy_stats.boxcox(np.array([value]), transformed_lambda)[0])
|
|
689
|
+
if value == 0 and transformed_lambda > 0:
|
|
690
|
+
return float(-1.0 / transformed_lambda)
|
|
691
|
+
return float("-inf")
|
|
692
|
+
|
|
693
|
+
work_lsl = transform_limit(work_lsl)
|
|
694
|
+
work_usl = transform_limit(work_usl)
|
|
695
|
+
work_target = transform_limit(work_target)
|
|
696
|
+
mean = float(work_values.mean())
|
|
697
|
+
std_overall = float(work_values.std(ddof=1))
|
|
698
|
+
method = sigma_method.lower()
|
|
699
|
+
std_within = std_overall
|
|
700
|
+
if historical_sigma is not None and historical_sigma > 0:
|
|
701
|
+
std_within = float(historical_sigma)
|
|
702
|
+
elif method in {"rbar", "range", "sbar", "pooled"} and subgroup and subgroup in df.columns:
|
|
703
|
+
frame = df.loc[:, [column, subgroup]].copy()
|
|
704
|
+
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
|
705
|
+
frame = frame.dropna()
|
|
706
|
+
groups = frame.groupby(subgroup, sort=False)[column]
|
|
707
|
+
sizes = groups.count()
|
|
708
|
+
n = max(2, min(int(sizes.median()), 25))
|
|
709
|
+
if method == "pooled":
|
|
710
|
+
variances = groups.var(ddof=1)
|
|
711
|
+
weights = (sizes - 1).clip(lower=0)
|
|
712
|
+
pooled_var = float((variances * weights).sum() / weights.sum()) if weights.sum() else std_overall**2
|
|
713
|
+
std_within = math.sqrt(max(pooled_var, 0.0))
|
|
714
|
+
elif method == "sbar":
|
|
715
|
+
spread = groups.std(ddof=1).dropna()
|
|
716
|
+
std_within = float(spread.mean() / _C4[n]) if len(spread) else std_overall
|
|
717
|
+
else:
|
|
718
|
+
spread = groups.max() - groups.min()
|
|
719
|
+
std_within = float(spread.mean() / _D2[n]) if len(spread) else std_overall
|
|
720
|
+
elif method in {"median_mr", "median_moving_range"}:
|
|
721
|
+
moving = raw_values.diff().abs().dropna()
|
|
722
|
+
std_within = float(moving.median() / 0.954) if len(moving) else std_overall
|
|
723
|
+
elif method != "overall":
|
|
724
|
+
moving = raw_values.diff().abs().dropna()
|
|
725
|
+
std_within = float(moving.mean() / _D2[2]) if len(moving) else std_overall
|
|
726
|
+
|
|
727
|
+
def ratio(numerator, denominator):
|
|
728
|
+
return numerator / denominator if denominator else np.nan
|
|
729
|
+
|
|
730
|
+
cp = ratio(work_usl - work_lsl, 6 * std_within) if work_lsl is not None and work_usl is not None else np.nan
|
|
731
|
+
cpu = ratio(work_usl - mean, 3 * std_within) if work_usl is not None else np.nan
|
|
732
|
+
cpl = ratio(mean - work_lsl, 3 * std_within) if work_lsl is not None else np.nan
|
|
733
|
+
cpk = min(cpu, cpl) if not (np.isnan(cpu) or np.isnan(cpl)) else np.nan
|
|
734
|
+
pp = ratio(work_usl - work_lsl, 6 * std_overall) if work_lsl is not None and work_usl is not None else np.nan
|
|
735
|
+
ppu = ratio(work_usl - mean, 3 * std_overall) if work_usl is not None else np.nan
|
|
736
|
+
ppl = ratio(mean - work_lsl, 3 * std_overall) if work_lsl is not None else np.nan
|
|
737
|
+
ppk = min(ppu, ppl) if not (np.isnan(ppu) or np.isnan(ppl)) else np.nan
|
|
738
|
+
cpm = np.nan
|
|
739
|
+
if work_lsl is not None and work_usl is not None and work_target is not None and std_within:
|
|
740
|
+
cpm = (work_usl - work_lsl) / (6 * math.sqrt(std_within**2 + (mean - work_target) ** 2))
|
|
741
|
+
fitted_distribution = None
|
|
742
|
+
fitted_parameters = None
|
|
743
|
+
if distribution_name not in {"normal", "boxcox", "box-cox"}:
|
|
744
|
+
from statstudio.stats.distributions import DISTRIBUTIONS, POSITIVE, SCIPY_ALIASES, SCIPY_NAMES
|
|
745
|
+
|
|
746
|
+
if distribution_name in POSITIVE and (values <= 0).any():
|
|
747
|
+
raise ValueError(f"{DISTRIBUTIONS[distribution_name]} requires positive values.")
|
|
748
|
+
scipy_name = SCIPY_NAMES.get(distribution_name, SCIPY_ALIASES.get(distribution_name, distribution_name))
|
|
749
|
+
fitted_distribution = getattr(_scipy_stats, scipy_name)
|
|
750
|
+
fitted_parameters = fitted_distribution.fit(values.to_numpy(dtype=float))
|
|
751
|
+
ppm_below = float(fitted_distribution.cdf(work_lsl, *fitted_parameters) * 1e6) if work_lsl is not None else np.nan
|
|
752
|
+
ppm_above = float((1 - fitted_distribution.cdf(work_usl, *fitted_parameters)) * 1e6) if work_usl is not None else np.nan
|
|
753
|
+
else:
|
|
754
|
+
ppm_below = float(_scipy_stats.norm.cdf((work_lsl - mean) / std_overall) * 1e6) if work_lsl is not None and std_overall else np.nan
|
|
755
|
+
ppm_above = float((1 - _scipy_stats.norm.cdf((work_usl - mean) / std_overall)) * 1e6) if work_usl is not None and std_overall else np.nan
|
|
756
|
+
ppm_total = np.nansum([ppm_below, ppm_above]) if not (np.isnan(ppm_below) and np.isnan(ppm_above)) else np.nan
|
|
757
|
+
sigma_level = (
|
|
758
|
+
float(_scipy_stats.norm.ppf(1 - ppm_total / 1e6))
|
|
759
|
+
if np.isfinite(ppm_total) and 0 < ppm_total < 1e6
|
|
760
|
+
else np.nan
|
|
761
|
+
)
|
|
762
|
+
alpha = 1 - confidence
|
|
763
|
+
df_value = max(1, len(values) - 1)
|
|
764
|
+
cp_low = cp_high = cpk_low = cpk_high = ppk_low = ppk_high = np.nan
|
|
765
|
+
if np.isfinite(cp):
|
|
766
|
+
cp_low = cp * math.sqrt(_scipy_stats.chi2.ppf(alpha / 2, df_value) / df_value)
|
|
767
|
+
cp_high = cp * math.sqrt(_scipy_stats.chi2.ppf(1 - alpha / 2, df_value) / df_value)
|
|
768
|
+
if np.isfinite(cpk):
|
|
769
|
+
se_cpk = math.sqrt(1 / (9 * len(values)) + cpk**2 / (2 * max(1, len(values) - 1)))
|
|
770
|
+
z_value = _scipy_stats.norm.ppf(1 - alpha / 2)
|
|
771
|
+
cpk_low, cpk_high = cpk - z_value * se_cpk, cpk + z_value * se_cpk
|
|
772
|
+
if np.isfinite(ppk):
|
|
773
|
+
se_ppk = math.sqrt(1 / (9 * len(values)) + ppk**2 / (2 * max(1, len(values) - 1)))
|
|
774
|
+
z_value = _scipy_stats.norm.ppf(1 - alpha / 2)
|
|
775
|
+
ppk_low, ppk_high = ppk - z_value * se_ppk, ppk + z_value * se_ppk
|
|
776
|
+
table = pd.DataFrame([{
|
|
777
|
+
"N": len(values), "Mean": mean, "Std Dev (Within)": std_within, "Std Dev (Overall)": std_overall,
|
|
778
|
+
"LSL": lsl, "Target": target, "USL": usl, "Cp": cp, "Cpl": cpl, "Cpu": cpu, "Cpk": cpk,
|
|
779
|
+
"Cp Lower": cp_low, "Cp Upper": cp_high, "Cpk Lower": cpk_low, "Cpk Upper": cpk_high,
|
|
780
|
+
"Pp": pp, "Ppl": ppl, "Ppu": ppu, "Ppk": ppk, "Ppk Lower": ppk_low, "Ppk Upper": ppk_high, "Cpm": cpm,
|
|
781
|
+
"PPM Below": ppm_below, "PPM Above": ppm_above, "PPM Total": ppm_total,
|
|
782
|
+
"Sigma Level": sigma_level,
|
|
783
|
+
"Sigma Method": sigma_method,
|
|
784
|
+
"Box-Cox Lambda": transformed_lambda if transformed_lambda is not None else np.nan,
|
|
785
|
+
"Distribution": distribution_name,
|
|
786
|
+
"Confidence": confidence,
|
|
787
|
+
}])
|
|
788
|
+
result = AnalysisResult(
|
|
789
|
+
title=f"Process Capability: {column}",
|
|
790
|
+
analysis_type="capability",
|
|
791
|
+
params={
|
|
792
|
+
"column": column,
|
|
793
|
+
"lsl": lsl,
|
|
794
|
+
"usl": usl,
|
|
795
|
+
"target": target,
|
|
796
|
+
"sigma_method": sigma_method,
|
|
797
|
+
"subgroup": subgroup,
|
|
798
|
+
"historical_sigma": historical_sigma,
|
|
799
|
+
"nonnormal": nonnormal,
|
|
800
|
+
"confidence": confidence,
|
|
801
|
+
},
|
|
802
|
+
)
|
|
803
|
+
result.add_table("Capability Indices", table)
|
|
804
|
+
result.add_plot("capability", {"column": column, "lsl": lsl, "usl": usl, "target": target}, title=f"Capability Histogram: {column}", data=df)
|
|
805
|
+
result.add_plot("sixpack", {"column": column, "lsl": lsl, "usl": usl, "target": target}, title=f"Six-Pack: {column}", data=df)
|
|
806
|
+
notes = []
|
|
807
|
+
if transformed_lambda is not None:
|
|
808
|
+
notes.append(f"Box-Cox transformation applied with lambda = {transformed_lambda:.4f}; limits were transformed for the analysis.")
|
|
809
|
+
if fitted_distribution is not None:
|
|
810
|
+
notes.append("Nonnormal capability uses fitted-distribution tail probabilities; Cp/Cpk remain normal-scale indices.")
|
|
811
|
+
notes.append("Cpm uses within-subgroup sigma and Sigma Level is the Z Bench: Phi^-1(1 - total PPM/1e6).")
|
|
812
|
+
if notes:
|
|
813
|
+
result.notes = " ".join(notes)
|
|
814
|
+
result.summary = f"Cp = {cp:.3g}, Cpk = {cpk:.3g}, Ppk = {ppk:.3g}, N = {len(values)}."
|
|
815
|
+
return result
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def gage_rr(
|
|
819
|
+
df: pd.DataFrame,
|
|
820
|
+
measurement: str,
|
|
821
|
+
part: str,
|
|
822
|
+
operator: str,
|
|
823
|
+
design: str = "crossed",
|
|
824
|
+
interaction: bool = True,
|
|
825
|
+
batch: str | None = None,
|
|
826
|
+
tolerance: float | None = None,
|
|
827
|
+
) -> AnalysisResult:
|
|
828
|
+
for column in [measurement, part, operator]:
|
|
829
|
+
if column not in df.columns:
|
|
830
|
+
raise KeyError(column)
|
|
831
|
+
columns = [measurement, part, operator] + ([batch] if batch and batch in df.columns else [])
|
|
832
|
+
frame = df[columns].copy()
|
|
833
|
+
frame[measurement] = pd.to_numeric(frame[measurement], errors="coerce")
|
|
834
|
+
frame = frame.dropna()
|
|
835
|
+
if frame[part].nunique() < 2 or frame[operator].nunique() < 2:
|
|
836
|
+
raise ValueError("Gage R&R requires at least two parts and two operators.")
|
|
837
|
+
if design == "nested":
|
|
838
|
+
return _gage_nested(frame, measurement, part, operator, tolerance=tolerance)
|
|
839
|
+
if design == "expanded" and batch and batch in frame.columns and frame[batch].nunique() > 1:
|
|
840
|
+
return _gage_expanded(frame, measurement, part, operator, batch, tolerance=tolerance)
|
|
841
|
+
formula = f'Q("{measurement}") ~ C(Q("{part}")) * C(Q("{operator}"))' if interaction else f'Q("{measurement}") ~ C(Q("{part}")) + C(Q("{operator}"))'
|
|
842
|
+
try:
|
|
843
|
+
model = _smf.ols(formula, data=frame).fit()
|
|
844
|
+
anova = _scipy_stats_anova(model)
|
|
845
|
+
except Exception as exc:
|
|
846
|
+
raise ValueError(f"Gage R&R model failed: {exc}") from exc
|
|
847
|
+
mse = float(model.mse_resid)
|
|
848
|
+
components = {}
|
|
849
|
+
try:
|
|
850
|
+
ms = anova.set_index("Source")["mean_sq"]
|
|
851
|
+
n_operators = frame[operator].nunique()
|
|
852
|
+
n_parts = frame[part].nunique()
|
|
853
|
+
n_reps = len(frame) / (n_parts * n_operators)
|
|
854
|
+
ms_part = float(ms.get(f'C(Q("{part}"))', np.nan))
|
|
855
|
+
ms_oper = float(ms.get(f'C(Q("{operator}"))', np.nan))
|
|
856
|
+
interaction_name = f'C(Q("{part}")):C(Q("{operator}"))'
|
|
857
|
+
ms_inter = float(ms.get(interaction_name, np.nan))
|
|
858
|
+
components["Repeatability"] = mse
|
|
859
|
+
if interaction and not np.isnan(ms_inter):
|
|
860
|
+
components["Interaction"] = max(0.0, (ms_inter - mse) / n_reps)
|
|
861
|
+
else:
|
|
862
|
+
components["Interaction"] = 0.0
|
|
863
|
+
components["Operator"] = max(0.0, (ms_oper - (ms_inter if interaction else mse)) / (n_parts * n_reps))
|
|
864
|
+
components["Part"] = max(0.0, (ms_part - (ms_inter if interaction else mse)) / (n_operators * n_reps))
|
|
865
|
+
except Exception:
|
|
866
|
+
components = {"Repeatability": mse, "Interaction": 0.0, "Operator": 0.0, "Part": max(0.0, float(frame.groupby(part)[measurement].mean().var()))}
|
|
867
|
+
grr = components.get("Repeatability", 0.0) + components.get("Interaction", 0.0) + components.get("Operator", 0.0)
|
|
868
|
+
total = grr + components.get("Part", 0.0)
|
|
869
|
+
rows = []
|
|
870
|
+
for name, variance in [("Repeatability", components.get("Repeatability", 0.0)), ("Operator", components.get("Operator", 0.0)), ("Interaction", components.get("Interaction", 0.0)), ("Part", components.get("Part", 0.0)), ("Total", total)]:
|
|
871
|
+
rows.append({"Component": name, "Variance": variance, "Contribution %": (variance / total * 100) if total else np.nan, "Std Dev": math.sqrt(max(variance, 0.0)), "Study Var (6SD)": 6 * math.sqrt(max(variance, 0.0)), "%Study Var": (6 * math.sqrt(max(variance, 0.0)) / (6 * math.sqrt(total)) * 100) if total else np.nan})
|
|
872
|
+
components_table = pd.DataFrame(rows)
|
|
873
|
+
ndc = int(1.41 * math.sqrt(components.get("Part", 0.0)) / math.sqrt(grr)) if grr > 0 else np.nan
|
|
874
|
+
summary = pd.DataFrame([{
|
|
875
|
+
"Gage R&R %Contribution": grr / total * 100 if total else np.nan,
|
|
876
|
+
"Gage R&R %Study Var": (6 * math.sqrt(grr)) / (6 * math.sqrt(total)) * 100 if total else np.nan,
|
|
877
|
+
"%Tolerance": (6 * math.sqrt(grr) / tolerance * 100) if tolerance and tolerance > 0 else np.nan,
|
|
878
|
+
"ndc": ndc,
|
|
879
|
+
}])
|
|
880
|
+
result = AnalysisResult(title=f"Gage R&R: {measurement}", analysis_type="gage_rr", params={"measurement": measurement, "part": part, "operator": operator, "design": design, "interaction": interaction, "tolerance": tolerance})
|
|
881
|
+
result.add_table("ANOVA", anova)
|
|
882
|
+
result.add_table("Variance Components", components_table)
|
|
883
|
+
result.add_table("Gage R&R Summary", summary)
|
|
884
|
+
result.add_plot("box", {"column": measurement, "group": part}, title=f"{measurement} by Part", data=frame)
|
|
885
|
+
result.summary = f"%GRR (study var) = {summary['Gage R&R %Study Var'].iloc[0]:.2f}%, ndc = {ndc}."
|
|
886
|
+
return result
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _scipy_stats_anova(model):
|
|
890
|
+
from statsmodels.stats.anova import anova_lm
|
|
891
|
+
|
|
892
|
+
frame = anova_lm(model, typ=2).reset_index()
|
|
893
|
+
frame = frame.rename(columns={frame.columns[0]: "Source"})
|
|
894
|
+
if "mean_sq" not in frame.columns and "sum_sq" in frame.columns and "df" in frame.columns:
|
|
895
|
+
frame["mean_sq"] = frame["sum_sq"] / frame["df"]
|
|
896
|
+
return frame
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def _gage_nested(frame: pd.DataFrame, measurement: str, part: str, operator: str, tolerance: float | None = None) -> AnalysisResult:
|
|
901
|
+
if (frame.groupby(part, observed=True)[operator].nunique() > 1).any():
|
|
902
|
+
raise ValueError("Nested Gage R&R requires each part to be measured by exactly one operator.")
|
|
903
|
+
counts = frame.groupby([operator, part], observed=True)[measurement].size()
|
|
904
|
+
if counts.empty or int(counts.min()) < 2:
|
|
905
|
+
raise ValueError("Nested Gage R&R requires at least two replicates per part.")
|
|
906
|
+
if counts.nunique() != 1:
|
|
907
|
+
raise ValueError("Nested Gage R&R requires equal replicates for every part.")
|
|
908
|
+
parts_per_operator = frame.groupby(operator, observed=True)[part].nunique()
|
|
909
|
+
if parts_per_operator.nunique() != 1 or int(parts_per_operator.min()) < 2:
|
|
910
|
+
raise ValueError("Nested Gage R&R requires the same number of parts for every operator.")
|
|
911
|
+
replicates = int(counts.iloc[0])
|
|
912
|
+
parts = int(parts_per_operator.iloc[0])
|
|
913
|
+
|
|
914
|
+
working = frame.copy()
|
|
915
|
+
working["_gage_part_index"] = working.groupby(operator, observed=True)[part].transform(
|
|
916
|
+
lambda values: pd.factorize(values)[0] + 1
|
|
917
|
+
)
|
|
918
|
+
model = _smf.ols(
|
|
919
|
+
f'Q("{measurement}") ~ C(Q("{operator}")) * C(Q("_gage_part_index"))',
|
|
920
|
+
data=working,
|
|
921
|
+
).fit()
|
|
922
|
+
anova = _scipy_stats_anova(model).set_index("Source")
|
|
923
|
+
operator_name = f'C(Q("{operator}"))'
|
|
924
|
+
part_name = 'C(Q("_gage_part_index"))'
|
|
925
|
+
interaction_name = f'C(Q("{operator}")):C(Q("_gage_part_index"))'
|
|
926
|
+
|
|
927
|
+
def mean_square(source: str) -> float:
|
|
928
|
+
if source not in anova.index:
|
|
929
|
+
return float("nan")
|
|
930
|
+
return float(anova.loc[source, "sum_sq"]) / float(anova.loc[source, "df"])
|
|
931
|
+
|
|
932
|
+
ms_operator = mean_square(operator_name)
|
|
933
|
+
ss_part = float(anova.loc[part_name, "sum_sq"]) + float(anova.loc[interaction_name, "sum_sq"])
|
|
934
|
+
df_part = float(anova.loc[part_name, "df"]) + float(anova.loc[interaction_name, "df"])
|
|
935
|
+
ms_part = ss_part / df_part
|
|
936
|
+
ss_residual = float(anova.loc["Residual", "sum_sq"])
|
|
937
|
+
df_residual = float(anova.loc["Residual", "df"])
|
|
938
|
+
mse = ss_residual / df_residual
|
|
939
|
+
|
|
940
|
+
repeatability = mse
|
|
941
|
+
part_operator = max(0.0, (ms_part - mse) / replicates)
|
|
942
|
+
operator_component = max(0.0, (ms_operator - ms_part) / (parts * replicates))
|
|
943
|
+
grr = repeatability + operator_component
|
|
944
|
+
total = grr + part_operator
|
|
945
|
+
|
|
946
|
+
anova_rows = [
|
|
947
|
+
{
|
|
948
|
+
"Source": operator,
|
|
949
|
+
"sum_sq": float(anova.loc[operator_name, "sum_sq"]),
|
|
950
|
+
"df": float(anova.loc[operator_name, "df"]),
|
|
951
|
+
"mean_sq": ms_operator,
|
|
952
|
+
"F": ms_operator / ms_part if ms_part else np.nan,
|
|
953
|
+
"p-value": float(_scipy_stats.f.sf(ms_operator / ms_part, float(anova.loc[operator_name, "df"]), df_part)) if ms_part else np.nan,
|
|
954
|
+
},
|
|
955
|
+
{
|
|
956
|
+
"Source": f"Part ({operator})",
|
|
957
|
+
"sum_sq": ss_part,
|
|
958
|
+
"df": df_part,
|
|
959
|
+
"mean_sq": ms_part,
|
|
960
|
+
"F": ms_part / mse if mse else np.nan,
|
|
961
|
+
"p-value": float(_scipy_stats.f.sf(ms_part / mse, df_part, df_residual)) if mse else np.nan,
|
|
962
|
+
},
|
|
963
|
+
{
|
|
964
|
+
"Source": "Residual",
|
|
965
|
+
"sum_sq": ss_residual,
|
|
966
|
+
"df": df_residual,
|
|
967
|
+
"mean_sq": mse,
|
|
968
|
+
"F": np.nan,
|
|
969
|
+
"p-value": np.nan,
|
|
970
|
+
},
|
|
971
|
+
]
|
|
972
|
+
|
|
973
|
+
rows = []
|
|
974
|
+
for name, variance in [("Repeatability", repeatability), ("Operator", operator_component), ("Part (Operator)", part_operator), ("Total", total)]:
|
|
975
|
+
rows.append({
|
|
976
|
+
"Component": name,
|
|
977
|
+
"Variance": variance,
|
|
978
|
+
"Contribution %": (variance / total * 100) if total else np.nan,
|
|
979
|
+
"Std Dev": math.sqrt(max(variance, 0.0)),
|
|
980
|
+
"Study Var (6SD)": 6 * math.sqrt(max(variance, 0.0)),
|
|
981
|
+
"%Study Var": (math.sqrt(max(variance, 0.0)) / math.sqrt(total) * 100) if total else np.nan,
|
|
982
|
+
})
|
|
983
|
+
ndc = int(1.41 * math.sqrt(part_operator) / math.sqrt(grr)) if grr > 0 else np.nan
|
|
984
|
+
summary = pd.DataFrame([{
|
|
985
|
+
"Gage R&R %Contribution": grr / total * 100 if total else np.nan,
|
|
986
|
+
"Gage R&R %Study Var": math.sqrt(grr / total) * 100 if total else np.nan,
|
|
987
|
+
"%Tolerance": (6 * math.sqrt(grr) / tolerance * 100) if tolerance and tolerance > 0 else np.nan,
|
|
988
|
+
"ndc": ndc,
|
|
989
|
+
}])
|
|
990
|
+
result = AnalysisResult(title=f"Gage R&R (Nested): {measurement}", analysis_type="gage_rr", params={"measurement": measurement, "part": part, "operator": operator, "design": "nested", "tolerance": tolerance})
|
|
991
|
+
result.add_table("ANOVA", pd.DataFrame(anova_rows))
|
|
992
|
+
result.add_table("Variance Components", pd.DataFrame(rows))
|
|
993
|
+
result.add_table("Gage R&R Summary", summary)
|
|
994
|
+
result.add_plot("box", {"column": measurement, "group": part}, title=f"{measurement} by Part", data=frame)
|
|
995
|
+
result.summary = f"Nested %GRR (study var) = {summary['Gage R&R %Study Var'].iloc[0]:.2f}%, ndc = {ndc}."
|
|
996
|
+
return result
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def _gage_expanded(frame: pd.DataFrame, measurement: str, part: str, operator: str, batch: str, tolerance: float | None = None) -> AnalysisResult:
|
|
1000
|
+
if (frame.groupby(part, observed=True)[batch].nunique() > 1).any():
|
|
1001
|
+
raise ValueError("Expanded Gage R&R requires each part to belong to exactly one batch.")
|
|
1002
|
+
parts_per_batch = frame.groupby(batch, observed=True)[part].nunique()
|
|
1003
|
+
if parts_per_batch.nunique() != 1 or int(parts_per_batch.min()) < 2:
|
|
1004
|
+
raise ValueError("Expanded Gage R&R requires the same number of parts in every batch.")
|
|
1005
|
+
counts = frame.groupby([part, operator], observed=True)[measurement].size()
|
|
1006
|
+
if counts.empty or int(counts.min()) < 2:
|
|
1007
|
+
raise ValueError("Expanded Gage R&R requires at least two replicates per part and operator.")
|
|
1008
|
+
if counts.nunique() != 1:
|
|
1009
|
+
raise ValueError("Expanded Gage R&R requires equal replicates for every part and operator.")
|
|
1010
|
+
replicates = int(counts.iloc[0])
|
|
1011
|
+
parts = int(parts_per_batch.iloc[0])
|
|
1012
|
+
operators = int(frame[operator].nunique())
|
|
1013
|
+
batches = int(frame[batch].nunique())
|
|
1014
|
+
|
|
1015
|
+
working = frame.copy()
|
|
1016
|
+
working["_gage_part_index"] = working.groupby(batch, observed=True)[part].transform(
|
|
1017
|
+
lambda values: pd.factorize(values)[0] + 1
|
|
1018
|
+
)
|
|
1019
|
+
model = _smf.ols(
|
|
1020
|
+
f'Q("{measurement}") ~ C(Q("{operator}")) * C(Q("{batch}")) * C(Q("_gage_part_index"))',
|
|
1021
|
+
data=working,
|
|
1022
|
+
).fit()
|
|
1023
|
+
anova = _scipy_stats_anova(model).set_index("Source")
|
|
1024
|
+
operator_name = f'C(Q("{operator}"))'
|
|
1025
|
+
batch_name = f'C(Q("{batch}"))'
|
|
1026
|
+
operator_batch_name = f'C(Q("{operator}")):C(Q("{batch}"))'
|
|
1027
|
+
index_name = 'C(Q("_gage_part_index"))'
|
|
1028
|
+
batch_index_name = f'C(Q("{batch}")):C(Q("_gage_part_index"))'
|
|
1029
|
+
operator_index_name = f'C(Q("{operator}")):C(Q("_gage_part_index"))'
|
|
1030
|
+
operator_batch_index_name = f'C(Q("{operator}")):C(Q("{batch}")):C(Q("_gage_part_index"))'
|
|
1031
|
+
|
|
1032
|
+
def mean_square(source: str) -> float:
|
|
1033
|
+
if source not in anova.index:
|
|
1034
|
+
return float("nan")
|
|
1035
|
+
return float(anova.loc[source, "sum_sq"]) / float(anova.loc[source, "df"])
|
|
1036
|
+
|
|
1037
|
+
def pooled(names: list[str]) -> tuple[float, float, float]:
|
|
1038
|
+
sources = [name for name in names if name in anova.index]
|
|
1039
|
+
ss = float(sum(anova.loc[name, "sum_sq"] for name in sources))
|
|
1040
|
+
df = float(sum(anova.loc[name, "df"] for name in sources))
|
|
1041
|
+
return ss, df, ss / df if df else float("nan")
|
|
1042
|
+
|
|
1043
|
+
ms_operator = mean_square(operator_name)
|
|
1044
|
+
ms_batch = mean_square(batch_name)
|
|
1045
|
+
ms_operator_batch = mean_square(operator_batch_name)
|
|
1046
|
+
ss_part, df_part, ms_part = pooled([index_name, batch_index_name])
|
|
1047
|
+
ss_operator_part, df_operator_part, ms_operator_part = pooled([operator_index_name, operator_batch_index_name])
|
|
1048
|
+
ss_residual = float(anova.loc["Residual", "sum_sq"])
|
|
1049
|
+
df_residual = float(anova.loc["Residual", "df"])
|
|
1050
|
+
mse = ss_residual / df_residual
|
|
1051
|
+
|
|
1052
|
+
repeatability = mse
|
|
1053
|
+
interaction = max(0.0, (ms_operator_part - mse) / replicates)
|
|
1054
|
+
part_component = max(0.0, (ms_part - ms_operator_part) / (operators * replicates))
|
|
1055
|
+
operator_batch = max(0.0, (ms_operator_batch - ms_operator_part) / (parts * replicates))
|
|
1056
|
+
batch_component = max(0.0, (ms_batch - ms_part - ms_operator_batch + ms_operator_part) / (operators * parts * replicates))
|
|
1057
|
+
operator_component = max(0.0, (ms_operator - ms_operator_batch) / (batches * parts * replicates))
|
|
1058
|
+
grr = repeatability + interaction + operator_batch + operator_component
|
|
1059
|
+
total = grr + part_component + batch_component
|
|
1060
|
+
|
|
1061
|
+
anova_rows = [
|
|
1062
|
+
{"Source": operator, "sum_sq": float(anova.loc[operator_name, "sum_sq"]), "df": float(anova.loc[operator_name, "df"]), "mean_sq": ms_operator, "F": ms_operator / ms_operator_batch if ms_operator_batch else np.nan, "p-value": float(_scipy_stats.f.sf(ms_operator / ms_operator_batch, float(anova.loc[operator_name, "df"]), float(anova.loc[operator_batch_name, "df"]))) if ms_operator_batch else np.nan},
|
|
1063
|
+
{"Source": batch, "sum_sq": float(anova.loc[batch_name, "sum_sq"]), "df": float(anova.loc[batch_name, "df"]), "mean_sq": ms_batch, "F": ms_batch / ms_part if ms_part else np.nan, "p-value": float(_scipy_stats.f.sf(ms_batch / ms_part, float(anova.loc[batch_name, "df"]), df_part)) if ms_part else np.nan},
|
|
1064
|
+
{"Source": f"{operator} x {batch}", "sum_sq": float(anova.loc[operator_batch_name, "sum_sq"]), "df": float(anova.loc[operator_batch_name, "df"]), "mean_sq": ms_operator_batch, "F": ms_operator_batch / ms_operator_part if ms_operator_part else np.nan, "p-value": float(_scipy_stats.f.sf(ms_operator_batch / ms_operator_part, float(anova.loc[operator_batch_name, "df"]), df_operator_part)) if ms_operator_part else np.nan},
|
|
1065
|
+
{"Source": f"Part ({batch})", "sum_sq": ss_part, "df": df_part, "mean_sq": ms_part, "F": ms_part / ms_operator_part if ms_operator_part else np.nan, "p-value": float(_scipy_stats.f.sf(ms_part / ms_operator_part, df_part, df_operator_part)) if ms_operator_part else np.nan},
|
|
1066
|
+
{"Source": f"{operator} x Part ({batch})", "sum_sq": ss_operator_part, "df": df_operator_part, "mean_sq": ms_operator_part, "F": ms_operator_part / mse if mse else np.nan, "p-value": float(_scipy_stats.f.sf(ms_operator_part / mse, df_operator_part, df_residual)) if mse else np.nan},
|
|
1067
|
+
{"Source": "Residual", "sum_sq": ss_residual, "df": df_residual, "mean_sq": mse, "F": np.nan, "p-value": np.nan},
|
|
1068
|
+
]
|
|
1069
|
+
|
|
1070
|
+
rows = []
|
|
1071
|
+
for name, variance in [
|
|
1072
|
+
("Repeatability", repeatability),
|
|
1073
|
+
("Operator", operator_component),
|
|
1074
|
+
("Operator x Batch", operator_batch),
|
|
1075
|
+
("Interaction (3-way)", interaction),
|
|
1076
|
+
("Batch", batch_component),
|
|
1077
|
+
("Part (Batch)", part_component),
|
|
1078
|
+
("Total", total),
|
|
1079
|
+
]:
|
|
1080
|
+
rows.append({
|
|
1081
|
+
"Component": name,
|
|
1082
|
+
"Variance": variance,
|
|
1083
|
+
"Contribution %": (variance / total * 100) if total else np.nan,
|
|
1084
|
+
"Std Dev": math.sqrt(max(variance, 0.0)),
|
|
1085
|
+
"Study Var (6SD)": 6 * math.sqrt(max(variance, 0.0)),
|
|
1086
|
+
"%Study Var": (math.sqrt(max(variance, 0.0)) / math.sqrt(total) * 100) if total else np.nan,
|
|
1087
|
+
})
|
|
1088
|
+
ndc = int(1.41 * math.sqrt(part_component) / math.sqrt(grr)) if grr > 0 else np.nan
|
|
1089
|
+
summary = pd.DataFrame([{
|
|
1090
|
+
"Gage R&R %Contribution": grr / total * 100 if total else np.nan,
|
|
1091
|
+
"Gage R&R %Study Var": math.sqrt(grr / total) * 100 if total else np.nan,
|
|
1092
|
+
"%Tolerance": (6 * math.sqrt(grr) / tolerance * 100) if tolerance and tolerance > 0 else np.nan,
|
|
1093
|
+
"ndc": ndc,
|
|
1094
|
+
}])
|
|
1095
|
+
result = AnalysisResult(title=f"Gage R&R (Expanded): {measurement}", analysis_type="gage_rr", params={"measurement": measurement, "part": part, "operator": operator, "batch": batch, "design": "expanded", "tolerance": tolerance})
|
|
1096
|
+
result.add_table("ANOVA", pd.DataFrame(anova_rows))
|
|
1097
|
+
result.add_table("Variance Components", pd.DataFrame(rows))
|
|
1098
|
+
result.add_table("Gage R&R Summary", summary)
|
|
1099
|
+
result.add_plot("box", {"column": measurement, "group": part}, title=f"{measurement} by Part", data=frame)
|
|
1100
|
+
result.summary = f"Expanded %GRR (study var) = {summary['Gage R&R %Study Var'].iloc[0]:.2f}%, ndc = {ndc}."
|
|
1101
|
+
return result
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def process_screening(
|
|
1105
|
+
df: pd.DataFrame,
|
|
1106
|
+
columns: list[str] | None = None,
|
|
1107
|
+
lsl: float | None = None,
|
|
1108
|
+
usl: float | None = None,
|
|
1109
|
+
subgroup: str | None = None,
|
|
1110
|
+
) -> AnalysisResult:
|
|
1111
|
+
columns = [column for column in (columns or df.columns) if column in df.columns]
|
|
1112
|
+
rows = []
|
|
1113
|
+
for column in columns:
|
|
1114
|
+
values = pd.to_numeric(df[column], errors="coerce").dropna()
|
|
1115
|
+
if len(values) < 5:
|
|
1116
|
+
continue
|
|
1117
|
+
mean = float(values.mean())
|
|
1118
|
+
std = float(values.std(ddof=1))
|
|
1119
|
+
moving = values.diff().abs().dropna()
|
|
1120
|
+
within = float(moving.mean() / _D2[2]) if len(moving) else std
|
|
1121
|
+
if subgroup and subgroup in df.columns:
|
|
1122
|
+
grouped = df.loc[:, [column, subgroup]].copy()
|
|
1123
|
+
grouped[column] = pd.to_numeric(grouped[column], errors="coerce")
|
|
1124
|
+
grouped = grouped.dropna()
|
|
1125
|
+
groups = grouped.groupby(subgroup, sort=False)[column]
|
|
1126
|
+
sizes = groups.count()
|
|
1127
|
+
variances = groups.var(ddof=1)
|
|
1128
|
+
weights = (sizes - 1).clip(lower=0)
|
|
1129
|
+
if weights.sum():
|
|
1130
|
+
within = float(math.sqrt(max(float((variances * weights).sum() / weights.sum()), 0.0)))
|
|
1131
|
+
cpk = np.nan
|
|
1132
|
+
if lsl is not None and usl is not None and within:
|
|
1133
|
+
cpk = min((usl - mean) / (3 * within), (mean - lsl) / (3 * within))
|
|
1134
|
+
elif usl is not None and within:
|
|
1135
|
+
cpk = (usl - mean) / (3 * within)
|
|
1136
|
+
elif lsl is not None and within:
|
|
1137
|
+
cpk = (mean - lsl) / (3 * within)
|
|
1138
|
+
rows.append({
|
|
1139
|
+
"Column": column,
|
|
1140
|
+
"N": len(values),
|
|
1141
|
+
"Mean": mean,
|
|
1142
|
+
"Std Dev": std,
|
|
1143
|
+
"Within Sigma": within,
|
|
1144
|
+
"Cpk": cpk,
|
|
1145
|
+
"Stable": bool(not any(status != "ok" for status in _run_rules(values.to_numpy(dtype=float), mean, mean + 3 * within, mean - 3 * within))),
|
|
1146
|
+
})
|
|
1147
|
+
if not rows:
|
|
1148
|
+
raise ValueError("No numeric columns with at least five observations.")
|
|
1149
|
+
table = pd.DataFrame(rows).sort_values("Cpk", ascending=False, na_position="last").reset_index(drop=True)
|
|
1150
|
+
result = AnalysisResult(
|
|
1151
|
+
title="Process Screening",
|
|
1152
|
+
analysis_type="process_screening",
|
|
1153
|
+
params={"columns": columns, "lsl": lsl, "usl": usl, "subgroup": subgroup},
|
|
1154
|
+
)
|
|
1155
|
+
result.add_table("Process Screening", table)
|
|
1156
|
+
result.add_plot("bar", {"x": "Column", "y": "Cpk"}, title="Capability by Process", data=table)
|
|
1157
|
+
result.summary = f"Screened {len(table)} processes; {int((table['Cpk'] >= 1.33).sum())} meet Cpk >= 1.33."
|
|
1158
|
+
return result
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
def attribute_agreement(
|
|
1162
|
+
df: pd.DataFrame,
|
|
1163
|
+
part: str,
|
|
1164
|
+
appraiser: str,
|
|
1165
|
+
rating: str,
|
|
1166
|
+
) -> AnalysisResult:
|
|
1167
|
+
for column in (part, appraiser, rating):
|
|
1168
|
+
if column not in df.columns:
|
|
1169
|
+
raise KeyError(column)
|
|
1170
|
+
frame = df.loc[:, [part, appraiser, rating]].dropna()
|
|
1171
|
+
if frame[appraiser].nunique() < 2 or frame[part].nunique() < 2:
|
|
1172
|
+
raise ValueError("Attribute agreement requires at least two parts and two appraisers.")
|
|
1173
|
+
pivot = frame.pivot_table(index=part, columns=appraiser, values=rating, aggfunc="first")
|
|
1174
|
+
complete = pivot.dropna()
|
|
1175
|
+
if complete.empty:
|
|
1176
|
+
raise ValueError("No parts were rated by every appraiser.")
|
|
1177
|
+
ratings = complete.to_numpy()
|
|
1178
|
+
n_parts, n_appraisers = ratings.shape
|
|
1179
|
+
labels = list(pd.unique(ratings.ravel()))
|
|
1180
|
+
observed = 0.0
|
|
1181
|
+
for row in ratings:
|
|
1182
|
+
counts = np.array([np.sum(row == label) for label in labels], dtype=float)
|
|
1183
|
+
observed += float((np.sum(counts**2) - n_appraisers) / (n_appraisers * (n_appraisers - 1))) if n_appraisers > 1 else 1.0
|
|
1184
|
+
observed = observed / n_parts
|
|
1185
|
+
expected = float(sum((np.sum(ratings == label) / (n_parts * n_appraisers)) ** 2 for label in labels))
|
|
1186
|
+
kappa = (observed - expected) / (1 - expected) if expected < 1 else np.nan
|
|
1187
|
+
pair_rows = []
|
|
1188
|
+
for first, second in itertools.combinations(range(n_appraisers), 2):
|
|
1189
|
+
first_values = ratings[:, first]
|
|
1190
|
+
second_values = ratings[:, second]
|
|
1191
|
+
pair_observed = float(np.mean(first_values == second_values))
|
|
1192
|
+
pair_expected = float(sum(
|
|
1193
|
+
np.mean(first_values == label) * np.mean(second_values == label)
|
|
1194
|
+
for label in labels
|
|
1195
|
+
))
|
|
1196
|
+
pair_kappa = (pair_observed - pair_expected) / (1 - pair_expected) if pair_expected < 1 else np.nan
|
|
1197
|
+
pair_rows.append({
|
|
1198
|
+
"Appraiser 1": complete.columns[first],
|
|
1199
|
+
"Appraiser 2": complete.columns[second],
|
|
1200
|
+
"Agreement": pair_observed,
|
|
1201
|
+
"Kappa": pair_kappa,
|
|
1202
|
+
})
|
|
1203
|
+
result = AnalysisResult(
|
|
1204
|
+
title="Attribute Agreement Analysis",
|
|
1205
|
+
analysis_type="attribute_agreement",
|
|
1206
|
+
params={"part": part, "appraiser": appraiser, "rating": rating},
|
|
1207
|
+
)
|
|
1208
|
+
result.add_table("Agreement Summary", pd.DataFrame([{
|
|
1209
|
+
"Parts": n_parts,
|
|
1210
|
+
"Appraisers": n_appraisers,
|
|
1211
|
+
"Overall Agreement": observed,
|
|
1212
|
+
"Expected Agreement": expected,
|
|
1213
|
+
"Fleiss Kappa (approx.)": kappa,
|
|
1214
|
+
}]))
|
|
1215
|
+
result.add_table("Pairwise Agreement", pd.DataFrame(pair_rows))
|
|
1216
|
+
result.add_table("Rating Matrix", complete.reset_index())
|
|
1217
|
+
result.summary = f"Overall agreement {observed:.1%}; kappa {kappa:.3f} across {n_parts} parts and {n_appraisers} appraisers."
|
|
1218
|
+
return result
|