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,239 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import importlib
5
+ import io
6
+ import traceback
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from PySide6.QtCore import QEvent, Qt
11
+ from PySide6.QtGui import QFont
12
+ from PySide6.QtWidgets import (
13
+ QHBoxLayout,
14
+ QLabel,
15
+ QPlainTextEdit,
16
+ QPushButton,
17
+ QVBoxLayout,
18
+ QWidget,
19
+ )
20
+
21
+ from statstudio.core import transform
22
+ from statstudio.core.joins import append_tables, merge_tables
23
+ from statstudio.core.project import Project
24
+ from statstudio.core.table import DataTable, add_rows
25
+ from statstudio.io.file_import import CSVOptions, read_file
26
+ from statstudio.io.sample_data import load_sample
27
+ from statstudio.io.table_io import load_table
28
+ from statstudio.stats.results import AnalysisResult, PlotSpec
29
+
30
+
31
+ class _LazyModule:
32
+ """Resolve a heavy package only when a script actually uses it."""
33
+
34
+ def __init__(self, name: str) -> None:
35
+ self._name = name
36
+
37
+ def _module(self):
38
+ return importlib.import_module(self._name)
39
+
40
+ def __getattr__(self, name: str):
41
+ return getattr(self._module(), name)
42
+
43
+ def __repr__(self) -> str:
44
+ return f"<lazy module {self._name!r}>"
45
+
46
+
47
+ class ConsoleSDK:
48
+ """Small scripting API exposing the StatStudio automation surface."""
49
+
50
+ def __init__(self, console: "PythonConsole") -> None:
51
+ self._console = console
52
+
53
+ def datasets(self) -> list[str]:
54
+ return [table.name for table in self._console.project.tables]
55
+
56
+ def dataset(self, name: str):
57
+ return self._console.project.get_table(name)
58
+
59
+ def analyses(self) -> list[str]:
60
+ return [report.title for report in self._console.project.reports]
61
+
62
+ def reports(self) -> list[str]:
63
+ return self.analyses()
64
+
65
+ def history(self) -> list[str]:
66
+ return list(self._console.history)
67
+
68
+ def journal(self) -> list[str]:
69
+ return [entry.title for entry in self._console.project.journal]
70
+
71
+ def run(self, code: str) -> str:
72
+ return self._console.execute(code)
73
+
74
+ def show(self, result: AnalysisResult):
75
+ """Open an AnalysisResult in a report window."""
76
+ if not isinstance(result, AnalysisResult):
77
+ raise TypeError("sdk.show expects an AnalysisResult returned by an analysis.")
78
+ window = self._console.window()
79
+ show_result = getattr(window, "show_result", None)
80
+ if not callable(show_result):
81
+ raise RuntimeError("The report window is unavailable in this context.")
82
+ return show_result(result)
83
+
84
+ def new_dataset(self, name: str = "Dataset"):
85
+ table = DataTable(pd.DataFrame(), name)
86
+ window = self._console.window()
87
+ if hasattr(window, "_add_table"):
88
+ return window._add_table(table)
89
+ self._console.project.add_table(table)
90
+ return table
91
+
92
+
93
+ class PythonConsole(QWidget):
94
+ def __init__(self, project: Project, parent: QWidget | None = None) -> None:
95
+ super().__init__(parent)
96
+ self.project = project
97
+ self.history: list[str] = []
98
+ self._history_pos = 0
99
+ self.namespace: dict[str, object] = {}
100
+ self.sdk = ConsoleSDK(self)
101
+ self._reset_namespace()
102
+ layout = QVBoxLayout(self)
103
+ layout.setContentsMargins(4, 4, 4, 4)
104
+ self.output = QPlainTextEdit()
105
+ self.output.setReadOnly(True)
106
+ self.output.setFont(QFont("monospace", 9))
107
+ self.output.setPlainText(
108
+ "StatStudio Python console\n"
109
+ "Available: project, tables(), stats, plots, pd, np, sdk\n"
110
+ "Persistent namespace: variables defined here carry across runs.\n"
111
+ "Example: sdk.datasets() | result = stats.descriptive.describe(tables()[0].analysis_df(), ['Height'])\n"
112
+ "Display a result: sdk.show(result)\n"
113
+ )
114
+ layout.addWidget(self.output, 1)
115
+ input_row = QHBoxLayout()
116
+ input_row.addWidget(QLabel(">>>"))
117
+ self.input = QPlainTextEdit()
118
+ self.input.setFont(QFont("monospace", 9))
119
+ self.input.setMaximumHeight(72)
120
+ self.input.setPlaceholderText("Enter Python code. Ctrl+Enter to run.")
121
+ self.input.installEventFilter(self)
122
+ input_row.addWidget(self.input, 1)
123
+ run_button = QPushButton("Run")
124
+ run_button.clicked.connect(self.run_code)
125
+ input_row.addWidget(run_button)
126
+ layout.addLayout(input_row)
127
+ from statstudio.ui.dialogs.help_topics import install_context_help
128
+
129
+ install_context_help(self, "python-console")
130
+
131
+ def _reset_namespace(self) -> None:
132
+ self.namespace = {
133
+ "project": self.project,
134
+ "tables": lambda: self.project.tables,
135
+ "stats": _LazyModule("statstudio.stats"),
136
+ "plots": _LazyModule("statstudio.plots"),
137
+ "pd": pd,
138
+ "np": np,
139
+ "sdk": self.sdk,
140
+ "transform": transform,
141
+ "merge_tables": merge_tables,
142
+ "append_tables": append_tables,
143
+ "read_file": read_file,
144
+ "CSVOptions": CSVOptions,
145
+ "load_sample": load_sample,
146
+ "load_table": load_table,
147
+ "DataTable": DataTable,
148
+ "add_rows": add_rows,
149
+ "PlotSpec": PlotSpec,
150
+ }
151
+
152
+ def set_project(self, project: Project) -> None:
153
+ self.project = project
154
+ self._reset_namespace()
155
+
156
+ def eventFilter(self, obj, event):
157
+ if obj is self.input and event.type() == QEvent.Type.KeyPress:
158
+ control = bool(event.modifiers() & Qt.KeyboardModifier.ControlModifier)
159
+ if event.key() == Qt.Key.Key_Return and control:
160
+ self.run_code()
161
+ return True
162
+ if control and event.key() == Qt.Key.Key_Up and self.history:
163
+ self._history_pos = min(len(self.history), self._history_pos + 1)
164
+ self.input.setPlainText(self.history[-self._history_pos])
165
+ return True
166
+ if control and event.key() == Qt.Key.Key_Down:
167
+ self._history_pos = max(0, self._history_pos - 1)
168
+ self.input.setPlainText(self.history[-self._history_pos] if self._history_pos else "")
169
+ return True
170
+ return super().eventFilter(obj, event)
171
+
172
+ def _execute(self, code: str) -> tuple[str, bool]:
173
+ code = code.strip()
174
+ if not code:
175
+ return "", True
176
+ buffer = io.StringIO()
177
+ self.history.append(code)
178
+ self._history_pos = 0
179
+ self.namespace["project"] = self.project
180
+ ok = True
181
+ try:
182
+ with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(buffer):
183
+ try:
184
+ result = eval(compile(code, "<console>", "eval"), self.namespace)
185
+ except SyntaxError:
186
+ exec(compile(code, "<console>", "exec"), self.namespace)
187
+ result = None
188
+ if result is not None:
189
+ print(repr(result))
190
+ except Exception:
191
+ ok = False
192
+ buffer.write(traceback.format_exc())
193
+ return buffer.getvalue().rstrip(), ok
194
+
195
+ def execute(self, code: str) -> str:
196
+ return self._execute(code)[0]
197
+
198
+ def run_script(self, code: str, table: DataTable | None = None) -> tuple[str, bool]:
199
+ sentinel = object()
200
+ previous_table = self.namespace.get("table", sentinel)
201
+ previous_tables = self.namespace.get("_tables", sentinel)
202
+ self.namespace["_tables"] = {
203
+ item.name: (item if table is not None and item is table else item.copy())
204
+ for item in self.project.tables
205
+ }
206
+ if table is not None:
207
+ self.namespace["table"] = table
208
+ try:
209
+ self.output.appendPlainText(">>> [script]")
210
+ text, ok = self._execute(code)
211
+ if text:
212
+ self.output.appendPlainText(text)
213
+ if ok:
214
+ from statstudio.core.runtime import sync_tables
215
+
216
+ sync_tables(self.project, self.namespace, table)
217
+ return text, ok
218
+ finally:
219
+ if previous_table is sentinel:
220
+ self.namespace.pop("table", None)
221
+ else:
222
+ self.namespace["table"] = previous_table
223
+ if previous_tables is sentinel:
224
+ self.namespace.pop("_tables", None)
225
+ else:
226
+ self.namespace["_tables"] = previous_tables
227
+
228
+ def run_script_with_table(self, code: str, table: DataTable) -> tuple[str, bool]:
229
+ return self.run_script(code, table=table)
230
+
231
+ def run_code(self) -> None:
232
+ code = self.input.toPlainText()
233
+ if not code.strip():
234
+ return
235
+ self.output.appendPlainText(f">>> {code}")
236
+ text, _ok = self._execute(code)
237
+ if text:
238
+ self.output.appendPlainText(text)
239
+ self.input.clear()
File without changes
@@ -0,0 +1,392 @@
1
+ from __future__ import annotations
2
+
3
+ from statstudio.core.table import DataTable
4
+ from statstudio.stats import custom_doe, desirability, distributions, doe, hypothesis, quality, simulator, tolerance
5
+ from statstudio.stats.results import AnalysisResult
6
+ from statstudio.ui.dialogs.base import BaseDialog, combo_value, text_value
7
+ from statstudio.ui.dialogs.stats_dialogs import (
8
+ all_columns,
9
+ first_categorical,
10
+ low_cardinality_columns,
11
+ numeric_columns,
12
+ )
13
+
14
+
15
+ def _optional_float(text: str) -> float | None:
16
+ text = text.strip()
17
+ return float(text) if text else None
18
+
19
+
20
+ class DistributionIDDialog(BaseDialog):
21
+ def __init__(self, table: DataTable, parent=None) -> None:
22
+ super().__init__(table, "Distribution Identification", parent)
23
+ self.column_combo = self.add_combo("Column", numeric_columns(table))
24
+
25
+ def make_job(self):
26
+ df = self.df
27
+ column = combo_value(self.column_combo) or ""
28
+ return lambda token, progress: distributions.distribution_id(df, column)
29
+
30
+ def compute(self) -> AnalysisResult:
31
+ return self.finish(distributions.distribution_id(self.df, combo_value(self.column_combo) or ""))
32
+
33
+
34
+ class ToleranceDialog(BaseDialog):
35
+ def __init__(self, table: DataTable, parent=None) -> None:
36
+ super().__init__(table, "Tolerance Interval", parent)
37
+ self.column_combo = self.add_combo("Column", numeric_columns(table))
38
+ self.coverage_spin = self.add_float("Coverage (%)", 95.0, 50.0, 99.999, 3)
39
+ self.confidence_spin = self.add_float("Confidence (%)", 95.0, 50.0, 99.999, 3)
40
+ self.sided_combo = self.add_combo("Sided", ["Two-sided", "Lower bound", "Upper bound"], default="Two-sided")
41
+ self.method_combo = self.add_combo("Method", ["Normal", "Nonparametric"], default="Normal")
42
+
43
+ def apply_params(self, params: dict | None) -> None:
44
+ params = dict(params or {})
45
+ for key, widget in (("coverage", self.coverage_spin), ("confidence", self.confidence_spin)):
46
+ if params.get(key) is not None:
47
+ widget.setValue(float(params.pop(key)) * 100.0)
48
+ sided = params.pop("sided", None)
49
+ if sided:
50
+ label = {"two-sided": "Two-sided", "lower": "Lower bound", "upper": "Upper bound"}.get(str(sided).lower())
51
+ if label:
52
+ self.sided_combo.setCurrentText(label)
53
+ method = params.pop("method", None)
54
+ if method:
55
+ self.method_combo.setCurrentText(str(method).title())
56
+ super().apply_params(params)
57
+
58
+ def _request(self):
59
+ sided = {"Two-sided": "two-sided", "Lower bound": "lower", "Upper bound": "upper"}.get(combo_value(self.sided_combo) or "Two-sided", "two-sided")
60
+ method = (combo_value(self.method_combo) or "Normal").lower()
61
+ return self.df, combo_value(self.column_combo) or "", self.coverage_spin.value() / 100, self.confidence_spin.value() / 100, sided, method
62
+
63
+ def make_job(self):
64
+ args = self._request()
65
+ return lambda token, progress: tolerance.tolerance_interval(*args)
66
+
67
+ def compute(self) -> AnalysisResult:
68
+ return self.finish(tolerance.tolerance_interval(*self._request()))
69
+
70
+
71
+ class SimulationDialog(BaseDialog):
72
+ def __init__(self, table: DataTable, parent=None) -> None:
73
+ super().__init__(table, "Response Simulation", parent)
74
+ info = doe.design_info(table)
75
+ if info:
76
+ self.add_label(f"Design: {info.get('design_type')} | Factors: {len(info.get('factors', []))}")
77
+ numeric = numeric_columns(table)
78
+ self.response_combo = self.add_combo("Response", numeric or all_columns(table), default=numeric[-1] if numeric else None)
79
+ self.order_combo = self.add_combo("Model order", ["Main effects", "Main + interactions", "Full quadratic"], default="Main + interactions")
80
+ self.simulations_spin = self.add_int("Simulations", 1000, 10, 1_000_000)
81
+ self.noise_edit = self.add_text("Noise standard deviation (blank = RMSE)", "")
82
+ self.distribution_combo = self.add_combo("Noise distribution", ["Normal", "Lognormal", "Uniform"], default="Normal")
83
+ self.lsl_edit = self.add_text("LSL (optional)", "")
84
+ self.usl_edit = self.add_text("USL (optional)", "")
85
+ self.seed_spin = self.add_int("Random seed", 42, 0, 2_000_000_000)
86
+ if info and info.get("design_type") == "Custom":
87
+ self.order_combo.setEnabled(False)
88
+
89
+ def apply_params(self, params: dict | None) -> None:
90
+ params = dict(params or {})
91
+ order = params.pop("order", None)
92
+ if order is not None:
93
+ label = {1: "Main effects", 2: "Main + interactions", 3: "Full quadratic"}.get(int(order))
94
+ if label:
95
+ self.order_combo.setCurrentText(label)
96
+ super().apply_params(params)
97
+
98
+ def _request(self):
99
+ info = doe.design_info(self.table) or {}
100
+ return {
101
+ "table": self.table,
102
+ "custom": info.get("design_type") == "Custom",
103
+ "response": combo_value(self.response_combo) or "",
104
+ "order": {"Main effects": 1, "Main + interactions": 2, "Full quadratic": 3}.get(combo_value(self.order_combo) or "", 2),
105
+ "simulations": self.simulations_spin.value(),
106
+ "noise_sd": _optional_float(text_value(self.noise_edit)),
107
+ "distribution": (combo_value(self.distribution_combo) or "Normal").lower(),
108
+ "lsl": _optional_float(text_value(self.lsl_edit)),
109
+ "usl": _optional_float(text_value(self.usl_edit)),
110
+ "seed": self.seed_spin.value(),
111
+ }
112
+
113
+ @staticmethod
114
+ def _run_request(values):
115
+ if values["custom"]:
116
+ return custom_doe.simulate_response(
117
+ values["table"],
118
+ values["response"],
119
+ simulations=values["simulations"],
120
+ noise_sd=values["noise_sd"],
121
+ distribution=values["distribution"],
122
+ lsl=values["lsl"],
123
+ usl=values["usl"],
124
+ seed=values["seed"],
125
+ )
126
+ return simulator.simulate_response(
127
+ values["table"],
128
+ values["response"],
129
+ values["order"],
130
+ values["simulations"],
131
+ values["noise_sd"],
132
+ values["distribution"],
133
+ values["lsl"],
134
+ values["usl"],
135
+ values["seed"],
136
+ )
137
+
138
+ def make_job(self):
139
+ values = self._request()
140
+ return lambda token, progress: self._run_request(values)
141
+
142
+ def compute(self) -> AnalysisResult:
143
+ return self.finish(self._run_request(self._request()))
144
+
145
+
146
+ class EquivalentTestDialog(BaseDialog):
147
+ def __init__(self, table: DataTable, parent=None) -> None:
148
+ super().__init__(table, "Equivalence Test", parent)
149
+ numeric = numeric_columns(table)
150
+ self.response_combo = self.add_combo("Response", numeric)
151
+ group_default = first_categorical(table) or (low_cardinality_columns(table)[0] if low_cardinality_columns(table) else None)
152
+ self.group_combo = self.add_combo("Group", all_columns(table), allow_none=True, default=group_default)
153
+ self.margin_spin = self.add_float("Equivalence margin", 0.5, 0.0001, 1e9)
154
+ self.alpha_spin = self.add_float("Alpha", 0.05, 0.0001, 0.5, 4)
155
+
156
+ def apply_params(self, params: dict | None) -> None:
157
+ params = dict(params or {})
158
+ if "value" in params:
159
+ params.setdefault("response", params.pop("value"))
160
+ super().apply_params(params)
161
+
162
+ def compute(self) -> AnalysisResult:
163
+ return self.finish(hypothesis.equivalence_test(self.df, combo_value(self.response_combo) or "", combo_value(self.group_combo) or "", self.margin_spin.value(), self.alpha_spin.value()))
164
+
165
+
166
+ class SignTestDialog(BaseDialog):
167
+ def __init__(self, table: DataTable, parent=None) -> None:
168
+ super().__init__(table, "Sign Test", parent)
169
+ self.column_combo = self.add_combo("Column", numeric_columns(table))
170
+ self.median_spin = self.add_float("Hypothesized median", 0.0)
171
+ self.alternative_combo = self.add_combo("Alternative", ["two-sided", "greater", "less"], default="two-sided")
172
+
173
+ def apply_params(self, params: dict | None) -> None:
174
+ params = dict(params or {})
175
+ if params.get("hypothesized_median") is not None:
176
+ self.median_spin.setValue(float(params.pop("hypothesized_median")))
177
+ super().apply_params(params)
178
+
179
+ def compute(self) -> AnalysisResult:
180
+ return self.finish(hypothesis.sign_test(self.df, combo_value(self.column_combo) or "", self.median_spin.value(), combo_value(self.alternative_combo) or "two-sided"))
181
+
182
+
183
+ class WilcoxonOneDialog(BaseDialog):
184
+ def __init__(self, table: DataTable, parent=None) -> None:
185
+ super().__init__(table, "One-Sample Wilcoxon", parent)
186
+ self.column_combo = self.add_combo("Column", numeric_columns(table))
187
+ self.median_spin = self.add_float("Hypothesized median", 0.0)
188
+ self.alternative_combo = self.add_combo("Alternative", ["two-sided", "greater", "less"], default="two-sided")
189
+
190
+ def apply_params(self, params: dict | None) -> None:
191
+ params = dict(params or {})
192
+ if params.get("hypothesized_median") is not None:
193
+ self.median_spin.setValue(float(params.pop("hypothesized_median")))
194
+ super().apply_params(params)
195
+
196
+ def compute(self) -> AnalysisResult:
197
+ return self.finish(hypothesis.one_sample_wilcoxon(self.df, combo_value(self.column_combo) or "", self.median_spin.value(), combo_value(self.alternative_combo) or "two-sided"))
198
+
199
+
200
+ class MoodMedianDialog(BaseDialog):
201
+ def __init__(self, table: DataTable, parent=None) -> None:
202
+ super().__init__(table, "Mood's Median Test", parent)
203
+ numeric = numeric_columns(table)
204
+ self.response_combo = self.add_combo("Response", numeric)
205
+ factor_default = first_categorical(table) or (low_cardinality_columns(table)[0] if low_cardinality_columns(table) else None)
206
+ self.factor_combo = self.add_combo("Factor", all_columns(table), allow_none=True, default=factor_default)
207
+
208
+ def compute(self) -> AnalysisResult:
209
+ return self.finish(hypothesis.mood_median_test(self.df, combo_value(self.response_combo) or "", combo_value(self.factor_combo) or ""))
210
+
211
+
212
+ class FriedmanDialog(BaseDialog):
213
+ def __init__(self, table: DataTable, parent=None) -> None:
214
+ super().__init__(table, "Friedman Test", parent)
215
+ numeric = numeric_columns(table)
216
+ self.columns = self.add_multi("Related columns", numeric, numeric[:3])
217
+
218
+ def compute(self) -> AnalysisResult:
219
+ return self.finish(hypothesis.friedman_test(self.df, self.columns.checked_items()))
220
+
221
+
222
+ class RunsTestDialog(BaseDialog):
223
+ def __init__(self, table: DataTable, parent=None) -> None:
224
+ super().__init__(table, "Runs Test", parent)
225
+ self.column_combo = self.add_combo("Column", numeric_columns(table))
226
+
227
+ def compute(self) -> AnalysisResult:
228
+ return self.finish(hypothesis.runs_test(self.df, combo_value(self.column_combo) or ""))
229
+
230
+
231
+ class ProcessScreeningDialog(BaseDialog):
232
+ def __init__(self, table: DataTable, parent=None) -> None:
233
+ super().__init__(table, "Process Screening", parent)
234
+ numeric = numeric_columns(table)
235
+ self.columns = self.add_multi("Measurements", numeric, numeric[: min(6, len(numeric))])
236
+ self.lsl_edit = self.add_text("Common LSL (optional)", "")
237
+ self.usl_edit = self.add_text("Common USL (optional)", "")
238
+
239
+ def compute(self) -> AnalysisResult:
240
+ return self.finish(quality.process_screening(self.df, self.columns.checked_items(), _optional_float(text_value(self.lsl_edit)), _optional_float(text_value(self.usl_edit))))
241
+
242
+
243
+ class ProfilerDialog(BaseDialog):
244
+ def __init__(self, table: DataTable, parent=None) -> None:
245
+ super().__init__(table, "Prediction Profiler", parent)
246
+ info = doe.design_info(table) or {}
247
+ numeric = numeric_columns(table)
248
+ self.response_combo = self.add_combo("Response", numeric or all_columns(table), default=numeric[-1] if numeric else None)
249
+ self.order_combo = self.add_combo("Model order", ["Main effects", "Main + interactions", "Full quadratic"], default="Main + interactions")
250
+ self.points_spin = self.add_int("Grid points", 9, 3, 51)
251
+ if info and info.get("design_type") == "Custom":
252
+ self.order_combo.setEnabled(False)
253
+
254
+ def apply_params(self, params: dict | None) -> None:
255
+ params = dict(params or {})
256
+ order = params.pop("order", None)
257
+ if order is not None:
258
+ label = {1: "Main effects", 2: "Main + interactions", 3: "Full quadratic"}.get(int(order))
259
+ if label:
260
+ self.order_combo.setCurrentText(label)
261
+ super().apply_params(params)
262
+
263
+ def compute(self) -> AnalysisResult:
264
+ info = doe.design_info(self.table) or {}
265
+ if info.get("design_type") == "Custom":
266
+ return self.finish(
267
+ custom_doe.prediction_profiler(
268
+ self.table,
269
+ combo_value(self.response_combo) or "",
270
+ points=self.points_spin.value(),
271
+ )
272
+ )
273
+ orders = {"Main effects": 1, "Main + interactions": 2, "Full quadratic": 3}
274
+ return self.finish(doe.prediction_profiler(self.table, combo_value(self.response_combo) or "", orders.get(combo_value(self.order_combo) or "", 2), self.points_spin.value()))
275
+
276
+
277
+ class MultiResponseDialog(BaseDialog):
278
+ def __init__(self, table: DataTable, parent=None) -> None:
279
+ super().__init__(table, "Multi-Response Optimization", parent)
280
+ numeric = numeric_columns(table)
281
+ self.responses = self.add_multi("Responses", numeric, numeric[: min(2, len(numeric))])
282
+ self.responses.setMaximumHeight(130)
283
+ self.order_combo = self.add_combo("Model order", ["Main effects", "Main + interactions", "Full quadratic"], default="Main + interactions")
284
+ self.goal_combo = self.add_combo("Goal", ["Maximize", "Minimize", "Target", "Within range"], default="Maximize")
285
+ self.low_edit = self.add_text("Low / lower bound", "")
286
+ self.high_edit = self.add_text("High / upper bound", "")
287
+ self.target_edit = self.add_text("Target (target goal)", "")
288
+ self.weight_spin = self.add_float("Desirability weight", 1.0, 0.0001, 10.0, 3)
289
+ self.importance_spin = self.add_float("Importance", 1.0, 0.0001, 10.0, 3)
290
+ self.starts_spin = self.add_int("Optimization starts", 20, 1, 200)
291
+
292
+ def apply_params(self, params: dict | None) -> None:
293
+ params = dict(params or {})
294
+ order = params.pop("order", None)
295
+ if order is not None:
296
+ label = {1: "Main effects", 2: "Main + interactions", 3: "Full quadratic"}.get(int(order))
297
+ if label:
298
+ self.order_combo.setCurrentText(label)
299
+ responses = params.pop("responses", None)
300
+ if responses:
301
+ self.responses.set_checked(responses)
302
+ goals = params.pop("goals", None) or {}
303
+ if goals:
304
+ first = next(iter(goals.values()))
305
+ goal = str(first.get("goal", "maximize")).title()
306
+ self.goal_combo.setCurrentText(goal if goal in {"Maximize", "Minimize", "Target"} else "Within range")
307
+ if first.get("low") is not None:
308
+ self.low_edit.setText(str(first["low"]))
309
+ if first.get("high") is not None:
310
+ self.high_edit.setText(str(first["high"]))
311
+ if first.get("target") is not None:
312
+ self.target_edit.setText(str(first["target"]))
313
+ if first.get("weight") is not None:
314
+ self.weight_spin.setValue(float(first["weight"]))
315
+ if first.get("importance") is not None:
316
+ self.importance_spin.setValue(float(first["importance"]))
317
+ super().apply_params(params)
318
+
319
+ def make_job(self):
320
+ info = doe.design_info(self.table) or {}
321
+ if info.get("design_type") == "Custom":
322
+ raise ValueError(
323
+ "Multi-response optimization for custom designs is not yet available. "
324
+ "Use the custom Prediction Profiler with response goals."
325
+ )
326
+ responses = self.responses.checked_items()
327
+ if not responses:
328
+ raise ValueError("Choose at least one response.")
329
+ orders = {"Main effects": 1, "Main + interactions": 2, "Full quadratic": 3}
330
+ order = orders.get(combo_value(self.order_combo) or "", 2)
331
+ goal = (combo_value(self.goal_combo) or "Maximize").lower()
332
+ table = self.table
333
+ goals = {
334
+ response: {
335
+ "goal": goal,
336
+ "low": _optional_float(text_value(self.low_edit)),
337
+ "high": _optional_float(text_value(self.high_edit)),
338
+ "target": _optional_float(text_value(self.target_edit)),
339
+ "weight": self.weight_spin.value(),
340
+ "importance": self.importance_spin.value(),
341
+ }
342
+ for response in responses
343
+ }
344
+ starts = self.starts_spin.value()
345
+
346
+ def run(token, progress):
347
+ models = {}
348
+ for response in responses:
349
+ model, factors, _ = doe.fit_design_model(table, response, order)
350
+ models[response] = model
351
+ _, factors, _ = doe.fit_design_model(table, responses[0], order)
352
+ return desirability.multi_response_optimize(models, factors, goals, ", ".join(responses), starts, order=order)
353
+
354
+ return run
355
+
356
+ def compute(self) -> AnalysisResult:
357
+ info = doe.design_info(self.table) or {}
358
+ if info.get("design_type") == "Custom":
359
+ raise ValueError(
360
+ "Multi-response optimization for custom designs is not yet available. "
361
+ "Use the custom Prediction Profiler with response goals."
362
+ )
363
+ responses = self.responses.checked_items()
364
+ if not responses:
365
+ raise ValueError("Choose at least one response.")
366
+ orders = {"Main effects": 1, "Main + interactions": 2, "Full quadratic": 3}
367
+ order = orders.get(combo_value(self.order_combo) or "", 2)
368
+ models = {}
369
+ goals = {}
370
+ goal = (combo_value(self.goal_combo) or "Maximize").lower()
371
+ for response in responses:
372
+ model, factors, _ = doe.fit_design_model(self.table, response, order)
373
+ models[response] = model
374
+ goals[response] = {
375
+ "goal": goal,
376
+ "low": _optional_float(text_value(self.low_edit)),
377
+ "high": _optional_float(text_value(self.high_edit)),
378
+ "target": _optional_float(text_value(self.target_edit)),
379
+ "weight": self.weight_spin.value(),
380
+ "importance": self.importance_spin.value(),
381
+ }
382
+ _, factors, _ = doe.fit_design_model(self.table, responses[0], order)
383
+ return self.finish(
384
+ desirability.multi_response_optimize(
385
+ models,
386
+ factors,
387
+ goals,
388
+ ", ".join(responses),
389
+ self.starts_spin.value(),
390
+ order=order,
391
+ )
392
+ )