py6sigma 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.
- py6sigma/__init__.py +29 -0
- py6sigma/analysis.py +616 -0
- py6sigma/cli.py +49 -0
- py6sigma/method_selection.py +201 -0
- py6sigma/pareto.py +126 -0
- py6sigma/scatter.py +58 -0
- py6sigma-0.1.0.dist-info/METADATA +364 -0
- py6sigma-0.1.0.dist-info/RECORD +12 -0
- py6sigma-0.1.0.dist-info/WHEEL +5 -0
- py6sigma-0.1.0.dist-info/entry_points.txt +2 -0
- py6sigma-0.1.0.dist-info/licenses/LICENSE +21 -0
- py6sigma-0.1.0.dist-info/top_level.txt +1 -0
py6sigma/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Statistical tools for Lean Six Sigma."""
|
|
2
|
+
|
|
3
|
+
from matplotlib.pyplot import show
|
|
4
|
+
|
|
5
|
+
from .analysis import Analysis, AndersonResult, CapabilityPerformance, CapabilityResult, DescriptiveResult, OneSampleTResult, RunChartResult, RunsResult, SigmaResult, TestResult, sigma_level
|
|
6
|
+
from .pareto import pareto_chart
|
|
7
|
+
from .method_selection import MethodCandidate, MethodSelection, select_statistical_method, xy_table_choice
|
|
8
|
+
from .scatter import scatter_plot
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Analysis",
|
|
12
|
+
"AndersonResult",
|
|
13
|
+
"CapabilityPerformance",
|
|
14
|
+
"CapabilityResult",
|
|
15
|
+
"DescriptiveResult",
|
|
16
|
+
"OneSampleTResult",
|
|
17
|
+
"MethodCandidate",
|
|
18
|
+
"MethodSelection",
|
|
19
|
+
"RunChartResult",
|
|
20
|
+
"RunsResult",
|
|
21
|
+
"SigmaResult",
|
|
22
|
+
"TestResult",
|
|
23
|
+
"pareto_chart",
|
|
24
|
+
"scatter_plot",
|
|
25
|
+
"select_statistical_method",
|
|
26
|
+
"xy_table_choice",
|
|
27
|
+
"sigma_level",
|
|
28
|
+
"show",
|
|
29
|
+
]
|
py6sigma/analysis.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""Descriptive statistics, normality tests, capability and plots."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from math import isfinite
|
|
5
|
+
from numbers import Integral, Real
|
|
6
|
+
from os import PathLike
|
|
7
|
+
from typing import Iterable, Literal
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from matplotlib.axes import Axes
|
|
13
|
+
from matplotlib.figure import Figure
|
|
14
|
+
from scipy import stats
|
|
15
|
+
from statsmodels.sandbox.stats.runs import runstest_1samp
|
|
16
|
+
from statsmodels.stats.diagnostic import normal_ad
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class DescriptiveResult:
|
|
21
|
+
n: int
|
|
22
|
+
mean: float
|
|
23
|
+
median: float
|
|
24
|
+
std_dev: float
|
|
25
|
+
minimum: float
|
|
26
|
+
maximum: float
|
|
27
|
+
q1: float
|
|
28
|
+
q3: float
|
|
29
|
+
p10: float
|
|
30
|
+
p50: float
|
|
31
|
+
p90: float
|
|
32
|
+
skewness: float
|
|
33
|
+
kurtosis: float
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class TestResult:
|
|
38
|
+
statistic: float
|
|
39
|
+
p_value: float
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class OneSampleTResult:
|
|
44
|
+
n: int
|
|
45
|
+
mean: float
|
|
46
|
+
std_dev: float
|
|
47
|
+
standard_error: float
|
|
48
|
+
hypothesized_mean: float
|
|
49
|
+
alternative: Literal["two-sided", "less", "greater"]
|
|
50
|
+
confidence_level: float
|
|
51
|
+
confidence_interval: tuple[float, float]
|
|
52
|
+
statistic: float
|
|
53
|
+
degrees_of_freedom: int
|
|
54
|
+
p_value: float
|
|
55
|
+
name: str
|
|
56
|
+
|
|
57
|
+
def __str__(self) -> str:
|
|
58
|
+
operators = {"two-sided": "not =", "less": "<", "greater": ">"}
|
|
59
|
+
level = f"{self.confidence_level * 100:g}%"
|
|
60
|
+
if self.alternative == "two-sided":
|
|
61
|
+
interval_header = f"{level} CI"
|
|
62
|
+
interval_top = ""
|
|
63
|
+
interval_value = f"({self.confidence_interval[0]:.2f}, {self.confidence_interval[1]:.2f})"
|
|
64
|
+
else:
|
|
65
|
+
interval_top = f"{level} {'Lower' if self.alternative == 'greater' else 'Upper'}"
|
|
66
|
+
interval_header = "Bound"
|
|
67
|
+
bound = self.confidence_interval[0 if self.alternative == "greater" else 1]
|
|
68
|
+
interval_value = f"{bound:.2f}"
|
|
69
|
+
headers = ["Variable", "N", "Mean", "StDev", "SE Mean", interval_header, "T", "P"]
|
|
70
|
+
values = [
|
|
71
|
+
self.name, str(self.n), f"{self.mean:.2f}", f"{self.std_dev:.2f}",
|
|
72
|
+
f"{self.standard_error:.2f}", interval_value, f"{self.statistic:.2f}", f"{self.p_value:.3f}",
|
|
73
|
+
]
|
|
74
|
+
widths = [max(len(header), len(value)) for header, value in zip(headers, values)]
|
|
75
|
+
widths[5] = max(widths[5], len(interval_top))
|
|
76
|
+
|
|
77
|
+
def row(items: list[str]) -> str:
|
|
78
|
+
return " ".join(
|
|
79
|
+
item.ljust(width) if index == 0 else item.rjust(width)
|
|
80
|
+
for index, (item, width) in enumerate(zip(items, widths))
|
|
81
|
+
).rstrip()
|
|
82
|
+
|
|
83
|
+
lines = [
|
|
84
|
+
f"One-Sample T: {self.name}",
|
|
85
|
+
"",
|
|
86
|
+
f"Test of mu = {self.hypothesized_mean:g} vs {operators[self.alternative]} {self.hypothesized_mean:g}",
|
|
87
|
+
"",
|
|
88
|
+
]
|
|
89
|
+
if interval_top:
|
|
90
|
+
lines.append(row(["", "", "", "", "", interval_top, "", ""]))
|
|
91
|
+
lines.extend((row(headers), row(values)))
|
|
92
|
+
relation = {
|
|
93
|
+
"two-sided": "différente de",
|
|
94
|
+
"less": "inférieure à",
|
|
95
|
+
"greater": "supérieure à",
|
|
96
|
+
}[self.alternative]
|
|
97
|
+
decision = "permettent" if self.p_value < 1 - self.confidence_level else "ne permettent pas"
|
|
98
|
+
lines.extend((
|
|
99
|
+
"",
|
|
100
|
+
f"Conclusion (seuil de {(1 - self.confidence_level) * 100:g} %) : "
|
|
101
|
+
f"les données {decision} de conclure que la moyenne de {self.name} "
|
|
102
|
+
f"est {relation} {self.hypothesized_mean}.",
|
|
103
|
+
))
|
|
104
|
+
return "\n".join(lines)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class RunsResult:
|
|
109
|
+
runs: int
|
|
110
|
+
n_above: int
|
|
111
|
+
n_below: int
|
|
112
|
+
statistic: float
|
|
113
|
+
p_value: float
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class RunChartResult:
|
|
118
|
+
median: float
|
|
119
|
+
runs_about_median: int
|
|
120
|
+
expected_runs_about_median: float
|
|
121
|
+
longest_run_about_median: int
|
|
122
|
+
p_clustering: float | None
|
|
123
|
+
p_mixtures: float | None
|
|
124
|
+
runs_up_down: int
|
|
125
|
+
expected_runs_up_down: float | None
|
|
126
|
+
longest_run_up_down: int
|
|
127
|
+
p_trends: float | None
|
|
128
|
+
p_oscillation: float | None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class AndersonResult:
|
|
133
|
+
statistic: float
|
|
134
|
+
critical_values: tuple[float, ...]
|
|
135
|
+
significance_levels: tuple[float, ...]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass(frozen=True)
|
|
139
|
+
class CapabilityPerformance:
|
|
140
|
+
ppm_below_lsl: float | None
|
|
141
|
+
ppm_above_usl: float | None
|
|
142
|
+
ppm_total: float
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class CapabilityResult:
|
|
147
|
+
lsl: float | None
|
|
148
|
+
usl: float | None
|
|
149
|
+
n: int
|
|
150
|
+
mean: float
|
|
151
|
+
std_within: float
|
|
152
|
+
std_overall: float
|
|
153
|
+
cp: float | None
|
|
154
|
+
cpl: float | None
|
|
155
|
+
cpu: float | None
|
|
156
|
+
cpk: float
|
|
157
|
+
pp: float | None
|
|
158
|
+
ppl: float | None
|
|
159
|
+
ppu: float | None
|
|
160
|
+
ppk: float
|
|
161
|
+
observed: CapabilityPerformance
|
|
162
|
+
expected_within: CapabilityPerformance
|
|
163
|
+
expected_overall: CapabilityPerformance
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True)
|
|
167
|
+
class SigmaResult:
|
|
168
|
+
dpo: float
|
|
169
|
+
dpmo: float
|
|
170
|
+
z_lt: float
|
|
171
|
+
z_st: float
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def sigma_level(
|
|
175
|
+
dpo: float | None = None,
|
|
176
|
+
*,
|
|
177
|
+
defects: int | None = None,
|
|
178
|
+
opportunities_per_unit: int | None = None,
|
|
179
|
+
units: int | None = None,
|
|
180
|
+
) -> SigmaResult:
|
|
181
|
+
"""Convert a defect probability to long- and short-term sigma levels."""
|
|
182
|
+
counts = (defects, opportunities_per_unit, units)
|
|
183
|
+
if dpo is not None:
|
|
184
|
+
if any(value is not None for value in counts):
|
|
185
|
+
raise ValueError("provide either dpo or defects, opportunities_per_unit and units")
|
|
186
|
+
if isinstance(dpo, bool) or not isinstance(dpo, Real) or not isfinite(dpo) or not 0 <= dpo <= 1:
|
|
187
|
+
raise ValueError("dpo must be a finite number between 0 and 1")
|
|
188
|
+
probability = float(dpo)
|
|
189
|
+
else:
|
|
190
|
+
if any(value is None for value in counts):
|
|
191
|
+
raise ValueError("provide either dpo or defects, opportunities_per_unit and units")
|
|
192
|
+
if any(isinstance(value, bool) or not isinstance(value, Integral) for value in counts):
|
|
193
|
+
raise ValueError("defects, opportunities_per_unit and units must be integers")
|
|
194
|
+
if defects is None or opportunities_per_unit is None or units is None:
|
|
195
|
+
raise ValueError("defects, opportunities_per_unit and units are required")
|
|
196
|
+
if defects < 0 or opportunities_per_unit <= 0 or units <= 0:
|
|
197
|
+
raise ValueError("defects must be non-negative and opportunities_per_unit and units must be positive")
|
|
198
|
+
total = opportunities_per_unit * units
|
|
199
|
+
if defects > total:
|
|
200
|
+
raise ValueError("defects cannot exceed the total number of opportunities")
|
|
201
|
+
probability = defects / total
|
|
202
|
+
z_lt = float(stats.norm.isf(probability))
|
|
203
|
+
return SigmaResult(probability, probability * 1_000_000, z_lt, z_lt + 1.5)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _group_indices(groups: Iterable[str | Real], size: int) -> dict[str | Real, list[int]]:
|
|
207
|
+
group_values = list(groups)
|
|
208
|
+
if len(group_values) != size:
|
|
209
|
+
raise ValueError("groups must have the same length as the data")
|
|
210
|
+
grouped: dict[str | Real, list[int]] = {}
|
|
211
|
+
for index, group in enumerate(group_values):
|
|
212
|
+
if not (
|
|
213
|
+
isinstance(group, str) and group.strip()
|
|
214
|
+
or isinstance(group, Real) and not isinstance(group, bool) and isfinite(group)
|
|
215
|
+
):
|
|
216
|
+
raise ValueError("groups must contain non-empty strings or finite numbers")
|
|
217
|
+
grouped.setdefault(group, []).append(index)
|
|
218
|
+
return grouped
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class Analysis:
|
|
222
|
+
"""Analyze a one-dimensional sequence of finite observations."""
|
|
223
|
+
|
|
224
|
+
def __init__(self, data: Iterable[float]):
|
|
225
|
+
values = np.asarray(list(data), dtype=float)
|
|
226
|
+
if values.ndim != 1 or values.size == 0:
|
|
227
|
+
raise ValueError("data must be a non-empty one-dimensional sequence")
|
|
228
|
+
if not np.isfinite(values).all():
|
|
229
|
+
raise ValueError("data must contain only finite numbers")
|
|
230
|
+
self._data = values.copy()
|
|
231
|
+
self._name = "Data"
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def from_excel(
|
|
235
|
+
cls, path: str | PathLike[str], column: str, *, sheet_name: str | int = 0
|
|
236
|
+
) -> "Analysis":
|
|
237
|
+
"""Load a numeric column from an Excel worksheet in its original order."""
|
|
238
|
+
frame = pd.read_excel(path, sheet_name=sheet_name, keep_default_na=False, na_values=[""])
|
|
239
|
+
if column not in frame.columns:
|
|
240
|
+
raise ValueError(f"column {column!r} not found in Excel worksheet")
|
|
241
|
+
values = pd.to_numeric(frame[column].dropna(), errors="raise")
|
|
242
|
+
analysis = cls(values)
|
|
243
|
+
analysis._name = column
|
|
244
|
+
return analysis
|
|
245
|
+
|
|
246
|
+
def _require(self, minimum: int, nonconstant: bool = False) -> None:
|
|
247
|
+
if self._data.size < minimum:
|
|
248
|
+
raise ValueError(f"at least {minimum} observations are required")
|
|
249
|
+
if nonconstant and np.ptp(self._data) == 0:
|
|
250
|
+
raise ValueError("data must not be constant")
|
|
251
|
+
|
|
252
|
+
def descriptive_statistics(self) -> DescriptiveResult:
|
|
253
|
+
self._require(2)
|
|
254
|
+
d = self._data
|
|
255
|
+
constant = np.ptp(d) == 0
|
|
256
|
+
return DescriptiveResult(
|
|
257
|
+
n=int(d.size),
|
|
258
|
+
mean=float(np.mean(d)),
|
|
259
|
+
median=float(np.median(d)),
|
|
260
|
+
std_dev=float(np.std(d, ddof=1)),
|
|
261
|
+
minimum=float(np.min(d)),
|
|
262
|
+
maximum=float(np.max(d)),
|
|
263
|
+
q1=float(np.percentile(d, 25)),
|
|
264
|
+
q3=float(np.percentile(d, 75)),
|
|
265
|
+
p10=float(np.percentile(d, 10)),
|
|
266
|
+
p50=float(np.percentile(d, 50)),
|
|
267
|
+
p90=float(np.percentile(d, 90)),
|
|
268
|
+
skewness=float("nan") if constant else float(stats.skew(d)),
|
|
269
|
+
kurtosis=float("nan") if constant else float(stats.kurtosis(d)),
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
def run_test(self) -> RunsResult:
|
|
273
|
+
median = np.median(self._data)
|
|
274
|
+
values = self._data[self._data != median]
|
|
275
|
+
above = values > median
|
|
276
|
+
n_above = int(np.sum(above))
|
|
277
|
+
n_below = int(values.size - n_above)
|
|
278
|
+
if n_above == 0 or n_below == 0 or values.size < 3:
|
|
279
|
+
raise ValueError("run test requires at least three non-median observations on both sides")
|
|
280
|
+
runs = int(1 + np.count_nonzero(above[1:] != above[:-1]))
|
|
281
|
+
z, p_value = runstest_1samp(values, cutoff=median)
|
|
282
|
+
return RunsResult(runs, n_above, n_below, float(z), float(p_value))
|
|
283
|
+
|
|
284
|
+
def run_chart_statistics(self) -> RunChartResult:
|
|
285
|
+
"""Return run-chart statistics for individual observations."""
|
|
286
|
+
values = self._data
|
|
287
|
+
n = len(values)
|
|
288
|
+
median = float(np.median(values))
|
|
289
|
+
above = values > median
|
|
290
|
+
lengths = np.diff(np.r_[0, np.flatnonzero(above[1:] != above[:-1]) + 1, n])
|
|
291
|
+
runs = len(lengths)
|
|
292
|
+
m = int(above.sum())
|
|
293
|
+
below = n - m
|
|
294
|
+
expected = 1 + 2 * m * below / n
|
|
295
|
+
variance = 2 * m * below * (2 * m * below - n) / (n**2 * (n - 1)) if n > 1 else 0
|
|
296
|
+
p_clustering = p_mixtures = None
|
|
297
|
+
if variance > 0:
|
|
298
|
+
z = (runs - expected) / np.sqrt(variance)
|
|
299
|
+
p_clustering = float(stats.norm.cdf(z))
|
|
300
|
+
p_mixtures = float(stats.norm.sf(z))
|
|
301
|
+
|
|
302
|
+
directions = np.diff(values) > 0
|
|
303
|
+
direction_lengths = np.diff(
|
|
304
|
+
np.r_[0, np.flatnonzero(directions[1:] != directions[:-1]) + 1, len(directions)]
|
|
305
|
+
) if directions.size else np.array([], dtype=int)
|
|
306
|
+
runs_up_down = len(direction_lengths)
|
|
307
|
+
if runs_up_down:
|
|
308
|
+
direction_lengths[0] += 1
|
|
309
|
+
longest_up_down = int(direction_lengths.max()) if runs_up_down else 0
|
|
310
|
+
expected_up_down = (2 * n - 1) / 3 if n >= 3 else None
|
|
311
|
+
p_trends = p_oscillation = None
|
|
312
|
+
if expected_up_down is not None:
|
|
313
|
+
z = (runs_up_down - expected_up_down) / np.sqrt((16 * n - 29) / 90)
|
|
314
|
+
p_trends = float(stats.norm.cdf(z))
|
|
315
|
+
p_oscillation = float(stats.norm.sf(z))
|
|
316
|
+
return RunChartResult(
|
|
317
|
+
median, runs, float(expected), int(lengths.max()), p_clustering, p_mixtures,
|
|
318
|
+
runs_up_down, expected_up_down, longest_up_down, p_trends, p_oscillation,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
def one_sample_t_test(
|
|
322
|
+
self,
|
|
323
|
+
hypothesized_mean: float,
|
|
324
|
+
*,
|
|
325
|
+
alternative: Literal["two-sided", "less", "greater"] = "two-sided",
|
|
326
|
+
confidence_level: float = 0.95,
|
|
327
|
+
name: str | None = None,
|
|
328
|
+
) -> OneSampleTResult:
|
|
329
|
+
"""Test the population mean and calculate its confidence interval."""
|
|
330
|
+
self._require(2, nonconstant=True)
|
|
331
|
+
if (isinstance(hypothesized_mean, bool) or not isinstance(hypothesized_mean, Real)
|
|
332
|
+
or not isfinite(hypothesized_mean)):
|
|
333
|
+
raise ValueError("hypothesized_mean must be a finite number")
|
|
334
|
+
if alternative not in ("two-sided", "less", "greater"):
|
|
335
|
+
raise ValueError("alternative must be 'two-sided', 'less', or 'greater'")
|
|
336
|
+
if (isinstance(confidence_level, bool) or not isinstance(confidence_level, Real)
|
|
337
|
+
or not isfinite(confidence_level) or not 0 < confidence_level < 1):
|
|
338
|
+
raise ValueError("confidence_level must be a finite number between 0 and 1, exclusive")
|
|
339
|
+
if name is not None and (not isinstance(name, str) or not name.strip() or "\n" in name or "\r" in name):
|
|
340
|
+
raise ValueError("name must be a non-empty single-line string")
|
|
341
|
+
n = int(self._data.size)
|
|
342
|
+
mean = float(np.mean(self._data))
|
|
343
|
+
std_dev = float(np.std(self._data, ddof=1))
|
|
344
|
+
standard_error = std_dev / np.sqrt(n)
|
|
345
|
+
if not isfinite(standard_error) or standard_error <= 0 or not isfinite(mean):
|
|
346
|
+
raise ValueError("sample mean and standard error must be finite, and standard error must be positive")
|
|
347
|
+
result = stats.ttest_1samp(self._data, hypothesized_mean, alternative=alternative)
|
|
348
|
+
interval = result.confidence_interval(confidence_level=confidence_level)
|
|
349
|
+
return OneSampleTResult(
|
|
350
|
+
n, mean, std_dev, float(standard_error), float(hypothesized_mean),
|
|
351
|
+
alternative, float(confidence_level), (float(interval.low), float(interval.high)),
|
|
352
|
+
float(result.statistic), n - 1, float(result.pvalue), self._name if name is None else name,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
def shapiro_test(self) -> TestResult:
|
|
356
|
+
self._require(3, nonconstant=True)
|
|
357
|
+
result = stats.shapiro(self._data)
|
|
358
|
+
return TestResult(float(result.statistic), float(result.pvalue))
|
|
359
|
+
|
|
360
|
+
def anderson_test(self) -> AndersonResult:
|
|
361
|
+
self._require(5, nonconstant=True)
|
|
362
|
+
result = stats.anderson(self._data, dist="norm")
|
|
363
|
+
return AndersonResult(
|
|
364
|
+
float(result.statistic),
|
|
365
|
+
tuple(float(value) for value in result.critical_values),
|
|
366
|
+
tuple(float(value) for value in result.significance_level),
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
def capability(self, lsl: float | None = None, usl: float | None = None) -> CapabilityResult:
|
|
370
|
+
"""Calculate normal capability indices for individual observations."""
|
|
371
|
+
self._require(2, nonconstant=True)
|
|
372
|
+
if lsl is None and usl is None:
|
|
373
|
+
raise ValueError("at least one specification limit is required")
|
|
374
|
+
if any(limit is not None and not np.isfinite(limit) for limit in (lsl, usl)):
|
|
375
|
+
raise ValueError("specification limits must be finite")
|
|
376
|
+
if lsl is not None and usl is not None and lsl >= usl:
|
|
377
|
+
raise ValueError("lsl must be less than usl")
|
|
378
|
+
|
|
379
|
+
mean = float(np.mean(self._data))
|
|
380
|
+
std_overall = float(np.std(self._data, ddof=1))
|
|
381
|
+
std_within = float(np.mean(np.abs(np.diff(self._data))) / 1.128)
|
|
382
|
+
|
|
383
|
+
def indices(sigma: float) -> tuple[float | None, float | None, float | None, float]:
|
|
384
|
+
lower = float((mean - lsl) / (3 * sigma)) if lsl is not None else None
|
|
385
|
+
upper = float((usl - mean) / (3 * sigma)) if usl is not None else None
|
|
386
|
+
spread = float((usl - lsl) / (6 * sigma)) if lsl is not None and usl is not None else None
|
|
387
|
+
available = [value for value in (lower, upper) if value is not None]
|
|
388
|
+
return spread, lower, upper, min(available)
|
|
389
|
+
|
|
390
|
+
def performance(below: float | None, above: float | None) -> CapabilityPerformance:
|
|
391
|
+
return CapabilityPerformance(below, above, (below or 0.0) + (above or 0.0))
|
|
392
|
+
|
|
393
|
+
def expected(sigma: float) -> CapabilityPerformance:
|
|
394
|
+
below = float(stats.norm.cdf(lsl, loc=mean, scale=sigma) * 1_000_000) if lsl is not None else None
|
|
395
|
+
above = float(stats.norm.sf(usl, loc=mean, scale=sigma) * 1_000_000) if usl is not None else None
|
|
396
|
+
return performance(below, above)
|
|
397
|
+
|
|
398
|
+
cp, cpl, cpu, cpk = indices(std_within)
|
|
399
|
+
pp, ppl, ppu, ppk = indices(std_overall)
|
|
400
|
+
below = float(np.mean(self._data < lsl) * 1_000_000) if lsl is not None else None
|
|
401
|
+
above = float(np.mean(self._data > usl) * 1_000_000) if usl is not None else None
|
|
402
|
+
return CapabilityResult(
|
|
403
|
+
float(lsl) if lsl is not None else None,
|
|
404
|
+
float(usl) if usl is not None else None,
|
|
405
|
+
int(self._data.size), mean, std_within, std_overall,
|
|
406
|
+
cp, cpl, cpu, cpk, pp, ppl, ppu, ppk,
|
|
407
|
+
performance(below, above), expected(std_within), expected(std_overall),
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
def capability_analysis_normal(
|
|
411
|
+
self, lsl: float | None = None, usl: float | None = None, *,
|
|
412
|
+
name: str | None = None, bins: int | Literal["auto"] = "auto",
|
|
413
|
+
) -> Figure:
|
|
414
|
+
"""Plot normal capability analysis for individual observations."""
|
|
415
|
+
if bins != "auto" and (isinstance(bins, bool) or not isinstance(bins, Integral) or bins < 1):
|
|
416
|
+
raise ValueError("bins must be 'auto' or a positive integer")
|
|
417
|
+
result = self.capability(lsl=lsl, usl=usl)
|
|
418
|
+
figure = plt.figure(figsize=(12, 8), layout="constrained")
|
|
419
|
+
grid = figure.add_gridspec(2, 3, width_ratios=(1.35, 2.8, 1.35), height_ratios=(3, 0.9))
|
|
420
|
+
process = figure.add_subplot(grid[0, 0])
|
|
421
|
+
ax = figure.add_subplot(grid[0, 1])
|
|
422
|
+
capability = figure.add_subplot(grid[0, 2])
|
|
423
|
+
performance_grid = grid[1, :].subgridspec(1, 3)
|
|
424
|
+
performance_axes = [figure.add_subplot(performance_grid[0, i]) for i in range(3)]
|
|
425
|
+
title = f"Process Capability of {name}" if name else "Process Capability"
|
|
426
|
+
figure.suptitle(title, fontsize=16)
|
|
427
|
+
ax.hist(self._data, bins=bins, density=True, color="#b8bec7", edgecolor="#555555")
|
|
428
|
+
limits = [limit for limit in (result.lsl, result.usl) if limit is not None]
|
|
429
|
+
lo = min(float(np.min(self._data)), result.mean - 4 * result.std_overall,
|
|
430
|
+
result.mean - 4 * result.std_within, *limits)
|
|
431
|
+
hi = max(float(np.max(self._data)), result.mean + 4 * result.std_overall,
|
|
432
|
+
result.mean + 4 * result.std_within, *limits)
|
|
433
|
+
x = np.linspace(lo, hi, 500)
|
|
434
|
+
ax.plot(x, stats.norm.pdf(x, result.mean, result.std_within), color="#b24542", label="Within")
|
|
435
|
+
ax.plot(x, stats.norm.pdf(x, result.mean, result.std_overall), color="#333333",
|
|
436
|
+
linestyle="--", label="Overall")
|
|
437
|
+
for label, limit in (("LSL", result.lsl), ("USL", result.usl)):
|
|
438
|
+
if limit is not None:
|
|
439
|
+
ax.axvline(limit, color="#b24542", linestyle="--", linewidth=1.2)
|
|
440
|
+
ax.text(limit, 1.01, label, transform=ax.get_xaxis_transform(),
|
|
441
|
+
ha="center", va="bottom", color="#b24542", fontsize="small")
|
|
442
|
+
ax.set(xlabel=name or "Value", ylabel="Density")
|
|
443
|
+
ax.legend(fontsize="small", loc="upper right")
|
|
444
|
+
|
|
445
|
+
def display(value: float | None, digits: int = 3) -> str:
|
|
446
|
+
return "N/A" if value is None else f"{value:.{digits}f}"
|
|
447
|
+
|
|
448
|
+
box = {"boxstyle": "square,pad=0.55", "facecolor": "white", "edgecolor": "#777777"}
|
|
449
|
+
process.axis("off")
|
|
450
|
+
process.text(
|
|
451
|
+
0, 1,
|
|
452
|
+
f"Process Data\n\nLSL {display(result.lsl)}\nUSL {display(result.usl)}\n"
|
|
453
|
+
f"Sample N {result.n}\nMean {result.mean:.4f}\n"
|
|
454
|
+
f"StDev (Within) {result.std_within:.4f}\nStDev (Overall) {result.std_overall:.4f}",
|
|
455
|
+
va="top", fontsize=9, fontfamily="monospace", bbox=box,
|
|
456
|
+
)
|
|
457
|
+
capability.axis("off")
|
|
458
|
+
capability.text(
|
|
459
|
+
0, 1,
|
|
460
|
+
f"Potential (Within)\n\nCp {display(result.cp)}\nCPL {display(result.cpl)}\n"
|
|
461
|
+
f"CPU {display(result.cpu)}\nCpk {result.cpk:.3f}\n\n"
|
|
462
|
+
f"Overall Capability\n\nPp {display(result.pp)}\nPPL {display(result.ppl)}\n"
|
|
463
|
+
f"PPU {display(result.ppu)}\nPpk {result.ppk:.3f}",
|
|
464
|
+
va="top", fontsize=9, fontfamily="monospace", bbox=box,
|
|
465
|
+
)
|
|
466
|
+
for panel, label, item in zip(
|
|
467
|
+
performance_axes,
|
|
468
|
+
("Observed Performance", "Expected Within", "Expected Overall"),
|
|
469
|
+
(result.observed, result.expected_within, result.expected_overall),
|
|
470
|
+
):
|
|
471
|
+
panel.axis("off")
|
|
472
|
+
panel.text(
|
|
473
|
+
0.05, 0.8,
|
|
474
|
+
f"{label}\n\nPPM < LSL {display(item.ppm_below_lsl, 2)}\n"
|
|
475
|
+
f"PPM > USL {display(item.ppm_above_usl, 2)}\nPPM Total {display(item.ppm_total, 2)}",
|
|
476
|
+
va="top", fontsize=9, fontfamily="monospace", bbox=box,
|
|
477
|
+
)
|
|
478
|
+
return figure
|
|
479
|
+
|
|
480
|
+
def histogram(self, ax: Axes | None = None) -> Axes:
|
|
481
|
+
if ax is None:
|
|
482
|
+
_, ax = plt.subplots()
|
|
483
|
+
ax.hist(self._data, bins="auto", edgecolor="black")
|
|
484
|
+
ax.set(title="Histogram", xlabel="Value", ylabel="Frequency")
|
|
485
|
+
return ax
|
|
486
|
+
|
|
487
|
+
def boxplot(
|
|
488
|
+
self, ax: Axes | None = None, *, name: str | None = None,
|
|
489
|
+
groups: Iterable[str | Real] | None = None, group_name: str | None = None,
|
|
490
|
+
reference_lines: Iterable[float] | None = None,
|
|
491
|
+
) -> Axes:
|
|
492
|
+
"""Plot quartiles and 1.5-IQR whiskers, optionally grouped by category."""
|
|
493
|
+
reference_values = [] if reference_lines is None else list(reference_lines)
|
|
494
|
+
if any(isinstance(value, bool) or not isinstance(value, Real) or not isfinite(value)
|
|
495
|
+
for value in reference_values):
|
|
496
|
+
raise ValueError("reference lines must be finite numbers")
|
|
497
|
+
if groups is None:
|
|
498
|
+
samples = [self._data]
|
|
499
|
+
labels = []
|
|
500
|
+
else:
|
|
501
|
+
grouped = _group_indices(groups, self._data.size)
|
|
502
|
+
labels = [str(group) for group in grouped]
|
|
503
|
+
samples = [self._data[indices] for indices in grouped.values()]
|
|
504
|
+
|
|
505
|
+
statistics = []
|
|
506
|
+
for sample in samples:
|
|
507
|
+
q1, median, q3 = np.quantile(sample, [0.25, 0.5, 0.75], method="weibull")
|
|
508
|
+
iqr = q3 - q1
|
|
509
|
+
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
|
|
510
|
+
inside = sample[(sample >= lower) & (sample <= upper)]
|
|
511
|
+
outliers = sample[(sample < lower) | (sample > upper)]
|
|
512
|
+
statistics.append({
|
|
513
|
+
"q1": q1, "med": median, "q3": q3,
|
|
514
|
+
"whislo": np.min(inside), "whishi": np.max(inside),
|
|
515
|
+
"fliers": outliers,
|
|
516
|
+
})
|
|
517
|
+
if ax is None:
|
|
518
|
+
_, ax = plt.subplots(figsize=(8, 6), layout="constrained")
|
|
519
|
+
ax.bxp(
|
|
520
|
+
statistics, showfliers=True, patch_artist=True, widths=0.3,
|
|
521
|
+
boxprops={"facecolor": "#86add8", "edgecolor": "#333333"},
|
|
522
|
+
medianprops={"color": "#333333"},
|
|
523
|
+
whiskerprops={"color": "#333333"},
|
|
524
|
+
capprops={"color": "#333333"},
|
|
525
|
+
flierprops={"marker": "*", "markeredgecolor": "#333333", "markerfacecolor": "#333333"},
|
|
526
|
+
)
|
|
527
|
+
for value in reference_values:
|
|
528
|
+
ax.axhline(value, color="#bd3d37", linestyle="--", linewidth=1.2, zorder=1)
|
|
529
|
+
ax.set_xticks(np.arange(1, len(labels) + 1), labels)
|
|
530
|
+
ax.set(title=f"Boxplot of {name}" if name else "Boxplot",
|
|
531
|
+
ylabel=name or "Value", xlabel=group_name or "")
|
|
532
|
+
ax.grid(axis="y", color="#dddddd", linewidth=0.7)
|
|
533
|
+
ax.set_axisbelow(True)
|
|
534
|
+
return ax
|
|
535
|
+
|
|
536
|
+
def run_chart(self, ax: Axes | None = None) -> Axes:
|
|
537
|
+
if ax is None:
|
|
538
|
+
figure, ax = plt.subplots(figsize=(10, 6))
|
|
539
|
+
figure.subplots_adjust(bottom=0.33)
|
|
540
|
+
result = self.run_chart_statistics()
|
|
541
|
+
ax.plot(
|
|
542
|
+
np.arange(1, self._data.size + 1), self._data,
|
|
543
|
+
marker="o", markersize=4, color="#345b9a", linewidth=1.2,
|
|
544
|
+
)
|
|
545
|
+
ax.axhline(result.median, color="#666666", linestyle="--", label=f"Median = {result.median:.4g}")
|
|
546
|
+
ax.set(title="Run Chart", xlabel="Observation", ylabel="Value")
|
|
547
|
+
ax.grid(True, linestyle="--", linewidth=0.6, alpha=0.35)
|
|
548
|
+
ax.legend()
|
|
549
|
+
|
|
550
|
+
def display(value: float | None) -> str:
|
|
551
|
+
return "N/A" if value is None else f"{value:.4f}"
|
|
552
|
+
|
|
553
|
+
median_summary = (
|
|
554
|
+
f"Runs about median: {result.runs_about_median}\n"
|
|
555
|
+
f"Expected runs: {result.expected_runs_about_median:.4f}\n"
|
|
556
|
+
f"Longest run: {result.longest_run_about_median}\n"
|
|
557
|
+
f"P-value, clustering: {display(result.p_clustering)}\n"
|
|
558
|
+
f"P-value, mixtures: {display(result.p_mixtures)}"
|
|
559
|
+
)
|
|
560
|
+
direction_summary = (
|
|
561
|
+
f"Runs up or down: {result.runs_up_down}\n"
|
|
562
|
+
f"Expected runs: {display(result.expected_runs_up_down)}\n"
|
|
563
|
+
f"Longest run: {result.longest_run_up_down}\n"
|
|
564
|
+
f"P-value, trends: {display(result.p_trends)}\n"
|
|
565
|
+
f"P-value, oscillation: {display(result.p_oscillation)}"
|
|
566
|
+
)
|
|
567
|
+
for x, summary in ((0, median_summary), (0.53, direction_summary)):
|
|
568
|
+
ax.text(x, -0.17, summary, transform=ax.transAxes, va="top", fontsize="small",
|
|
569
|
+
bbox={"boxstyle": "square,pad=0.4", "facecolor": "white", "edgecolor": "#999999"})
|
|
570
|
+
if np.any(np.diff(self._data) == 0):
|
|
571
|
+
ax.text(0, -0.44, "Ties can affect the up/down approximation.",
|
|
572
|
+
transform=ax.transAxes, va="top", fontsize="small")
|
|
573
|
+
return ax
|
|
574
|
+
|
|
575
|
+
def normality_test(self, ax: Axes | None = None) -> Axes:
|
|
576
|
+
"""Plot normality and, for five or more observations, the Anderson-Darling test."""
|
|
577
|
+
self._require(2, nonconstant=True)
|
|
578
|
+
if ax is None:
|
|
579
|
+
_, ax = plt.subplots(figsize=(9, 6), layout="constrained")
|
|
580
|
+
|
|
581
|
+
values = np.sort(self._data)
|
|
582
|
+
n = values.size
|
|
583
|
+
mean = float(np.mean(values))
|
|
584
|
+
std_dev = float(np.std(values, ddof=1))
|
|
585
|
+
probabilities = (np.arange(1, n + 1) - 0.3) / (n + 0.4)
|
|
586
|
+
quantiles = stats.norm.ppf(probabilities)
|
|
587
|
+
ax.scatter(values, quantiles, s=30, color="#bd3d37", zorder=3, label="Observations")
|
|
588
|
+
|
|
589
|
+
percent_ticks = np.array([0.1, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 99.9])
|
|
590
|
+
tick_positions = stats.norm.ppf(percent_ticks / 100)
|
|
591
|
+
z_min = min(float(tick_positions[1]), float(quantiles[0]) - 0.15)
|
|
592
|
+
z_max = max(float(tick_positions[-2]), float(quantiles[-1]) + 0.15)
|
|
593
|
+
z = np.linspace(z_min, z_max, 300)
|
|
594
|
+
fitted = mean + std_dev * z
|
|
595
|
+
ax.plot(fitted, z, color="#345b9a", linewidth=1.5, label="Normal fit")
|
|
596
|
+
if n >= 3:
|
|
597
|
+
margin = stats.norm.ppf(0.975) * std_dev * np.sqrt(1 / n + z**2 / (2 * (n - 1)))
|
|
598
|
+
ax.plot(fitted - margin, z, color="#345b9a", linewidth=1, linestyle="--", label="Approx. 95% pointwise CI")
|
|
599
|
+
ax.plot(fitted + margin, z, color="#345b9a", linewidth=1, linestyle="--")
|
|
600
|
+
|
|
601
|
+
summary = f"N {n}\nMean {mean:.4g}\nStDev {std_dev:.4g}"
|
|
602
|
+
if n >= 5:
|
|
603
|
+
statistic, p_value = normal_ad(values)
|
|
604
|
+
summary += f"\nAD {statistic:.4g}\nP-value {p_value:.4g}"
|
|
605
|
+
ax.text(
|
|
606
|
+
1.02, 0.98, summary, transform=ax.transAxes, va="top",
|
|
607
|
+
fontfamily="monospace", fontsize="small",
|
|
608
|
+
bbox={"boxstyle": "square,pad=0.4", "facecolor": "white", "edgecolor": "#999999"},
|
|
609
|
+
)
|
|
610
|
+
ax.set_yticks(tick_positions, [f"{value:g}" for value in percent_ticks])
|
|
611
|
+
ax.set_ylim(z_min, z_max)
|
|
612
|
+
ax.set(title="Normal Probability Plot", xlabel="Value", ylabel="Percent")
|
|
613
|
+
ax.grid(True, linestyle="--", linewidth=0.6, alpha=0.5)
|
|
614
|
+
ax.legend(loc="lower right", fontsize="small")
|
|
615
|
+
return ax
|
|
616
|
+
|