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,235 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import html
5
+ import io
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ import pandas as pd
10
+
11
+
12
+ @dataclass
13
+ class ResultTable:
14
+ title: str
15
+ frame: pd.DataFrame
16
+ notes: str = ""
17
+
18
+
19
+ @dataclass
20
+ class PlotSpec:
21
+ kind: str
22
+ params: dict[str, Any] = field(default_factory=dict)
23
+ title: str = ""
24
+ data: pd.DataFrame | None = None
25
+ row_ids: list[Any] | None = None
26
+ include_in_report: bool = True
27
+ row_styles: dict[Any, dict[str, Any]] | None = None
28
+ png_cache: str | None = field(default=None, repr=False, compare=False)
29
+
30
+
31
+ @dataclass
32
+ class AnalysisResult:
33
+ title: str
34
+ tables: list[ResultTable] = field(default_factory=list)
35
+ plots: list[PlotSpec] = field(default_factory=list)
36
+ summary: str = ""
37
+ notes: str = ""
38
+ analysis_type: str = ""
39
+ source_table: str = ""
40
+ params: dict[str, Any] = field(default_factory=dict)
41
+ models: dict[str, Any] = field(default_factory=dict)
42
+ deferred_plots: list[PlotSpec] = field(default_factory=list)
43
+ profiler_session: Any = field(default=None, repr=False, compare=False)
44
+
45
+ def defer_extra_plots(
46
+ self,
47
+ primary_kinds: list[str] | None = None,
48
+ keep_kinds: list[str] | None = None,
49
+ ) -> None:
50
+ """Keep primary plots and park the rest for on-demand addition."""
51
+ if len(self.plots) <= 1:
52
+ return
53
+ original = list(self.plots)
54
+ preferred = list(primary_kinds or [])
55
+ primary_index = 0
56
+ for kind in preferred:
57
+ for index, plot in enumerate(original):
58
+ if plot.kind == kind:
59
+ primary_index = index
60
+ break
61
+ else:
62
+ continue
63
+ break
64
+ keep = set(keep_kinds or [])
65
+ retained = {primary_index} | {index for index, plot in enumerate(original) if plot.kind in keep}
66
+ self.plots = [plot for index, plot in enumerate(original) if index in retained]
67
+ self.deferred_plots.extend(plot for index, plot in enumerate(original) if index not in retained)
68
+
69
+ def add_table(self, title: str, frame: pd.DataFrame, notes: str = "") -> None:
70
+ self.tables.append(ResultTable(title=title, frame=frame, notes=notes))
71
+
72
+ def add_plot(
73
+ self,
74
+ kind: str,
75
+ params: dict[str, Any] | None = None,
76
+ title: str = "",
77
+ data: pd.DataFrame | None = None,
78
+ row_ids: list[Any] | None = None,
79
+ ) -> None:
80
+ self.plots.append(PlotSpec(kind=kind, params=params or {}, title=title, data=data, row_ids=row_ids))
81
+
82
+ def add_model(self, name: str, model: Any) -> None:
83
+ self.models[name] = model
84
+
85
+ def to_html(self, include_plots: bool = True, plot_urls: list[str] | None = None, interactive: bool = False) -> str:
86
+ body: list[str] = [
87
+ "<html><head><meta charset='utf-8'>",
88
+ "<style>",
89
+ "body{font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#20242a;background:#fff;padding:16px;}",
90
+ "h1{font-size:20px;margin:0 0 6px 0;} h2{font-size:15px;margin:20px 0 8px 0;border-bottom:1px solid #d8dde4;padding-bottom:3px;}",
91
+ ".summary{background:#f4f6f8;border-left:4px solid #3c78b4;padding:8px 12px;margin:10px 0;}",
92
+ "table.data{border-collapse:collapse;margin:8px 0 16px 0;font-size:12px;}",
93
+ "table.data th{background:#e9eef4;text-align:left;padding:4px 8px;border:1px solid #ccd3dc;}",
94
+ "table.data td{padding:3px 8px;border:1px solid #d8dde4;white-space:nowrap;}",
95
+ ".note{color:#5a6270;font-size:12px;margin:4px 0 10px 0;}",
96
+ ".plot{margin:12px 0;}",
97
+ "</style></head><body>",
98
+ f"<h1>{html.escape(self.title)}</h1>",
99
+ ]
100
+ if self.source_table:
101
+ body.append(f"<div class='note'>Data table: {html.escape(self.source_table)}</div>")
102
+ if self.summary:
103
+ body.append(f"<div class='summary'>{html.escape(self.summary)}</div>")
104
+ for table in self.tables:
105
+ body.append(f"<h2>{html.escape(table.title)}</h2>")
106
+ if table.notes:
107
+ body.append(f"<div class='note'>{html.escape(table.notes)}</div>")
108
+ body.append(_frame_html(table.frame))
109
+ if include_plots and self.plots:
110
+ visible_index = 0
111
+ plotly_js = False
112
+ for plot in self.plots:
113
+ if not plot.include_in_report:
114
+ continue
115
+ body.append(f"<h2>{html.escape(plot.title or plot.kind.title())}</h2>")
116
+ url = plot_urls[visible_index] if (plot_urls and visible_index < len(plot_urls)) else None
117
+ visible_index += 1
118
+ if interactive:
119
+ fragment = _plot_interactive_html(plot, include_js=not plotly_js)
120
+ if fragment:
121
+ body.append(f"<div class='plot'>{fragment}</div>")
122
+ plotly_js = True
123
+ continue
124
+ if url:
125
+ body.append(f"<div class='plot'><img src='{html.escape(url)}'></div>")
126
+ continue
127
+ try:
128
+ image = _plot_png(plot)
129
+ except Exception as exc:
130
+ body.append(
131
+ f"<div class='note'>Plot could not be rendered: {html.escape(str(exc))}</div>"
132
+ )
133
+ else:
134
+ if image:
135
+ body.append(f"<div class='plot'><img src='data:image/png;base64,{image}'></div>")
136
+ if self.notes:
137
+ body.append(f"<h2>Notes</h2><p>{html.escape(self.notes)}</p>")
138
+ body.append("</body></html>")
139
+ return "".join(body)
140
+
141
+
142
+ def _frame_html(frame: pd.DataFrame) -> str:
143
+ if frame is None or frame.empty:
144
+ return "<div class='note'>No rows.</div>"
145
+ display = frame.copy()
146
+ for column in display.columns:
147
+ if pd.api.types.is_float_dtype(display[column]):
148
+ display[column] = display[column].map(
149
+ lambda value: "" if pd.isna(value) else f"{value:.6g}"
150
+ )
151
+ return display.to_html(index=False, classes="data", border=0, escape=True, na_rep="")
152
+
153
+
154
+ def figure_png_base64(figure, dpi: int = 110) -> str:
155
+ buffer = io.BytesIO()
156
+ figure.savefig(buffer, format="png", dpi=dpi, bbox_inches="tight")
157
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
158
+
159
+
160
+ def _plot_png(spec: PlotSpec) -> str | None:
161
+ if spec.png_cache:
162
+ return spec.png_cache
163
+ from statstudio.plots.registry import build_figure
164
+
165
+ figure = build_figure(spec)
166
+ try:
167
+ spec.png_cache = figure_png_base64(figure)
168
+ return spec.png_cache
169
+ finally:
170
+ try:
171
+ import matplotlib.pyplot as plt
172
+
173
+ plt.close(figure)
174
+ except Exception:
175
+ pass
176
+
177
+
178
+ def _plot_interactive_html(spec: PlotSpec, include_js: bool = True) -> str | None:
179
+ """Render a plot as an interactive Plotly fragment, or None when unavailable."""
180
+ try:
181
+ import plotly # noqa: F401
182
+ except Exception:
183
+ return None
184
+
185
+ plotly_figure = None
186
+ try:
187
+ from statstudio.plots.plotly_builders import build_plotly_figure
188
+
189
+ plotly_figure = build_plotly_figure(spec)
190
+ except Exception:
191
+ plotly_figure = None
192
+
193
+ if plotly_figure is None:
194
+ try:
195
+ from plotly import tools as plotly_tools
196
+
197
+ from statstudio.plots.registry import build_figure
198
+
199
+ figure = build_figure(spec)
200
+ try:
201
+ plotly_figure = plotly_tools.mpl_to_plotly(figure)
202
+ finally:
203
+ try:
204
+ import matplotlib.pyplot as plt
205
+
206
+ plt.close(figure)
207
+ except Exception:
208
+ pass
209
+ except Exception:
210
+ return None
211
+
212
+ try:
213
+ return plotly_figure.to_html(
214
+ full_html=False,
215
+ include_plotlyjs="inline" if include_js else False,
216
+ config={"responsive": True, "displaylogo": False},
217
+ )
218
+ except Exception:
219
+ return None
220
+
221
+
222
+ def format_pvalue(value: float) -> str:
223
+ if value is None or pd.isna(value):
224
+ return ""
225
+ if value < 0.0001:
226
+ return "<0.0001"
227
+ return f"{value:.4f}"
228
+
229
+
230
+ def format_number(value: float, digits: int = 4) -> str:
231
+ if value is None or pd.isna(value):
232
+ return ""
233
+ if abs(value) >= 1e6 or (value != 0 and abs(value) < 1e-4):
234
+ return f"{value:.{digits}e}"
235
+ return f"{value:.{digits}g}"
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import statsmodels.formula.api as smf
8
+
9
+ from statstudio.core.table import DataTable
10
+ from statstudio.stats.doe import _coded_frame, _model_terms, design_factors
11
+ from statstudio.stats.results import AnalysisResult
12
+
13
+
14
+ def simulate_response(
15
+ table: DataTable,
16
+ response: str,
17
+ order: int = 2,
18
+ simulations: int = 1000,
19
+ noise_sd: float | None = None,
20
+ distribution: str = "normal",
21
+ lsl: float | None = None,
22
+ usl: float | None = None,
23
+ seed: int = 42,
24
+ ) -> AnalysisResult:
25
+ factors = design_factors(table)
26
+ if not factors:
27
+ raise ValueError("This table has no DOE design metadata.")
28
+ if simulations < 10:
29
+ raise ValueError("At least ten simulated runs are required.")
30
+ frame = _coded_frame(table, factors, response)
31
+ formula = f'Q("{response}") ~ ' + " + ".join(_model_terms(factors, order))
32
+ model = smf.ols(formula, data=frame).fit()
33
+ rng = np.random.default_rng(seed)
34
+ actual_settings = pd.DataFrame({
35
+ factor.name: rng.uniform(factor.low, factor.high, simulations) for factor in factors
36
+ })
37
+ coded = pd.DataFrame({
38
+ factor.name: (actual_settings[factor.name] - factor.center) / factor.half_range if factor.half_range else 0.0
39
+ for factor in factors
40
+ })
41
+ systematic = np.asarray(model.predict(coded), dtype=float)
42
+ sd = float(noise_sd if noise_sd is not None else np.sqrt(max(model.mse_resid, 0.0)))
43
+ distribution = distribution.lower()
44
+ if distribution in {"normal", "gaussian"}:
45
+ noise = rng.normal(0.0, sd, simulations) if sd > 0 else np.zeros(simulations)
46
+ elif distribution in {"lognormal", "lognormal_noise"}:
47
+ if sd > 0:
48
+ sigma_log = math.sqrt(math.log1p(sd ** 2))
49
+ noise = rng.lognormal(mean=-0.5 * sigma_log ** 2, sigma=sigma_log, size=simulations) - 1.0
50
+ else:
51
+ noise = np.zeros(simulations)
52
+ elif distribution in {"uniform", "uniform_noise"}:
53
+ half = sd * np.sqrt(3)
54
+ noise = rng.uniform(-half, half, simulations)
55
+ else:
56
+ noise = rng.normal(0.0, sd, simulations) if sd > 0 else np.zeros(simulations)
57
+ simulated = systematic + noise
58
+ data = actual_settings.copy()
59
+ data["Systematic"] = systematic
60
+ data["Noise"] = noise
61
+ data["Simulated"] = simulated
62
+ if lsl is not None and usl is not None:
63
+ data["Within Spec"] = (data["Simulated"] >= lsl) & (data["Simulated"] <= usl)
64
+ yield_rate = float(data["Within Spec"].mean())
65
+ else:
66
+ yield_rate = np.nan
67
+ table_result = AnalysisResult(
68
+ title=f"Response Simulation: {response}",
69
+ analysis_type="response_simulation",
70
+ params={"response": response, "order": order, "simulations": simulations, "noise_sd": noise_sd, "distribution": distribution, "lsl": lsl, "usl": usl, "seed": seed},
71
+ source_table=table.name,
72
+ )
73
+ table_result.add_table("Simulation Summary", pd.DataFrame([{
74
+ "Simulations": simulations,
75
+ "Noise Std Dev": sd,
76
+ "Noise Distribution": distribution,
77
+ "Mean": float(np.mean(simulated)),
78
+ "Std Dev": float(np.std(simulated, ddof=1)),
79
+ "P05": float(np.quantile(simulated, 0.05)),
80
+ "P50": float(np.quantile(simulated, 0.50)),
81
+ "P95": float(np.quantile(simulated, 0.95)),
82
+ "Within Spec": yield_rate,
83
+ "Expected PPM": (1 - yield_rate) * 1e6 if np.isfinite(yield_rate) else np.nan,
84
+ }]))
85
+ table_result.add_table("Simulated Runs (first 200)", data.head(200))
86
+ table_result.add_plot("histogram", {"column": "Simulated", "lsl": lsl, "usl": usl}, title=f"Simulated {response}", data=data)
87
+ if lsl is not None or usl is not None:
88
+ table_result.add_plot("capability", {"column": "Simulated", "lsl": lsl, "usl": usl}, title=f"Simulated Capability: {response}", data=data)
89
+ table_result.add_model("doe_model", model)
90
+ table_result.summary = (
91
+ f"{simulations} simulations from the fitted model; mean {np.mean(simulated):.6g}, "
92
+ f"std dev {np.std(simulated, ddof=1):.6g}"
93
+ + (f", within-spec {yield_rate:.2%}." if np.isfinite(yield_rate) else ".")
94
+ )
95
+ return table_result