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.
Files changed (110) hide show
  1. statstudio/__init__.py +9 -0
  2. statstudio/__main__.py +3 -0
  3. statstudio/app.py +83 -0
  4. statstudio/cli.py +116 -0
  5. statstudio/core/__init__.py +3 -0
  6. statstudio/core/archive.py +27 -0
  7. statstudio/core/commands.py +67 -0
  8. statstudio/core/formula_catalog.py +74 -0
  9. statstudio/core/formulas.py +605 -0
  10. statstudio/core/joins.py +123 -0
  11. statstudio/core/project.py +358 -0
  12. statstudio/core/runtime.py +321 -0
  13. statstudio/core/scripting.py +594 -0
  14. statstudio/core/table.py +796 -0
  15. statstudio/core/transform.py +450 -0
  16. statstudio/feature_help.py +595 -0
  17. statstudio/io/__init__.py +3 -0
  18. statstudio/io/docx.py +201 -0
  19. statstudio/io/export.py +99 -0
  20. statstudio/io/file_import.py +199 -0
  21. statstudio/io/odbc.py +334 -0
  22. statstudio/io/sample_data.py +164 -0
  23. statstudio/io/table_io.py +118 -0
  24. statstudio/plots/__init__.py +19 -0
  25. statstudio/plots/advanced.py +651 -0
  26. statstudio/plots/basic.py +957 -0
  27. statstudio/plots/bayesian_plots.py +94 -0
  28. statstudio/plots/common.py +334 -0
  29. statstudio/plots/diagnostics.py +214 -0
  30. statstudio/plots/doe_plots.py +235 -0
  31. statstudio/plots/plotly_builders.py +719 -0
  32. statstudio/plots/predictive_plots.py +72 -0
  33. statstudio/plots/registry.py +251 -0
  34. statstudio/plugins.py +111 -0
  35. statstudio/resources/help_topics.json +13195 -0
  36. statstudio/resources/logo.ico +0 -0
  37. statstudio/resources/logo.png +0 -0
  38. statstudio/resources/statstudio.svg +8 -0
  39. statstudio/stats/__init__.py +42 -0
  40. statstudio/stats/bayesian.py +1094 -0
  41. statstudio/stats/bayesian_optimization.py +590 -0
  42. statstudio/stats/common.py +140 -0
  43. statstudio/stats/correlation.py +135 -0
  44. statstudio/stats/custom_doe.py +1714 -0
  45. statstudio/stats/descriptive.py +200 -0
  46. statstudio/stats/desirability.py +132 -0
  47. statstudio/stats/distributions.py +331 -0
  48. statstudio/stats/doe.py +1070 -0
  49. statstudio/stats/hypothesis.py +1305 -0
  50. statstudio/stats/multivariate.py +307 -0
  51. statstudio/stats/optimal_doe.py +264 -0
  52. statstudio/stats/power.py +194 -0
  53. statstudio/stats/predictive.py +605 -0
  54. statstudio/stats/profiler.py +379 -0
  55. statstudio/stats/quality.py +1218 -0
  56. statstudio/stats/regression.py +1600 -0
  57. statstudio/stats/results.py +235 -0
  58. statstudio/stats/simulator.py +95 -0
  59. statstudio/stats/survival.py +637 -0
  60. statstudio/stats/timeseries.py +643 -0
  61. statstudio/stats/tolerance.py +154 -0
  62. statstudio/ui/__init__.py +0 -0
  63. statstudio/ui/analysis_hub.py +271 -0
  64. statstudio/ui/command_catalog.py +460 -0
  65. statstudio/ui/command_palette.py +55 -0
  66. statstudio/ui/console.py +239 -0
  67. statstudio/ui/dialogs/__init__.py +0 -0
  68. statstudio/ui/dialogs/advanced_dialogs.py +392 -0
  69. statstudio/ui/dialogs/base.py +537 -0
  70. statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
  71. statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
  72. statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
  73. statstudio/ui/dialogs/doe_dialogs.py +220 -0
  74. statstudio/ui/dialogs/extended_dialogs.py +665 -0
  75. statstudio/ui/dialogs/graph_builder.py +139 -0
  76. statstudio/ui/dialogs/help_dialog.py +207 -0
  77. statstudio/ui/dialogs/help_topics.py +280 -0
  78. statstudio/ui/dialogs/lazy.py +184 -0
  79. statstudio/ui/dialogs/odbc_dialog.py +311 -0
  80. statstudio/ui/dialogs/plot_dialog.py +1385 -0
  81. statstudio/ui/dialogs/report_composer.py +218 -0
  82. statstudio/ui/dialogs/script_dialogs.py +267 -0
  83. statstudio/ui/dialogs/stats_dialogs.py +1688 -0
  84. statstudio/ui/dialogs/table_dialogs.py +997 -0
  85. statstudio/ui/dialogs/window.py +58 -0
  86. statstudio/ui/docks/__init__.py +0 -0
  87. statstudio/ui/formula_editor.py +121 -0
  88. statstudio/ui/icons.py +257 -0
  89. statstudio/ui/jobs.py +179 -0
  90. statstudio/ui/main_window.py +3934 -0
  91. statstudio/ui/plot_interaction.py +178 -0
  92. statstudio/ui/profiler_widget.py +437 -0
  93. statstudio/ui/recent.py +82 -0
  94. statstudio/ui/reports/__init__.py +0 -0
  95. statstudio/ui/reports/report_view.py +1632 -0
  96. statstudio/ui/script_jobs.py +35 -0
  97. statstudio/ui/scripts_panel.py +271 -0
  98. statstudio/ui/table_document.py +233 -0
  99. statstudio/ui/table_model.py +285 -0
  100. statstudio/ui/table_view.py +285 -0
  101. statstudio/ui/theme.py +645 -0
  102. statstudio/ui/welcome.py +453 -0
  103. statstudio/ui/window_controls.py +53 -0
  104. statstudio/ui/workers.py +53 -0
  105. statstudio-0.1.0.dist-info/METADATA +261 -0
  106. statstudio-0.1.0.dist-info/RECORD +110 -0
  107. statstudio-0.1.0.dist-info/WHEEL +5 -0
  108. statstudio-0.1.0.dist-info/entry_points.txt +5 -0
  109. statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
  110. statstudio-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,200 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy import stats
8
+
9
+ from statstudio.stats.common import moment_kurtosis, moment_skewness, numeric_columns, numeric_frame, resolve_roles, weighted_mean, weighted_std
10
+ from statstudio.stats.results import AnalysisResult
11
+
12
+
13
+ def _summary_rows(series: pd.Series, label: str, group: str = "", weights: pd.Series | None = None) -> dict[str, object]:
14
+ numeric_values = pd.to_numeric(series, errors="coerce")
15
+ valid = numeric_values.notna()
16
+ if weights is not None:
17
+ valid = valid & pd.Series(weights, index=series.index).notna()
18
+ values = numeric_values[valid]
19
+ n = int(values.count())
20
+ missing = int(series.isna().sum())
21
+ if n == 0:
22
+ return {
23
+ "Variable": label,
24
+ "Group": group,
25
+ "N": 0,
26
+ "Missing": missing,
27
+ "Mean": np.nan,
28
+ "Std Dev": np.nan,
29
+ "Min": np.nan,
30
+ "Q1": np.nan,
31
+ "Median": np.nan,
32
+ "Q3": np.nan,
33
+ "Max": np.nan,
34
+ "Skewness": np.nan,
35
+ "Kurtosis": np.nan,
36
+ "CI Low": np.nan,
37
+ "CI High": np.nan,
38
+ }
39
+ weights_valid = weights[valid] if weights is not None else None
40
+ mean = weighted_mean(values, weights_valid)
41
+ std = weighted_std(values, weights_valid) if n > 1 else np.nan
42
+ effective_n = float(n)
43
+ if weights_valid is not None:
44
+ weight_array = pd.to_numeric(weights_valid, errors="coerce").to_numpy(dtype=float)
45
+ total_weight = float(weight_array.sum())
46
+ squared_weight = float(np.sum(weight_array**2))
47
+ if squared_weight > 0:
48
+ effective_n = total_weight**2 / squared_weight
49
+ if effective_n > 1 and std and np.isfinite(std):
50
+ ci_low, ci_high = stats.t.interval(0.95, effective_n - 1, loc=mean, scale=std / np.sqrt(effective_n))
51
+ else:
52
+ ci_low = ci_high = np.nan
53
+ return {
54
+ "Variable": label,
55
+ "Group": group,
56
+ "N": n,
57
+ "Missing": missing,
58
+ "Mean": mean,
59
+ "Std Dev": std,
60
+ "Std Error": std / np.sqrt(effective_n) if effective_n and std and np.isfinite(std) else np.nan,
61
+ "CV": std / mean if mean else np.nan,
62
+ "Min": float(values.min()),
63
+ "Q1": float(values.quantile(0.25)),
64
+ "Median": float(values.median()),
65
+ "Q3": float(values.quantile(0.75)),
66
+ "Max": float(values.max()),
67
+ "Range": float(values.max() - values.min()),
68
+ "Sum of Squares": float(np.sum((values - mean) ** 2)),
69
+ "Trimmed Mean": float(stats.trim_mean(values, 0.1)),
70
+ "MSSD": float(np.mean(np.diff(values) ** 2)) if n > 1 else np.nan,
71
+ "Skewness": moment_skewness(values) if n > 2 else np.nan,
72
+ "Kurtosis": moment_kurtosis(values) if n > 3 else np.nan,
73
+ "CI Low": float(ci_low),
74
+ "CI High": float(ci_high),
75
+ }
76
+
77
+
78
+ def describe(
79
+ df: pd.DataFrame,
80
+ columns: Sequence[str] | None = None,
81
+ group: str | None = None,
82
+ weight: str | None = None,
83
+ freq: str | None = None,
84
+ ) -> AnalysisResult:
85
+ if columns is None:
86
+ columns = numeric_columns(df)
87
+ columns = [c for c in columns if c in df.columns]
88
+ if not columns:
89
+ raise ValueError("Choose at least one numeric column.")
90
+ roles = resolve_roles(
91
+ df,
92
+ columns + ([group] if group else []),
93
+ freq=freq,
94
+ weight=weight,
95
+ dropna=False,
96
+ )
97
+ frame = roles.frame
98
+ rows: list[dict[str, object]] = []
99
+ weights = roles.weight
100
+ if group and group in frame.columns:
101
+ for group_value, chunk in frame.groupby(group, dropna=False, sort=True):
102
+ label = "Missing" if pd.isna(group_value) else str(group_value)
103
+ for column in columns:
104
+ chunk_weights = weights.reindex(chunk.index) if weights is not None else None
105
+ rows.append(_summary_rows(chunk[column], column, label, chunk_weights))
106
+ else:
107
+ for column in columns:
108
+ rows.append(_summary_rows(frame[column], column, weights=weights))
109
+ summary_frame = pd.DataFrame(rows)
110
+ result = AnalysisResult(
111
+ title="Descriptive Statistics",
112
+ analysis_type="descriptive",
113
+ source_table="",
114
+ params={"columns": list(columns), "group": group, "weight": weight, "freq": freq},
115
+ )
116
+ result.add_table("Summary Statistics", summary_frame)
117
+ if group and group in frame.columns:
118
+ for column in columns:
119
+ result.add_plot(
120
+ "box",
121
+ {"column": column, "group": group},
122
+ title=f"{column} by {group}",
123
+ data=frame,
124
+ )
125
+ else:
126
+ for column in columns:
127
+ result.add_plot("histogram", {"column": column}, title=f"Distribution of {column}", data=frame)
128
+ numeric = numeric_frame(frame, columns)
129
+ correlation = numeric.corr(numeric_only=True)
130
+ if len(columns) > 1:
131
+ result.add_table("Correlations", correlation.reset_index().rename(columns={"index": "Variable"}))
132
+ result.add_plot("correlation_heatmap", {"columns": list(columns)}, title="Correlation Heatmap", data=frame)
133
+ result.summary = (
134
+ f"Summary for {len(columns)} variable(s)"
135
+ + (f" grouped by {group}" if group else "")
136
+ + f". Total rows: {len(frame)}."
137
+ )
138
+ return result
139
+
140
+
141
+ def frequency_table(df: pd.DataFrame, column: str, max_levels: int = 50) -> AnalysisResult:
142
+ if column not in df.columns:
143
+ raise KeyError(column)
144
+ all_counts = df[column].fillna("(missing)").astype(str).value_counts(dropna=False)
145
+ counts = all_counts.head(max_levels)
146
+ missing_count = int(df[column].isna().sum())
147
+ frame = counts.rename_axis(column).reset_index(name="Count")
148
+ frame["Percent"] = (frame["Count"] / len(df) * 100).round(3)
149
+ if len(all_counts) > max_levels:
150
+ omitted = int(all_counts.iloc[max_levels:].sum())
151
+ other_percent = round(100.0 - float(frame["Percent"].sum()), 3)
152
+ other = pd.DataFrame([{column: "(other levels)", "Count": omitted, "Percent": other_percent}])
153
+ frame = pd.concat([frame, other], ignore_index=True)
154
+ result = AnalysisResult(
155
+ title=f"Distribution of {column}",
156
+ analysis_type="frequency",
157
+ params={"column": column},
158
+ )
159
+ result.add_table("Frequency", frame)
160
+ result.add_plot("bar", {"x": column, "y": "Count"}, title=f"Counts of {column}", data=frame)
161
+ result.summary = f"{int(len(df) - missing_count)} non-missing values across {len(all_counts)} levels ({missing_count} missing)."
162
+ if len(all_counts) > max_levels:
163
+ result.notes = f"Showing the {max_levels} most frequent of {len(all_counts)} levels; {len(all_counts) - max_levels} level(s) are omitted."
164
+ return result
165
+
166
+
167
+ def grouped_summary(
168
+ df: pd.DataFrame,
169
+ response: str,
170
+ group: str,
171
+ aggregate: str = "mean",
172
+ ) -> AnalysisResult:
173
+ if response not in df.columns or group not in df.columns:
174
+ raise KeyError("Response or group column missing.")
175
+ frame = df.copy()
176
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
177
+ grouped = frame.groupby(group, dropna=False)[response]
178
+ aggregate = aggregate.lower()
179
+ if aggregate not in {"mean", "median", "sum", "count", "std", "min", "max"}:
180
+ raise ValueError(f"Unsupported aggregate: {aggregate}")
181
+ if aggregate == "mean":
182
+ table = grouped.agg(["count", "mean", "std", "min", "median", "max"]).reset_index()
183
+ table.columns = [group, "N", "Mean", "Std Dev", "Min", "Median", "Max"]
184
+ result = AnalysisResult(
185
+ title=f"{response} by {group}",
186
+ analysis_type="grouped_summary",
187
+ params={"response": response, "group": group, "aggregate": aggregate},
188
+ )
189
+ result.add_table("Group Summary", table)
190
+ result.add_plot("bar", {"x": group, "y": "Mean", "error": "Std Dev"}, title=f"Mean {response} by {group}", data=table)
191
+ return result
192
+ values = grouped.agg(aggregate).reset_index(name=aggregate.title())
193
+ result = AnalysisResult(
194
+ title=f"{response} by {group}",
195
+ analysis_type="grouped_summary",
196
+ params={"response": response, "group": group, "aggregate": aggregate},
197
+ )
198
+ result.add_table("Group Summary", values)
199
+ result.add_plot("bar", {"x": group, "y": aggregate.title()}, title=f"{aggregate.title()} {response} by {group}", data=values)
200
+ return result
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Sequence
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy.optimize import minimize
8
+
9
+ from statstudio.stats.results import AnalysisResult
10
+
11
+
12
+ def desirability_score(value: float, low: float | None = None, high: float | None = None, target: float | None = None, weight: float = 1.0, goal: str = "maximize") -> float:
13
+ weight = max(float(weight), 1e-9)
14
+ goal = goal.lower()
15
+ if goal in {"max", "maximize"}:
16
+ if low is None or high is None:
17
+ return float("nan")
18
+ if value <= low:
19
+ return 0.0
20
+ if value >= high:
21
+ return 1.0
22
+ return float(((value - low) / (high - low)) ** weight)
23
+ if goal in {"min", "minimize"}:
24
+ if low is None or high is None:
25
+ return float("nan")
26
+ if value <= low:
27
+ return 1.0
28
+ if value >= high:
29
+ return 0.0
30
+ return float(((high - value) / (high - low)) ** weight)
31
+ if goal in {"target", "nominal"}:
32
+ if low is None or high is None or target is None:
33
+ return float("nan")
34
+ if value < low or value > high:
35
+ return 0.0
36
+ if value == target:
37
+ return 1.0
38
+ denominator = target - low if value < target else high - target
39
+ if denominator <= 0:
40
+ return 1.0
41
+ return float((1 - abs(value - target) / denominator) ** weight)
42
+ if goal in {"within", "range", "within range"}:
43
+ if low is None or high is None:
44
+ return float("nan")
45
+ return 1.0 if low <= value <= high else 0.0
46
+ raise ValueError(f"Unknown desirability goal: {goal}")
47
+
48
+
49
+ def overall_desirability(scores: Sequence[float], importance: Sequence[float] | None = None) -> float:
50
+ raw_values = np.asarray(scores, dtype=float)
51
+ raw_weights = np.asarray(importance, dtype=float) if importance is not None else np.ones(len(raw_values))
52
+ if len(raw_weights) < len(raw_values):
53
+ raw_weights = np.resize(raw_weights, len(raw_values))
54
+ finite = np.isfinite(raw_values)
55
+ values = raw_values[finite]
56
+ weights = raw_weights[finite]
57
+ if len(values) == 0 or np.any(values <= 0):
58
+ return 0.0
59
+ weights = np.where(weights > 0, weights, 1.0)
60
+ return float(np.exp(np.sum(weights * np.log(values)) / np.sum(weights)))
61
+
62
+
63
+ def multi_response_optimize(
64
+ models: dict[str, Any],
65
+ factors: Sequence[Any],
66
+ goals: dict[str, dict[str, Any]],
67
+ response: str = "Overall",
68
+ starts: int = 20,
69
+ seed: int = 42,
70
+ order: int = 2,
71
+ ) -> AnalysisResult:
72
+ if not models or not factors:
73
+ raise ValueError("At least one model and one factor are required.")
74
+ rng = np.random.default_rng(seed)
75
+
76
+ def settings_frame(values: Sequence[float]) -> pd.DataFrame:
77
+ return pd.DataFrame([{factor.name: float(value) for factor, value in zip(factors, values)}])
78
+
79
+ def desirability(values: Sequence[float]) -> tuple[float, dict[str, float], dict[str, float]]:
80
+ encoded = settings_frame(values)
81
+ scores = {}
82
+ predictions = {}
83
+ for model_name, model in models.items():
84
+ goal = goals.get(model_name, {"goal": "maximize"})
85
+ prediction = float(model.predict(encoded).iloc[0])
86
+ predictions[model_name] = prediction
87
+ scores[model_name] = desirability_score(
88
+ prediction,
89
+ goal.get("low"),
90
+ goal.get("high"),
91
+ goal.get("target"),
92
+ goal.get("weight", 1.0),
93
+ goal.get("goal", "maximize"),
94
+ )
95
+ importance = [goals.get(name, {}).get("importance", 1.0) for name in scores]
96
+ return overall_desirability(list(scores.values()), importance), scores, predictions
97
+
98
+ def objective(values: np.ndarray) -> float:
99
+ return -desirability(values)[0]
100
+
101
+ starts_values = [np.zeros(len(factors))]
102
+ starts_values.extend(rng.uniform(-1, 1, size=len(factors)) for _ in range(max(1, starts)))
103
+ best = None
104
+ for start in starts_values:
105
+ try:
106
+ outcome = minimize(objective, start, bounds=[(-1, 1)] * len(factors), method="L-BFGS-B")
107
+ except Exception:
108
+ continue
109
+ if best is None or outcome.fun < best.fun:
110
+ best = outcome
111
+ if best is None:
112
+ raise ValueError("Optimization failed.")
113
+ score, individual, predictions = desirability(best.x)
114
+ row: dict[str, Any] = {"Overall Desirability": score}
115
+ for factor, value in zip(factors, best.x):
116
+ row[f"{factor.name} (coded)"] = float(value)
117
+ row[f"{factor.name} (actual)"] = factor.actual(float(value))
118
+ for name, value in predictions.items():
119
+ row[f"Predicted {name}"] = value
120
+ row[f"Desirability {name}"] = individual.get(name)
121
+ table = pd.DataFrame([row])
122
+ result = AnalysisResult(
123
+ title=f"Multi-Response Optimization: {response}",
124
+ analysis_type="multi_response_optimization",
125
+ params={"responses": list(models.keys()), "goals": goals, "starts": starts, "seed": seed, "order": int(order), "response": response},
126
+ )
127
+ result.add_table("Optimal Settings", table)
128
+ detail = pd.DataFrame([{"Response": name, "Prediction": predictions[name], "Desirability": individual[name], "Importance": goals.get(name, {}).get("importance", 1.0)} for name in models])
129
+ result.add_table("Response Desirability", detail)
130
+ result.add_plot("bar", {"x": "Response", "y": "Desirability"}, title="Desirability by Response", data=detail)
131
+ result.summary = f"Overall desirability = {score:.4f} across {len(models)} responses."
132
+ return result
@@ -0,0 +1,331 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy import stats
8
+
9
+ from statstudio.stats.common import moment_kurtosis, moment_skewness
10
+ from statstudio.stats.results import AnalysisResult
11
+
12
+ SCIPY_NAMES = {"normal": "norm"}
13
+
14
+ DISTRIBUTIONS = {
15
+ "normal": "Normal",
16
+ "lognorm": "Lognormal (3-parameter)",
17
+ "expon": "Exponential (2-parameter)",
18
+ "gamma": "Gamma (3-parameter)",
19
+ "weibull_min": "Weibull (3-parameter)",
20
+ "loglogistic": "Loglogistic",
21
+ "beta": "Beta",
22
+ "uniform": "Uniform",
23
+ "logistic": "Logistic",
24
+ "loggamma": "Loggamma",
25
+ "invgauss": "Inverse Gaussian",
26
+ "genpareto": "Generalized Pareto",
27
+ "rayleigh": "Rayleigh",
28
+ "johnsonsu": "Johnson SU",
29
+ "johnsonsb": "Johnson SB",
30
+ }
31
+
32
+ SCIPY_ALIASES = {"loglogistic": "fisk"}
33
+ POSITIVE = {"lognorm", "gamma", "weibull_min", "loglogistic", "loggamma", "invgauss", "genpareto", "rayleigh", "johnsonsb"}
34
+ UNIT_INTERVAL = {"beta", "johnsonsb"}
35
+
36
+
37
+ def fit_distribution(
38
+ df: pd.DataFrame,
39
+ column: str,
40
+ distribution: str = "normal",
41
+ bootstrap_ks: bool = True,
42
+ ) -> AnalysisResult:
43
+ if column not in df.columns:
44
+ raise KeyError(column)
45
+ if distribution not in DISTRIBUTIONS:
46
+ raise ValueError(f"Unsupported distribution: {distribution}")
47
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
48
+ if len(values) < 5:
49
+ raise ValueError("At least five observations are required.")
50
+ if distribution in POSITIVE and np.any(values <= 0):
51
+ raise ValueError(f"{DISTRIBUTIONS[distribution]} requires positive values.")
52
+ if distribution in UNIT_INTERVAL and (np.any(values <= 0) or np.any(values >= 1)):
53
+ raise ValueError(f"{DISTRIBUTIONS[distribution]} requires values between 0 and 1.")
54
+ scipy_name = SCIPY_NAMES.get(distribution, SCIPY_ALIASES.get(distribution, distribution))
55
+ scipy_distribution = getattr(stats, scipy_name)
56
+ try:
57
+ parameters = scipy_distribution.fit(values)
58
+ except Exception as exc:
59
+ raise ValueError(f"Could not fit {DISTRIBUTIONS[distribution]}: {exc}") from exc
60
+ log_likelihood = float(np.sum(scipy_distribution.logpdf(values, *parameters)))
61
+ parameter_count = len(parameters)
62
+ aic = 2 * parameter_count - 2 * log_likelihood
63
+ bic = parameter_count * np.log(len(values)) - 2 * log_likelihood
64
+ aicc = aic + (2 * parameter_count * (parameter_count + 1) / max(1, len(values) - parameter_count - 1))
65
+ ks_statistic, ks_pvalue = stats.kstest(values, scipy_distribution.cdf, args=parameters)
66
+ ad_statistic = _anderson_darling(values, scipy_distribution, parameters)
67
+ ks_label = "KS p-value"
68
+ if distribution in {"normal", "expon"}:
69
+ try:
70
+ from statsmodels.stats.diagnostic import lilliefors
71
+
72
+ ks_statistic, ks_pvalue = lilliefors(values, dist="norm" if distribution == "normal" else "expon")
73
+ ks_label = "KS p-value (Lilliefors)"
74
+ except Exception:
75
+ ks_label = "KS p-value (approx.)"
76
+ elif bootstrap_ks:
77
+ ks_statistic, ks_pvalue = _parametric_bootstrap_ks(values, scipy_distribution, parameters)
78
+ ks_label = "KS p-value (parametric bootstrap)"
79
+ else:
80
+ ks_pvalue = np.nan
81
+ ks_label = "KS p-value (bootstrap not computed)"
82
+ names = _parameter_names(distribution, parameter_count)
83
+ parameters_frame = pd.DataFrame(
84
+ [{"Parameter": name, "Estimate": value} for name, value in zip(names, parameters)]
85
+ )
86
+ metrics = pd.DataFrame(
87
+ [
88
+ ("Distribution", DISTRIBUTIONS[distribution]),
89
+ ("N", len(values)),
90
+ ("Mean", float(np.mean(values))),
91
+ ("Std Dev", float(np.std(values, ddof=1))),
92
+ ("Log likelihood", log_likelihood),
93
+ ("AIC", aic),
94
+ ("AICc", aicc),
95
+ ("BIC", bic),
96
+ ("Anderson-Darling", ad_statistic),
97
+ ("KS statistic", ks_statistic),
98
+ (ks_label, ks_pvalue),
99
+ ],
100
+ columns=["Metric", "Value"],
101
+ )
102
+ result = AnalysisResult(
103
+ title=f"Distribution Fit: {column} ({DISTRIBUTIONS[distribution]})",
104
+ analysis_type="distribution_fit",
105
+ params={"column": column, "distribution": distribution},
106
+ )
107
+ result.add_table("Parameters", parameters_frame)
108
+ result.add_table("Fit Statistics", metrics)
109
+ result.add_plot(
110
+ "histogram",
111
+ {
112
+ "column": column,
113
+ "distribution": distribution,
114
+ "scipy_distribution": scipy_name,
115
+ "fit_args": list(parameters),
116
+ },
117
+ title=f"Fitted {DISTRIBUTIONS[distribution]}: {column}",
118
+ data=df,
119
+ )
120
+ result.summary = (
121
+ f"{DISTRIBUTIONS[distribution]} fit to {len(values)} observations; "
122
+ f"AICc = {aicc:.4g}, KS p = {ks_pvalue:.4g}."
123
+ )
124
+ return result
125
+
126
+
127
+ def _parametric_bootstrap_ks(
128
+ values: np.ndarray,
129
+ distribution,
130
+ parameters: tuple,
131
+ *,
132
+ replicates: int | None = None,
133
+ seed: int = 20240101,
134
+ ) -> tuple[float, float]:
135
+ """KS goodness-of-fit p-value that accounts for parameters estimated from the data.
136
+
137
+ The null distribution is generated by repeatedly resampling from the fitted
138
+ distribution, refitting the parameters, and recomputing the KS statistic.
139
+ This avoids the anti-conservative p-values produced by comparing an
140
+ estimated-parameter fit against the fixed-parameter KS distribution.
141
+ """
142
+ statistic = float(stats.kstest(values, distribution.cdf, args=parameters).statistic)
143
+ n = len(values)
144
+ if replicates is None:
145
+ if n <= 200:
146
+ replicates = 199
147
+ elif n <= 2000:
148
+ replicates = 99
149
+ elif n <= 10000:
150
+ replicates = 49
151
+ else:
152
+ replicates = 19
153
+ rng = np.random.default_rng(seed)
154
+ exceedances = 0
155
+ for _ in range(replicates):
156
+ sample = distribution.rvs(*parameters, size=n, random_state=rng)
157
+ try:
158
+ fitted = distribution.fit(sample)
159
+ except Exception:
160
+ fitted = parameters
161
+ simulated = float(stats.kstest(sample, distribution.cdf, args=fitted).statistic)
162
+ if simulated >= statistic:
163
+ exceedances += 1
164
+ pvalue = (exceedances + 1.0) / (replicates + 1.0)
165
+ return statistic, float(pvalue)
166
+
167
+
168
+ def _anderson_darling(values: np.ndarray, distribution, parameters: tuple) -> float:
169
+ ordered = np.sort(values)
170
+ cdf = np.clip(distribution.cdf(ordered, *parameters), 1e-12, 1 - 1e-12)
171
+ n = len(ordered)
172
+ index = np.arange(1, n + 1)
173
+ return float(-n - np.sum((2 * index - 1) * (np.log(cdf) + np.log(1 - cdf[::-1]))) / n)
174
+
175
+
176
+ def distribution_id(df: pd.DataFrame, column: str, candidates: Sequence[str] | None = None) -> AnalysisResult:
177
+ if column not in df.columns:
178
+ raise KeyError(column)
179
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
180
+ if len(values) < 5:
181
+ raise ValueError("At least five observations are required.")
182
+ keys = list(candidates or DISTRIBUTIONS.keys())
183
+ rows = []
184
+ for key in keys:
185
+ if key not in DISTRIBUTIONS:
186
+ continue
187
+ if key in POSITIVE and np.any(values <= 0):
188
+ continue
189
+ if key in UNIT_INTERVAL and (np.any(values <= 0) or np.any(values >= 1)):
190
+ continue
191
+ try:
192
+ result = fit_distribution(df, column, key, bootstrap_ks=False)
193
+ metrics = result.tables[1].frame.set_index("Metric")["Value"]
194
+ rows.append({
195
+ "Distribution": DISTRIBUTIONS[key],
196
+ "Key": key,
197
+ "AIC": metrics.get("AIC"),
198
+ "AICc": metrics.get("AICc"),
199
+ "BIC": metrics.get("BIC"),
200
+ "Anderson-Darling": metrics.get("Anderson-Darling"),
201
+ })
202
+ except Exception:
203
+ continue
204
+ if not rows:
205
+ raise ValueError("No distribution could be fitted to these values.")
206
+ table = pd.DataFrame(rows).sort_values(["AICc", "Anderson-Darling"], na_position="last").reset_index(drop=True)
207
+ table.insert(0, "Rank", np.arange(1, len(table) + 1))
208
+ best = table.iloc[0]
209
+ result = AnalysisResult(
210
+ title=f"Distribution Identification: {column}",
211
+ analysis_type="distribution_id",
212
+ params={"column": column, "candidates": keys},
213
+ )
214
+ result.add_table("Distribution Ranking", table)
215
+ result.add_plot("histogram", {"column": column, "distribution": best["Key"], "scipy_distribution": SCIPY_ALIASES.get(best["Key"], SCIPY_NAMES.get(best["Key"], best["Key"]))}, title=f"Best Fit: {best['Distribution']}", data=df)
216
+ result.summary = f"Best fitting distribution: {best['Distribution']} (AICc = {best['AICc']:.6g})."
217
+ result.notes = (
218
+ "Ranking is by AICc. Anderson-Darling statistics are provided for comparison; "
219
+ "KS p-values are omitted because they require a separate bootstrap for each candidate."
220
+ )
221
+ return result
222
+
223
+
224
+ def _parameter_names(distribution: str, count: int) -> list[str]:
225
+ if count == 2:
226
+ return ["Location", "Scale"]
227
+ if count == 3:
228
+ return ["Shape", "Location", "Scale"]
229
+ if count == 4:
230
+ return ["Shape 1", "Shape 2", "Location", "Scale"]
231
+ return [f"Parameter {i + 1}" for i in range(count)]
232
+
233
+
234
+ def distribution_summary(
235
+ df: pd.DataFrame,
236
+ columns: Sequence[str],
237
+ group: str | None = None,
238
+ ci_width: float = 95.0,
239
+ ) -> AnalysisResult:
240
+ """Summary + normality (Shapiro-Wilk) with optional grouping and Q-Q plots."""
241
+ from scipy import stats as scipy_stats
242
+
243
+ columns = [c for c in columns if c in df.columns]
244
+ if not columns:
245
+ raise ValueError("Choose at least one numeric column.")
246
+ rows = []
247
+ normality_rows = []
248
+ alpha = 1 - ci_width / 100.0
249
+
250
+ def summarize(series: pd.Series, label: str, group_label: str = "") -> None:
251
+ values = pd.to_numeric(series, errors="coerce").dropna()
252
+ n = int(values.count())
253
+ if n == 0:
254
+ rows.append({"Variable": label, "Group": group_label, "N": 0})
255
+ return
256
+ mean = float(values.mean())
257
+ std = float(values.std(ddof=1)) if n > 1 else 0.0
258
+ se = std / np.sqrt(n) if n else np.nan
259
+ if n > 1 and std > 0:
260
+ crit = scipy_stats.t.ppf(1 - alpha / 2, n - 1)
261
+ ci_low, ci_high = mean - crit * se, mean + crit * se
262
+ else:
263
+ ci_low = ci_high = mean
264
+ rows.append(
265
+ {
266
+ "Variable": label,
267
+ "Group": group_label,
268
+ "N": n,
269
+ "Missing": int(series.isna().sum()),
270
+ "Mean": mean,
271
+ "Std Dev": std,
272
+ "Std Error": se,
273
+ "CI Low": ci_low,
274
+ "CI High": ci_high,
275
+ "Min": float(values.min()),
276
+ "Q1": float(values.quantile(0.25)),
277
+ "Median": float(values.median()),
278
+ "Q3": float(values.quantile(0.75)),
279
+ "Max": float(values.max()),
280
+ "Skewness": moment_skewness(values) if n > 2 else np.nan,
281
+ "Kurtosis": moment_kurtosis(values) if n > 3 else np.nan,
282
+ }
283
+ )
284
+ if 3 <= n <= 5000:
285
+ try:
286
+ statistic, pvalue = scipy_stats.shapiro(values)
287
+ ad_result = scipy_stats.anderson(values, dist="norm")
288
+ ordered = np.sort(values)
289
+ normal_scores = scipy_stats.norm.ppf((np.arange(1, n + 1) - 0.375) / (n + 0.25))
290
+ ryan_joiner = float(np.corrcoef(ordered, normal_scores)[0, 1])
291
+ normality_rows.append(
292
+ {
293
+ "Variable": label,
294
+ "Group": group_label,
295
+ "Test": "Shapiro-Wilk",
296
+ "W": statistic,
297
+ "p-value": pvalue,
298
+ "Anderson-Darling": float(ad_result.statistic),
299
+ "Ryan-Joiner": ryan_joiner,
300
+ }
301
+ )
302
+ except Exception:
303
+ pass
304
+
305
+ if group and group in df.columns:
306
+ for group_value, chunk in df.groupby(group, dropna=False, sort=True):
307
+ group_label = "Missing" if pd.isna(group_value) else str(group_value)
308
+ for column in columns:
309
+ summarize(chunk[column], column, group_label)
310
+ else:
311
+ for column in columns:
312
+ summarize(df[column], column)
313
+ result = AnalysisResult(
314
+ title="Distribution",
315
+ analysis_type="distribution_summary",
316
+ params={"columns": list(columns), "group": group, "ci_width": ci_width},
317
+ )
318
+ result.add_table("Summary Statistics", pd.DataFrame(rows))
319
+ if normality_rows:
320
+ normality = pd.DataFrame(normality_rows)
321
+ normality["Significance"] = normality["p-value"].map(
322
+ lambda p: "***" if p < 0.001 else "**" if p < 0.01 else "*" if p < 0.05 else ""
323
+ )
324
+ result.add_table("Normality (Shapiro-Wilk)", normality)
325
+ for column in columns:
326
+ result.add_plot("histogram", {"column": column, "group": group}, title=f"Distribution of {column}", data=df)
327
+ if not group:
328
+ result.add_plot("qq", {"column": column}, title=f"Q-Q Plot: {column}", data=df)
329
+ result.add_plot("box", {"column": column, "group": group}, title=f"Box Plot: {column}", data=df)
330
+ result.summary = f"Distribution summary for {', '.join(columns)}" + (f" grouped by {group}" if group else "") + "."
331
+ return result