statstudio 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1688 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from PySide6.QtCore import Qt
|
|
6
|
+
from PySide6.QtWidgets import QAbstractItemView, QTableWidget, QTableWidgetItem
|
|
7
|
+
|
|
8
|
+
from statstudio.core.table import DataTable
|
|
9
|
+
from statstudio.stats import (
|
|
10
|
+
correlation,
|
|
11
|
+
custom_doe,
|
|
12
|
+
optimal_doe,
|
|
13
|
+
descriptive,
|
|
14
|
+
distributions,
|
|
15
|
+
doe,
|
|
16
|
+
hypothesis,
|
|
17
|
+
multivariate,
|
|
18
|
+
power,
|
|
19
|
+
quality,
|
|
20
|
+
regression,
|
|
21
|
+
survival,
|
|
22
|
+
timeseries,
|
|
23
|
+
)
|
|
24
|
+
from statstudio.stats.results import AnalysisResult
|
|
25
|
+
from statstudio.ui.dialogs.base import BaseDialog, combo_value, text_value
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
REGRESSION_MODELS = ["Linear", "Logistic", "GLM", "Polynomial", "Mixed", "GEE", "Stepwise"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def numeric_columns(table: DataTable) -> list[str]:
|
|
32
|
+
result = []
|
|
33
|
+
for column in table.columns:
|
|
34
|
+
spec = table.specs.get(column)
|
|
35
|
+
if spec is not None and spec.modeling_type in {"nominal", "ordinal"}:
|
|
36
|
+
continue
|
|
37
|
+
if pd.api.types.is_numeric_dtype(table.data[column]):
|
|
38
|
+
result.append(column)
|
|
39
|
+
return result
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def all_columns(table: DataTable) -> list[str]:
|
|
43
|
+
return list(table.columns)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def categorical_columns(table: DataTable) -> list[str]:
|
|
47
|
+
numeric = set(numeric_columns(table))
|
|
48
|
+
return [c for c in table.columns if c not in numeric]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def first_categorical(table: DataTable, exclude: list[str] | None = None) -> str | None:
|
|
52
|
+
exclude = set(exclude or [])
|
|
53
|
+
for column in categorical_columns(table):
|
|
54
|
+
if column not in exclude:
|
|
55
|
+
return column
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def low_cardinality_columns(table: DataTable, max_levels: int = 15, min_levels: int = 2) -> list[str]:
|
|
60
|
+
result = []
|
|
61
|
+
for column in table.columns:
|
|
62
|
+
try:
|
|
63
|
+
levels = table.data[column].nunique(dropna=True)
|
|
64
|
+
except Exception:
|
|
65
|
+
continue
|
|
66
|
+
if min_levels <= levels <= max_levels:
|
|
67
|
+
result.append(column)
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def preferred_categorical(table: DataTable) -> str | None:
|
|
72
|
+
low = low_cardinality_columns(table)
|
|
73
|
+
if low:
|
|
74
|
+
return low[0]
|
|
75
|
+
return first_categorical(table)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def binary_columns(table: DataTable) -> list[str]:
|
|
79
|
+
result = []
|
|
80
|
+
for column in table.columns:
|
|
81
|
+
try:
|
|
82
|
+
if 1 < table.data[column].nunique(dropna=True) <= 2:
|
|
83
|
+
result.append(column)
|
|
84
|
+
except Exception:
|
|
85
|
+
continue
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class DescriptiveDialog(BaseDialog):
|
|
90
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
91
|
+
super().__init__(table, "Descriptive Statistics", parent)
|
|
92
|
+
numeric = numeric_columns(table)
|
|
93
|
+
self.variables = self.add_multi("Variables", numeric, numeric[: min(4, len(numeric))])
|
|
94
|
+
self.group_combo = self.add_combo("Group by", all_columns(table), allow_none=True)
|
|
95
|
+
self.weight_combo = self.add_combo("Weight column", all_columns(table), allow_none=True)
|
|
96
|
+
self.freq_combo = self.add_combo("Frequency column", all_columns(table), allow_none=True)
|
|
97
|
+
|
|
98
|
+
def apply_params(self, params: dict | None) -> None:
|
|
99
|
+
params = dict(params or {})
|
|
100
|
+
columns = params.pop("columns", None)
|
|
101
|
+
if columns:
|
|
102
|
+
self.variables.check_all(False)
|
|
103
|
+
selected = {str(column) for column in columns}
|
|
104
|
+
for index in range(self.variables.count()):
|
|
105
|
+
item = self.variables.item(index)
|
|
106
|
+
if item.text() in selected:
|
|
107
|
+
item.setCheckState(Qt.CheckState.Checked)
|
|
108
|
+
super().apply_params(params)
|
|
109
|
+
|
|
110
|
+
def compute(self) -> AnalysisResult:
|
|
111
|
+
return self.finish(
|
|
112
|
+
descriptive.describe(
|
|
113
|
+
self.df,
|
|
114
|
+
self.variables.checked_items(),
|
|
115
|
+
combo_value(self.group_combo),
|
|
116
|
+
combo_value(self.weight_combo),
|
|
117
|
+
combo_value(self.freq_combo),
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class DistributionDialog(BaseDialog):
|
|
123
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
124
|
+
super().__init__(table, "Distribution Fit", parent)
|
|
125
|
+
self.column_combo = self.add_combo("Column", numeric_columns(table))
|
|
126
|
+
keys = list(distributions.DISTRIBUTIONS.keys())
|
|
127
|
+
self.distribution_combo = self.add_combo(
|
|
128
|
+
"Distribution",
|
|
129
|
+
[distributions.DISTRIBUTIONS[key] for key in keys],
|
|
130
|
+
default="Normal",
|
|
131
|
+
)
|
|
132
|
+
self._keys = keys
|
|
133
|
+
|
|
134
|
+
def apply_params(self, params: dict | None) -> None:
|
|
135
|
+
super().apply_params(params)
|
|
136
|
+
params = params or {}
|
|
137
|
+
column = params.get("column")
|
|
138
|
+
if column:
|
|
139
|
+
index = self.column_combo.findData(column)
|
|
140
|
+
if index >= 0:
|
|
141
|
+
self.column_combo.setCurrentIndex(index)
|
|
142
|
+
distribution = params.get("distribution")
|
|
143
|
+
if distribution:
|
|
144
|
+
label = distributions.DISTRIBUTIONS.get(distribution)
|
|
145
|
+
if label:
|
|
146
|
+
self.distribution_combo.setCurrentText(label)
|
|
147
|
+
|
|
148
|
+
def compute(self) -> AnalysisResult:
|
|
149
|
+
index = self.distribution_combo.currentIndex()
|
|
150
|
+
key = self._keys[index] if 0 <= index < len(self._keys) else "normal"
|
|
151
|
+
return self.finish(distributions.fit_distribution(self.df, combo_value(self.column_combo) or "", key))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class FrequencyDialog(BaseDialog):
|
|
155
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
156
|
+
super().__init__(table, "Frequency Distribution", parent)
|
|
157
|
+
self.column_combo = self.add_combo("Column", all_columns(table), default=first_categorical(table) or table.columns[0])
|
|
158
|
+
|
|
159
|
+
def compute(self) -> AnalysisResult:
|
|
160
|
+
return self.finish(descriptive.frequency_table(self.df, combo_value(self.column_combo) or ""))
|
|
161
|
+
|
|
162
|
+
def finish(self, result):
|
|
163
|
+
result.source_table = self.table.name
|
|
164
|
+
return result
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class GroupSummaryDialog(BaseDialog):
|
|
168
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
169
|
+
super().__init__(table, "Grouped Summary", parent)
|
|
170
|
+
numeric = numeric_columns(table)
|
|
171
|
+
self.response_combo = self.add_combo("Response", numeric, default=numeric[0] if numeric else None)
|
|
172
|
+
self.group_combo = self.add_combo("Group", all_columns(table), default=first_categorical(table) or table.columns[0])
|
|
173
|
+
self.aggregate_combo = self.add_combo("Aggregate", ["mean", "sum", "median", "count"], default="mean")
|
|
174
|
+
|
|
175
|
+
def compute(self) -> AnalysisResult:
|
|
176
|
+
return self.finish(
|
|
177
|
+
descriptive.grouped_summary(
|
|
178
|
+
self.df,
|
|
179
|
+
combo_value(self.response_combo) or "",
|
|
180
|
+
combo_value(self.group_combo) or "",
|
|
181
|
+
combo_value(self.aggregate_combo) or "mean",
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class TTestDialog(BaseDialog):
|
|
187
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
188
|
+
super().__init__(table, "t Test", parent)
|
|
189
|
+
numeric = numeric_columns(table)
|
|
190
|
+
has_categorical = first_categorical(table) is not None
|
|
191
|
+
default_mode = "Two sample" if has_categorical else ("Paired" if len(numeric) > 1 else "One sample")
|
|
192
|
+
self.mode_combo = self.add_combo("Test", ["One sample", "Two sample", "Paired"], default=default_mode)
|
|
193
|
+
self.value_combo = self.add_combo("Value / first column", numeric, default=numeric[0] if numeric else None)
|
|
194
|
+
self.group_combo = self.add_combo("Group column (two sample)", all_columns(table), allow_none=True, default=first_categorical(table))
|
|
195
|
+
self.second_combo = self.add_combo("Second column (paired)", all_columns(table), allow_none=True, default=numeric[1] if len(numeric) > 1 else None)
|
|
196
|
+
self.mu_spin = self.add_float("Hypothesized mean", 0.0)
|
|
197
|
+
self.equal_var_check = self.add_bool("Assume equal variances", False)
|
|
198
|
+
self.alternative_combo = self.add_combo("Alternative", ["two-sided", "greater", "less"], default="two-sided")
|
|
199
|
+
self.mode_combo.currentTextChanged.connect(self._sync_mode_controls)
|
|
200
|
+
self._sync_mode_controls()
|
|
201
|
+
|
|
202
|
+
def _sync_mode_controls(self, *_args) -> None:
|
|
203
|
+
mode = combo_value(self.mode_combo) or "One sample"
|
|
204
|
+
one_sample = mode == "One sample"
|
|
205
|
+
two_sample = mode == "Two sample"
|
|
206
|
+
paired = mode == "Paired"
|
|
207
|
+
self._form.setRowVisible(self.mu_spin, one_sample)
|
|
208
|
+
self._form.setRowVisible(self.group_combo, two_sample)
|
|
209
|
+
self._form.setRowVisible(self.second_combo, paired)
|
|
210
|
+
self._form.setRowVisible(self.equal_var_check, two_sample)
|
|
211
|
+
|
|
212
|
+
def apply_params(self, params: dict | None) -> None:
|
|
213
|
+
super().apply_params(params)
|
|
214
|
+
params = params or {}
|
|
215
|
+
if "mu" in params:
|
|
216
|
+
self.mode_combo.setCurrentText("One sample")
|
|
217
|
+
elif "group" in params:
|
|
218
|
+
self.mode_combo.setCurrentText("Two sample")
|
|
219
|
+
elif "column1" in params or "column2" in params:
|
|
220
|
+
self.mode_combo.setCurrentText("Paired")
|
|
221
|
+
value = params.get("column") or params.get("value") or params.get("column1")
|
|
222
|
+
if value:
|
|
223
|
+
index = self.value_combo.findData(value)
|
|
224
|
+
if index >= 0:
|
|
225
|
+
self.value_combo.setCurrentIndex(index)
|
|
226
|
+
group = params.get("group")
|
|
227
|
+
if group:
|
|
228
|
+
index = self.group_combo.findData(group)
|
|
229
|
+
if index >= 0:
|
|
230
|
+
self.group_combo.setCurrentIndex(index)
|
|
231
|
+
second = params.get("column2")
|
|
232
|
+
if second:
|
|
233
|
+
index = self.second_combo.findData(second)
|
|
234
|
+
if index >= 0:
|
|
235
|
+
self.second_combo.setCurrentIndex(index)
|
|
236
|
+
if "mu" in params:
|
|
237
|
+
self.mu_spin.setValue(float(params["mu"]))
|
|
238
|
+
if params.get("alternative"):
|
|
239
|
+
self.alternative_combo.setCurrentText(str(params["alternative"]))
|
|
240
|
+
if "equal_var" in params:
|
|
241
|
+
self.equal_var_check.setChecked(bool(params["equal_var"]))
|
|
242
|
+
self._sync_mode_controls()
|
|
243
|
+
|
|
244
|
+
def compute(self) -> AnalysisResult:
|
|
245
|
+
mode = combo_value(self.mode_combo)
|
|
246
|
+
value = combo_value(self.value_combo) or ""
|
|
247
|
+
alternative = combo_value(self.alternative_combo) or "two-sided"
|
|
248
|
+
if mode == "One sample":
|
|
249
|
+
result = hypothesis.one_sample_t_test(self.df, value, self.mu_spin.value(), alternative)
|
|
250
|
+
elif mode == "Two sample":
|
|
251
|
+
group = combo_value(self.group_combo)
|
|
252
|
+
if not group:
|
|
253
|
+
raise ValueError("Choose a group column for a two-sample test.")
|
|
254
|
+
result = hypothesis.two_sample_t_test(self.df, value, group, self.equal_var_check.isChecked(), alternative)
|
|
255
|
+
elif mode == "Paired":
|
|
256
|
+
second = combo_value(self.second_combo)
|
|
257
|
+
if not second:
|
|
258
|
+
raise ValueError("Choose the second column for a paired test.")
|
|
259
|
+
result = hypothesis.paired_t_test(self.df, value, second, alternative)
|
|
260
|
+
else:
|
|
261
|
+
raise ValueError("Unknown test.")
|
|
262
|
+
return self.finish(result)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class ANOVADialog(BaseDialog):
|
|
266
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
267
|
+
super().__init__(table, "Analysis of Variance", parent)
|
|
268
|
+
numeric = numeric_columns(table)
|
|
269
|
+
self.response_combo = self.add_combo("Response", numeric, default=numeric[0] if numeric else None)
|
|
270
|
+
self.factor_combo = self.add_combo("Factor", all_columns(table), default=first_categorical(table))
|
|
271
|
+
self.test_combo = self.add_combo("Test", ["One-way ANOVA", "Kruskal-Wallis"], default="One-way ANOVA")
|
|
272
|
+
self.tukey_letters_check = self.add_bool("Tukey HSD grouping letters", True)
|
|
273
|
+
self.alpha_spin = self.add_float("Tukey alpha", 0.05, 0.0001, 0.9999, 4)
|
|
274
|
+
self.test_combo.currentTextChanged.connect(self._sync_test_controls)
|
|
275
|
+
self._sync_test_controls()
|
|
276
|
+
|
|
277
|
+
def _sync_test_controls(self, *_args) -> None:
|
|
278
|
+
show_tukey = combo_value(self.test_combo) == "One-way ANOVA"
|
|
279
|
+
self._form.setRowVisible(self.tukey_letters_check, show_tukey)
|
|
280
|
+
self._form.setRowVisible(self.alpha_spin, show_tukey)
|
|
281
|
+
|
|
282
|
+
def apply_kind(self, kind: str) -> None:
|
|
283
|
+
if kind == "kruskal":
|
|
284
|
+
self.test_combo.setCurrentText("Kruskal-Wallis")
|
|
285
|
+
elif kind in {"anova", "one_way_anova"}:
|
|
286
|
+
self.test_combo.setCurrentText("One-way ANOVA")
|
|
287
|
+
self._sync_test_controls()
|
|
288
|
+
|
|
289
|
+
def compute(self) -> AnalysisResult:
|
|
290
|
+
response = combo_value(self.response_combo) or ""
|
|
291
|
+
factor = combo_value(self.factor_combo) or ""
|
|
292
|
+
if not response or not factor or response == factor:
|
|
293
|
+
raise ValueError("Choose distinct numeric response and categorical factor columns.")
|
|
294
|
+
if combo_value(self.test_combo) == "Kruskal-Wallis":
|
|
295
|
+
result = hypothesis.kruskal_test(self.df, response, factor)
|
|
296
|
+
else:
|
|
297
|
+
result = hypothesis.anova_oneway(
|
|
298
|
+
self.df,
|
|
299
|
+
response,
|
|
300
|
+
factor,
|
|
301
|
+
tukey_letters=self.tukey_letters_check.isChecked(),
|
|
302
|
+
alpha=self.alpha_spin.value(),
|
|
303
|
+
)
|
|
304
|
+
return self.finish(result)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class MannWhitneyDialog(BaseDialog):
|
|
308
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
309
|
+
super().__init__(table, "Mann-Whitney Test", parent)
|
|
310
|
+
numeric = numeric_columns(table)
|
|
311
|
+
self.value_combo = self.add_combo("Value", numeric, default=numeric[0] if numeric else None)
|
|
312
|
+
group_default = first_categorical(table) or (low_cardinality_columns(table)[0] if low_cardinality_columns(table) else None)
|
|
313
|
+
self.group_combo = self.add_combo("Group", all_columns(table), allow_none=True, default=group_default)
|
|
314
|
+
self.alternative_combo = self.add_combo("Alternative", ["two-sided", "greater", "less"], default="two-sided")
|
|
315
|
+
|
|
316
|
+
def compute(self) -> AnalysisResult:
|
|
317
|
+
return self.finish(
|
|
318
|
+
hypothesis.mann_whitney_test(
|
|
319
|
+
self.df,
|
|
320
|
+
combo_value(self.value_combo) or "",
|
|
321
|
+
combo_value(self.group_combo) or "",
|
|
322
|
+
combo_value(self.alternative_combo) or "two-sided",
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class WilcoxonDialog(BaseDialog):
|
|
328
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
329
|
+
super().__init__(table, "Wilcoxon Signed-Rank Test", parent)
|
|
330
|
+
numeric = numeric_columns(table)
|
|
331
|
+
self.first_combo = self.add_combo("First column", numeric)
|
|
332
|
+
self.second_combo = self.add_combo("Second column", numeric, default=numeric[1] if len(numeric) > 1 else None)
|
|
333
|
+
self.alternative_combo = self.add_combo("Alternative", ["two-sided", "greater", "less"], default="two-sided")
|
|
334
|
+
|
|
335
|
+
def compute(self) -> AnalysisResult:
|
|
336
|
+
first = combo_value(self.first_combo) or ""
|
|
337
|
+
second = combo_value(self.second_combo) or ""
|
|
338
|
+
if not first or not second:
|
|
339
|
+
raise ValueError("Choose two numeric columns.")
|
|
340
|
+
if first == second:
|
|
341
|
+
raise ValueError("Choose two different columns for the signed-rank test.")
|
|
342
|
+
return self.finish(
|
|
343
|
+
hypothesis.wilcoxon_test(
|
|
344
|
+
self.df,
|
|
345
|
+
first,
|
|
346
|
+
second,
|
|
347
|
+
combo_value(self.alternative_combo) or "two-sided",
|
|
348
|
+
)
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
def apply_params(self, params: dict | None) -> None:
|
|
352
|
+
super().apply_params(params)
|
|
353
|
+
params = params or {}
|
|
354
|
+
for key, widget in (("column1", self.first_combo), ("column2", self.second_combo)):
|
|
355
|
+
value = params.get(key)
|
|
356
|
+
if value is None:
|
|
357
|
+
continue
|
|
358
|
+
index = widget.findData(value)
|
|
359
|
+
if index < 0:
|
|
360
|
+
index = widget.findText(str(value))
|
|
361
|
+
if index >= 0:
|
|
362
|
+
widget.setCurrentIndex(index)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class ChiSquareDialog(BaseDialog):
|
|
366
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
367
|
+
super().__init__(table, "Chi-Square Test", parent)
|
|
368
|
+
categorical = categorical_columns(table)
|
|
369
|
+
self.row_combo = self.add_combo("Row variable", all_columns(table), default=categorical[0] if categorical else None)
|
|
370
|
+
self.column_combo = self.add_combo("Column variable", all_columns(table), default=categorical[1] if len(categorical) > 1 else None)
|
|
371
|
+
if len(categorical) < 2:
|
|
372
|
+
self.column_combo.setCurrentIndex(-1)
|
|
373
|
+
|
|
374
|
+
def compute(self) -> AnalysisResult:
|
|
375
|
+
column = combo_value(self.column_combo)
|
|
376
|
+
if not column:
|
|
377
|
+
raise ValueError("Choose a second (column) variable.")
|
|
378
|
+
return self.finish(
|
|
379
|
+
hypothesis.chi_square_test(
|
|
380
|
+
self.df,
|
|
381
|
+
combo_value(self.row_combo) or "",
|
|
382
|
+
column,
|
|
383
|
+
)
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class ProportionDialog(BaseDialog):
|
|
388
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
389
|
+
super().__init__(table, "Proportion Test", parent)
|
|
390
|
+
self.column_combo = self.add_combo("Column", all_columns(table), default=first_categorical(table) or table.columns[0])
|
|
391
|
+
self.success_edit = self.add_text("Success value", "")
|
|
392
|
+
self.null_spin = self.add_float("Null proportion", 0.5, 0.0001, 0.9999, 4)
|
|
393
|
+
self.group_combo = self.add_combo("Group (optional)", all_columns(table), allow_none=True)
|
|
394
|
+
|
|
395
|
+
def compute(self) -> AnalysisResult:
|
|
396
|
+
success = text_value(self.success_edit)
|
|
397
|
+
if not success:
|
|
398
|
+
raise ValueError("Enter the success value.")
|
|
399
|
+
return self.finish(
|
|
400
|
+
hypothesis.proportion_test(
|
|
401
|
+
self.df,
|
|
402
|
+
combo_value(self.column_combo) or "",
|
|
403
|
+
success,
|
|
404
|
+
self.null_spin.value(),
|
|
405
|
+
combo_value(self.group_combo),
|
|
406
|
+
)
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
def apply_params(self, params: dict | None) -> None:
|
|
410
|
+
super().apply_params(params)
|
|
411
|
+
value = (params or {}).get("null_proportion")
|
|
412
|
+
if value is not None:
|
|
413
|
+
self.null_spin.setValue(float(value))
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
class NormalityDialog(BaseDialog):
|
|
417
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
418
|
+
super().__init__(table, "Normality Test", parent)
|
|
419
|
+
self.column_combo = self.add_combo("Column", numeric_columns(table))
|
|
420
|
+
|
|
421
|
+
def compute(self) -> AnalysisResult:
|
|
422
|
+
return self.finish(hypothesis.normality_test(self.df, combo_value(self.column_combo) or ""))
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class CorrelationDialog(BaseDialog):
|
|
426
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
427
|
+
super().__init__(table, "Correlation", parent)
|
|
428
|
+
numeric = numeric_columns(table)
|
|
429
|
+
self.columns = self.add_multi("Variables", numeric, numeric[: min(4, len(numeric))])
|
|
430
|
+
self.method_combo = self.add_combo("Method", ["pearson", "spearman", "kendall"], default="pearson")
|
|
431
|
+
self.covariance_check = self.add_bool("Also show covariance matrix", False)
|
|
432
|
+
|
|
433
|
+
def apply_params(self, params: dict | None) -> None:
|
|
434
|
+
params = dict(params or {})
|
|
435
|
+
if params.get("covariance") is not None:
|
|
436
|
+
self.covariance_check.setChecked(bool(params.pop("covariance")))
|
|
437
|
+
super().apply_params(params)
|
|
438
|
+
|
|
439
|
+
def compute(self) -> AnalysisResult:
|
|
440
|
+
result = correlation.correlation_matrix(
|
|
441
|
+
self.df,
|
|
442
|
+
self.columns.checked_items(),
|
|
443
|
+
combo_value(self.method_combo) or "pearson",
|
|
444
|
+
covariance=self.covariance_check.isChecked(),
|
|
445
|
+
)
|
|
446
|
+
return self.finish(result)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class CovarianceDialog(BaseDialog):
|
|
450
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
451
|
+
super().__init__(table, "Covariance", parent)
|
|
452
|
+
numeric = numeric_columns(table)
|
|
453
|
+
self.columns = self.add_multi("Variables", numeric, numeric[: min(4, len(numeric))])
|
|
454
|
+
|
|
455
|
+
def compute(self) -> AnalysisResult:
|
|
456
|
+
return self.finish(correlation.covariance_matrix(self.df, self.columns.checked_items()))
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class RegressionDialog(BaseDialog):
|
|
460
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
461
|
+
super().__init__(table, "Multi Linear", parent)
|
|
462
|
+
self.type_combo = self.add_combo(
|
|
463
|
+
"Model",
|
|
464
|
+
REGRESSION_MODELS,
|
|
465
|
+
default="Linear",
|
|
466
|
+
)
|
|
467
|
+
numeric = numeric_columns(table)
|
|
468
|
+
default_response = numeric[-1] if numeric else (table.columns[-1] if table.columns else None)
|
|
469
|
+
self.response_combo = self.add_combo("Response", all_columns(table), default=default_response)
|
|
470
|
+
predictors_default = [c for c in numeric if c != default_response][:3]
|
|
471
|
+
if not predictors_default:
|
|
472
|
+
predictors_default = [c for c in all_columns(table) if c != default_response][:3]
|
|
473
|
+
self.predictors = self.add_multi("Predictors", all_columns(table), predictors_default)
|
|
474
|
+
self.interactions_check = self.add_bool("Include two-way interactions", False)
|
|
475
|
+
self.add_page("Advanced")
|
|
476
|
+
self.robust_check = self.add_bool("Robust standard errors (HC3, linear only)", False)
|
|
477
|
+
self.degree_spin = self.add_int("Polynomial degree", 2, 1, 8)
|
|
478
|
+
self.family_combo = self.add_combo("GLM family", ["gaussian", "binomial", "poisson", "gamma", "inverse_gaussian", "negative_binomial"], default="gaussian")
|
|
479
|
+
self.link_combo = self.add_combo("GLM link", ["default", "identity", "log", "logit", "probit", "inverse", "sqrt", "cloglog"], default="default")
|
|
480
|
+
self.correlation_combo = self.add_combo("GEE correlation", ["exchangeable", "independence", "ar", "stationary"], default="exchangeable")
|
|
481
|
+
self.gee_compare_check = self.add_bool("Compare GEE correlation structures", False)
|
|
482
|
+
self.test_size_spin = self.add_float("Holdout fraction", 0.0, 0.0, 0.5, 2)
|
|
483
|
+
self.weight_combo = self.add_combo("Weight column (linear)", all_columns(table), allow_none=True)
|
|
484
|
+
self.group_combo = self.add_combo("Mixed model group", all_columns(table), allow_none=True, default=preferred_categorical(table))
|
|
485
|
+
self.random_slope_combo = self.add_combo("Random slope (optional)", all_columns(table), allow_none=True)
|
|
486
|
+
self.threshold_spin = self.add_float("Stepwise p threshold", 0.05, 0.0001, 0.9999, 4)
|
|
487
|
+
|
|
488
|
+
def apply_kind(self, kind: str) -> None:
|
|
489
|
+
label = {
|
|
490
|
+
"linear_regression": "Linear",
|
|
491
|
+
"regression": "Linear",
|
|
492
|
+
"logistic_regression": "Logistic",
|
|
493
|
+
"glm": "GLM",
|
|
494
|
+
"polynomial_regression": "Polynomial",
|
|
495
|
+
"mixed_model": "Mixed",
|
|
496
|
+
"gee": "GEE",
|
|
497
|
+
"stepwise_regression": "Stepwise",
|
|
498
|
+
"poisson_regression": "GLM",
|
|
499
|
+
"negative_binomial_regression": "GLM",
|
|
500
|
+
}.get(kind)
|
|
501
|
+
if label:
|
|
502
|
+
self.type_combo.setCurrentText(label)
|
|
503
|
+
|
|
504
|
+
def apply_params(self, params: dict | None) -> None:
|
|
505
|
+
params = dict(params or {})
|
|
506
|
+
if params.get("compare_structures") is not None:
|
|
507
|
+
params.setdefault("gee_compare", params["compare_structures"])
|
|
508
|
+
super().apply_params(params)
|
|
509
|
+
|
|
510
|
+
def _request(self):
|
|
511
|
+
model_type = combo_value(self.type_combo)
|
|
512
|
+
response = combo_value(self.response_combo) or ""
|
|
513
|
+
predictors = [p for p in self.predictors.checked_items() if p != response]
|
|
514
|
+
if not predictors:
|
|
515
|
+
raise ValueError("Choose at least one predictor.")
|
|
516
|
+
return {
|
|
517
|
+
"df": self.df,
|
|
518
|
+
"model_type": model_type,
|
|
519
|
+
"response": response,
|
|
520
|
+
"predictors": predictors,
|
|
521
|
+
"interactions": self.interactions_check.isChecked(),
|
|
522
|
+
"robust": self.robust_check.isChecked(),
|
|
523
|
+
"weight": combo_value(self.weight_combo),
|
|
524
|
+
"test_size": self.test_size_spin.value(),
|
|
525
|
+
"link": combo_value(self.link_combo),
|
|
526
|
+
"family": combo_value(self.family_combo) or "gaussian",
|
|
527
|
+
"degree": self.degree_spin.value(),
|
|
528
|
+
"group": combo_value(self.group_combo),
|
|
529
|
+
"random_slope": combo_value(self.random_slope_combo),
|
|
530
|
+
"correlation": combo_value(self.correlation_combo) or "exchangeable",
|
|
531
|
+
"compare_structures": self.gee_compare_check.isChecked(),
|
|
532
|
+
"threshold": self.threshold_spin.value(),
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
@staticmethod
|
|
536
|
+
def _run_request(values):
|
|
537
|
+
df = values["df"]
|
|
538
|
+
model_type = values["model_type"]
|
|
539
|
+
response = values["response"]
|
|
540
|
+
predictors = values["predictors"]
|
|
541
|
+
if model_type == "Linear":
|
|
542
|
+
return regression.linear_regression(df, response, predictors, values["interactions"], values["robust"], values["weight"], values["test_size"])
|
|
543
|
+
if model_type == "Logistic":
|
|
544
|
+
return regression.logistic_regression(df, response, predictors, values["interactions"])
|
|
545
|
+
if model_type == "GLM":
|
|
546
|
+
link = values["link"]
|
|
547
|
+
return regression.glm_regression(df, response, predictors, values["family"], values["interactions"], None if link == "default" else link, values["test_size"])
|
|
548
|
+
if model_type == "Polynomial":
|
|
549
|
+
if len(predictors) != 1:
|
|
550
|
+
raise ValueError("Polynomial regression uses exactly one predictor.")
|
|
551
|
+
return regression.polynomial_regression(df, response, predictors[0], values["degree"])
|
|
552
|
+
if model_type == "Mixed":
|
|
553
|
+
group = values["group"]
|
|
554
|
+
if not group:
|
|
555
|
+
raise ValueError("Choose a group column for a mixed model.")
|
|
556
|
+
return regression.mixed_model(df, response, predictors, group, values["random_slope"])
|
|
557
|
+
if model_type == "GEE":
|
|
558
|
+
group = values["group"]
|
|
559
|
+
if not group:
|
|
560
|
+
raise ValueError("Choose a group column for GEE.")
|
|
561
|
+
return regression.gee_regression(df, response, predictors, group, values["correlation"], values["family"], values["compare_structures"])
|
|
562
|
+
if model_type == "Stepwise":
|
|
563
|
+
return regression.stepwise_regression(df, response, predictors, "pvalue", values["threshold"])
|
|
564
|
+
raise ValueError("Unknown regression model.")
|
|
565
|
+
|
|
566
|
+
def make_job(self):
|
|
567
|
+
values = self._request()
|
|
568
|
+
return lambda token, progress: self._run_request(values)
|
|
569
|
+
|
|
570
|
+
def compute(self) -> AnalysisResult:
|
|
571
|
+
return self.finish(self._run_request(self._request()))
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
class RegressionProfilerDialog(RegressionDialog):
|
|
575
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
576
|
+
super().__init__(table, parent)
|
|
577
|
+
self.setWindowTitle("Prediction Profiler")
|
|
578
|
+
self.add_page("Profiler")
|
|
579
|
+
self.points_spin = self.add_int("Grid points", 9, 3, 51)
|
|
580
|
+
|
|
581
|
+
def apply_kind(self, kind: str) -> None:
|
|
582
|
+
if kind == "regression_prediction_profiler":
|
|
583
|
+
return
|
|
584
|
+
super().apply_kind(kind)
|
|
585
|
+
|
|
586
|
+
def apply_params(self, params: dict | None = None) -> None:
|
|
587
|
+
model_type = (params or {}).get("model_type")
|
|
588
|
+
if model_type:
|
|
589
|
+
self.type_combo.setCurrentText(str(model_type))
|
|
590
|
+
super().apply_params(params)
|
|
591
|
+
|
|
592
|
+
def compute(self) -> AnalysisResult:
|
|
593
|
+
fit_result = super().compute()
|
|
594
|
+
fitted = fit_result.models.get("regression")
|
|
595
|
+
if not isinstance(fitted, regression.FittedRegression):
|
|
596
|
+
raise ValueError("The fitted regression model is not available for profiling.")
|
|
597
|
+
params = dict(fit_result.params)
|
|
598
|
+
params["model_type"] = combo_value(self.type_combo) or "Linear"
|
|
599
|
+
params["predictors"] = list(fitted.predictors)
|
|
600
|
+
params["points"] = self.points_spin.value()
|
|
601
|
+
return self.finish(regression.profile_result(fitted, self.points_spin.value(), params))
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
class RegressionMultiResponseDialog(BaseDialog):
|
|
605
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
606
|
+
super().__init__(table, "Multi-Response Optimization", parent)
|
|
607
|
+
self.type_combo = self.add_combo("Model", REGRESSION_MODELS, default="Linear")
|
|
608
|
+
numeric = numeric_columns(table)
|
|
609
|
+
responses_default = numeric[: min(2, len(numeric))]
|
|
610
|
+
self.responses = self.add_multi("Responses", numeric, responses_default)
|
|
611
|
+
self.responses.setMaximumHeight(110)
|
|
612
|
+
predictors_default = [column for column in numeric if column not in responses_default][:3]
|
|
613
|
+
if not predictors_default:
|
|
614
|
+
predictors_default = [
|
|
615
|
+
column for column in all_columns(table) if column not in responses_default
|
|
616
|
+
][:3]
|
|
617
|
+
self.predictors = self.add_multi("Predictors", all_columns(table), predictors_default)
|
|
618
|
+
self.interactions_check = self.add_bool("Include two-way interactions", False)
|
|
619
|
+
|
|
620
|
+
self.add_page("Goals")
|
|
621
|
+
self.add_label(
|
|
622
|
+
"Set a desirability goal for each response. Lower and upper bounds default to the "
|
|
623
|
+
"observed response range."
|
|
624
|
+
)
|
|
625
|
+
self.goals_table = QTableWidget(0, 7)
|
|
626
|
+
self.goals_table.setHorizontalHeaderLabels(
|
|
627
|
+
["Response", "Goal", "Lower", "Upper", "Target", "Weight", "Importance"]
|
|
628
|
+
)
|
|
629
|
+
self.goals_table.horizontalHeader().setStretchLastSection(True)
|
|
630
|
+
self.goals_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
|
631
|
+
self.goals_table.setMaximumHeight(190)
|
|
632
|
+
self.add_row("Response goals", self.goals_table)
|
|
633
|
+
|
|
634
|
+
self.add_page("Advanced")
|
|
635
|
+
self.robust_check = self.add_bool("Robust standard errors (HC3, linear only)", False)
|
|
636
|
+
self.degree_spin = self.add_int("Polynomial degree", 2, 1, 8)
|
|
637
|
+
self.family_combo = self.add_combo(
|
|
638
|
+
"GLM family",
|
|
639
|
+
["gaussian", "binomial", "poisson", "gamma", "inverse_gaussian", "negative_binomial"],
|
|
640
|
+
default="gaussian",
|
|
641
|
+
)
|
|
642
|
+
self.link_combo = self.add_combo(
|
|
643
|
+
"GLM link",
|
|
644
|
+
["default", "identity", "log", "logit", "probit", "inverse", "sqrt", "cloglog"],
|
|
645
|
+
default="default",
|
|
646
|
+
)
|
|
647
|
+
self.correlation_combo = self.add_combo(
|
|
648
|
+
"GEE correlation", ["exchangeable", "independence", "ar", "stationary"], default="exchangeable"
|
|
649
|
+
)
|
|
650
|
+
self.gee_compare_check = self.add_bool("Compare GEE correlation structures", False)
|
|
651
|
+
self.test_size_spin = self.add_float("Holdout fraction", 0.0, 0.0, 0.5, 2)
|
|
652
|
+
self.weight_combo = self.add_combo("Weight column (linear)", all_columns(table), allow_none=True)
|
|
653
|
+
self.group_combo = self.add_combo(
|
|
654
|
+
"Mixed / GEE group", all_columns(table), allow_none=True, default=preferred_categorical(table)
|
|
655
|
+
)
|
|
656
|
+
self.random_slope_combo = self.add_combo("Random slope (optional)", all_columns(table), allow_none=True)
|
|
657
|
+
self.threshold_spin = self.add_float("Stepwise p threshold", 0.05, 0.0001, 0.9999, 4)
|
|
658
|
+
|
|
659
|
+
self.add_page("Optimization")
|
|
660
|
+
self.starts_spin = self.add_int("Optimization starts", 20, 1, 500)
|
|
661
|
+
self.seed_spin = self.add_int("Random seed", 42, 0, 2_000_000_000)
|
|
662
|
+
self.max_categories_spin = self.add_int("Max categorical combinations", 256, 1, 100_000)
|
|
663
|
+
|
|
664
|
+
self._refreshing_goals = False
|
|
665
|
+
self.responses.itemChanged.connect(self._refresh_goal_rows)
|
|
666
|
+
self._refresh_goal_rows()
|
|
667
|
+
|
|
668
|
+
def _default_goal(self, response: str) -> dict[str, str]:
|
|
669
|
+
values = pd.to_numeric(self.df[response], errors="coerce").dropna()
|
|
670
|
+
if values.empty:
|
|
671
|
+
low = high = target = ""
|
|
672
|
+
else:
|
|
673
|
+
low_value = float(values.min())
|
|
674
|
+
high_value = float(values.max())
|
|
675
|
+
low = f"{low_value:.6g}"
|
|
676
|
+
high = f"{high_value:.6g}"
|
|
677
|
+
target = f"{(low_value + high_value) / 2:.6g}"
|
|
678
|
+
return {
|
|
679
|
+
"goal": "Maximize",
|
|
680
|
+
"low": low,
|
|
681
|
+
"upper": high,
|
|
682
|
+
"target": target,
|
|
683
|
+
"weight": "1",
|
|
684
|
+
"importance": "1",
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
def _goal_row_values(self) -> dict[str, list[str]]:
|
|
688
|
+
previous: dict[str, list[str]] = {}
|
|
689
|
+
for row in range(self.goals_table.rowCount()):
|
|
690
|
+
response_item = self.goals_table.item(row, 0)
|
|
691
|
+
if response_item is None:
|
|
692
|
+
continue
|
|
693
|
+
values = []
|
|
694
|
+
for column in range(1, self.goals_table.columnCount()):
|
|
695
|
+
item = self.goals_table.item(row, column)
|
|
696
|
+
values.append("" if item is None else item.text())
|
|
697
|
+
previous[response_item.text()] = values
|
|
698
|
+
return previous
|
|
699
|
+
|
|
700
|
+
def _refresh_goal_rows(self) -> None:
|
|
701
|
+
if self._refreshing_goals:
|
|
702
|
+
return
|
|
703
|
+
self._refreshing_goals = True
|
|
704
|
+
try:
|
|
705
|
+
previous = self._goal_row_values()
|
|
706
|
+
selected = self.responses.checked_items()
|
|
707
|
+
self.goals_table.setRowCount(len(selected))
|
|
708
|
+
for row, response in enumerate(selected):
|
|
709
|
+
values = previous.get(response)
|
|
710
|
+
if values is None:
|
|
711
|
+
defaults = self._default_goal(response)
|
|
712
|
+
values = [
|
|
713
|
+
defaults["goal"],
|
|
714
|
+
defaults["low"],
|
|
715
|
+
defaults["upper"],
|
|
716
|
+
defaults["target"],
|
|
717
|
+
defaults["weight"],
|
|
718
|
+
defaults["importance"],
|
|
719
|
+
]
|
|
720
|
+
response_item = QTableWidgetItem(response)
|
|
721
|
+
response_item.setFlags(response_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
|
|
722
|
+
self.goals_table.setItem(row, 0, response_item)
|
|
723
|
+
for column, value in enumerate(values, start=1):
|
|
724
|
+
self.goals_table.setItem(row, column, QTableWidgetItem(str(value)))
|
|
725
|
+
finally:
|
|
726
|
+
self._refreshing_goals = False
|
|
727
|
+
|
|
728
|
+
@staticmethod
|
|
729
|
+
def _goal_float(text: str) -> float | None:
|
|
730
|
+
text = text.strip()
|
|
731
|
+
if not text:
|
|
732
|
+
return None
|
|
733
|
+
try:
|
|
734
|
+
return float(text)
|
|
735
|
+
except ValueError as exc:
|
|
736
|
+
raise ValueError(f"Invalid goal value: {text!r}") from exc
|
|
737
|
+
|
|
738
|
+
def _goals_from_table(self) -> dict[str, dict]:
|
|
739
|
+
goals: dict[str, dict] = {}
|
|
740
|
+
for row in range(self.goals_table.rowCount()):
|
|
741
|
+
response_item = self.goals_table.item(row, 0)
|
|
742
|
+
if response_item is None:
|
|
743
|
+
continue
|
|
744
|
+
cells = [
|
|
745
|
+
self.goals_table.item(row, column)
|
|
746
|
+
for column in range(1, self.goals_table.columnCount())
|
|
747
|
+
]
|
|
748
|
+
texts = [cell.text() if cell is not None else "" for cell in cells]
|
|
749
|
+
goals[response_item.text()] = {
|
|
750
|
+
"goal": texts[0],
|
|
751
|
+
"low": self._goal_float(texts[1]),
|
|
752
|
+
"high": self._goal_float(texts[2]),
|
|
753
|
+
"target": self._goal_float(texts[3]),
|
|
754
|
+
"weight": self._goal_float(texts[4]),
|
|
755
|
+
"importance": self._goal_float(texts[5]),
|
|
756
|
+
}
|
|
757
|
+
return goals
|
|
758
|
+
|
|
759
|
+
def _apply_goals(self, goals: dict[str, dict]) -> None:
|
|
760
|
+
self._refresh_goal_rows()
|
|
761
|
+
for row in range(self.goals_table.rowCount()):
|
|
762
|
+
response_item = self.goals_table.item(row, 0)
|
|
763
|
+
if response_item is None:
|
|
764
|
+
continue
|
|
765
|
+
values = goals.get(response_item.text())
|
|
766
|
+
if not values:
|
|
767
|
+
continue
|
|
768
|
+
raw = [
|
|
769
|
+
str(values.get("goal", "none")).title(),
|
|
770
|
+
"" if values.get("low") is None else f"{float(values['low']):.6g}",
|
|
771
|
+
"" if values.get("high") is None else f"{float(values['high']):.6g}",
|
|
772
|
+
"" if values.get("target") is None else f"{float(values['target']):.6g}",
|
|
773
|
+
"" if values.get("weight") is None else f"{float(values['weight']):.6g}",
|
|
774
|
+
"" if values.get("importance") is None else f"{float(values['importance']):.6g}",
|
|
775
|
+
]
|
|
776
|
+
for column, value in enumerate(raw, start=1):
|
|
777
|
+
self.goals_table.setItem(row, column, QTableWidgetItem(value))
|
|
778
|
+
|
|
779
|
+
def apply_kind(self, kind: str) -> None:
|
|
780
|
+
if kind == "regression_multi_response_optimization":
|
|
781
|
+
return
|
|
782
|
+
|
|
783
|
+
def apply_params(self, params: dict | None = None) -> None:
|
|
784
|
+
params = dict(params or {})
|
|
785
|
+
model_type = params.get("model_type")
|
|
786
|
+
if params.get("max_categorical_combinations") is not None:
|
|
787
|
+
params.setdefault("max_categories", params["max_categorical_combinations"])
|
|
788
|
+
if params.get("compare_structures") is not None:
|
|
789
|
+
params.setdefault("gee_compare", params["compare_structures"])
|
|
790
|
+
if model_type:
|
|
791
|
+
self.type_combo.setCurrentText(str(model_type))
|
|
792
|
+
super().apply_params(params)
|
|
793
|
+
responses = params.get("responses")
|
|
794
|
+
if responses:
|
|
795
|
+
self.responses.set_checked(responses)
|
|
796
|
+
self._apply_goals(params.get("goals") or {})
|
|
797
|
+
|
|
798
|
+
def make_job(self):
|
|
799
|
+
model_type = combo_value(self.type_combo) or "Linear"
|
|
800
|
+
responses = self.responses.checked_items()
|
|
801
|
+
predictors = [item for item in self.predictors.checked_items() if item not in responses]
|
|
802
|
+
if not responses:
|
|
803
|
+
raise ValueError("Choose at least one response.")
|
|
804
|
+
if not predictors:
|
|
805
|
+
raise ValueError("Choose at least one predictor.")
|
|
806
|
+
link = combo_value(self.link_combo)
|
|
807
|
+
values = {
|
|
808
|
+
"df": self.df,
|
|
809
|
+
"responses": responses,
|
|
810
|
+
"predictors": predictors,
|
|
811
|
+
"model_type": model_type,
|
|
812
|
+
"goals": self._goals_from_table(),
|
|
813
|
+
"starts": self.starts_spin.value(),
|
|
814
|
+
"seed": self.seed_spin.value(),
|
|
815
|
+
"interactions": self.interactions_check.isChecked(),
|
|
816
|
+
"robust": self.robust_check.isChecked(),
|
|
817
|
+
"weight": combo_value(self.weight_combo),
|
|
818
|
+
"test_size": self.test_size_spin.value(),
|
|
819
|
+
"degree": self.degree_spin.value(),
|
|
820
|
+
"family": combo_value(self.family_combo) or "gaussian",
|
|
821
|
+
"link": None if link == "default" else link,
|
|
822
|
+
"group": combo_value(self.group_combo),
|
|
823
|
+
"random_slope": combo_value(self.random_slope_combo),
|
|
824
|
+
"correlation": combo_value(self.correlation_combo) or "exchangeable",
|
|
825
|
+
"compare_structures": self.gee_compare_check.isChecked(),
|
|
826
|
+
"criterion": "auto",
|
|
827
|
+
"threshold": self.threshold_spin.value(),
|
|
828
|
+
"max_categorical_combinations": self.max_categories_spin.value(),
|
|
829
|
+
}
|
|
830
|
+
return lambda token, progress: regression.multi_response_optimize(
|
|
831
|
+
values["df"],
|
|
832
|
+
values["responses"],
|
|
833
|
+
values["predictors"],
|
|
834
|
+
values["model_type"],
|
|
835
|
+
values["goals"],
|
|
836
|
+
values["starts"],
|
|
837
|
+
values["seed"],
|
|
838
|
+
values["interactions"],
|
|
839
|
+
values["robust"],
|
|
840
|
+
values["weight"],
|
|
841
|
+
values["test_size"],
|
|
842
|
+
values["degree"],
|
|
843
|
+
values["family"],
|
|
844
|
+
values["link"],
|
|
845
|
+
values["group"],
|
|
846
|
+
values["random_slope"],
|
|
847
|
+
values["correlation"],
|
|
848
|
+
values["compare_structures"],
|
|
849
|
+
values["criterion"],
|
|
850
|
+
values["threshold"],
|
|
851
|
+
values["max_categorical_combinations"],
|
|
852
|
+
)
|
|
853
|
+
|
|
854
|
+
def compute(self) -> AnalysisResult:
|
|
855
|
+
model_type = combo_value(self.type_combo) or "Linear"
|
|
856
|
+
responses = self.responses.checked_items()
|
|
857
|
+
predictors = [item for item in self.predictors.checked_items() if item not in responses]
|
|
858
|
+
if not responses:
|
|
859
|
+
raise ValueError("Choose at least one response.")
|
|
860
|
+
if not predictors:
|
|
861
|
+
raise ValueError("Choose at least one predictor.")
|
|
862
|
+
link = combo_value(self.link_combo)
|
|
863
|
+
result = regression.multi_response_optimize(
|
|
864
|
+
self.df,
|
|
865
|
+
responses,
|
|
866
|
+
predictors,
|
|
867
|
+
model_type,
|
|
868
|
+
self._goals_from_table(),
|
|
869
|
+
self.starts_spin.value(),
|
|
870
|
+
self.seed_spin.value(),
|
|
871
|
+
self.interactions_check.isChecked(),
|
|
872
|
+
self.robust_check.isChecked(),
|
|
873
|
+
combo_value(self.weight_combo),
|
|
874
|
+
self.test_size_spin.value(),
|
|
875
|
+
self.degree_spin.value(),
|
|
876
|
+
combo_value(self.family_combo) or "gaussian",
|
|
877
|
+
None if link == "default" else link,
|
|
878
|
+
combo_value(self.group_combo),
|
|
879
|
+
combo_value(self.random_slope_combo),
|
|
880
|
+
combo_value(self.correlation_combo) or "exchangeable",
|
|
881
|
+
self.gee_compare_check.isChecked(),
|
|
882
|
+
"pvalue",
|
|
883
|
+
self.threshold_spin.value(),
|
|
884
|
+
self.max_categories_spin.value(),
|
|
885
|
+
)
|
|
886
|
+
return self.finish(result)
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
class MultivariateDialog(BaseDialog):
|
|
890
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
891
|
+
super().__init__(table, "Multivariate Analysis", parent)
|
|
892
|
+
self.type_combo = self.add_combo(
|
|
893
|
+
"Analysis",
|
|
894
|
+
["PCA", "K-Means", "Hierarchical Clustering", "Discriminant Analysis", "Factor Analysis", "MANOVA", "Canonical Correlation"],
|
|
895
|
+
default="PCA",
|
|
896
|
+
)
|
|
897
|
+
numeric = numeric_columns(table)
|
|
898
|
+
self.columns = self.add_multi("Numeric variables", numeric, numeric[: min(5, len(numeric))])
|
|
899
|
+
self.class_combo = self.add_combo("Class / factor (discriminant, MANOVA)", all_columns(table), allow_none=True, default=low_cardinality_columns(table)[0] if low_cardinality_columns(table) else first_categorical(table))
|
|
900
|
+
self.components_spin = self.add_int("PCA components", 2, 1, 30)
|
|
901
|
+
self.factors_spin = self.add_int("Factor count", 2, 1, 20)
|
|
902
|
+
self.clusters_spin = self.add_int("Clusters", 3, 1, 50)
|
|
903
|
+
self.linkage_combo = self.add_combo("Linkage", ["ward", "complete", "average", "single"], default="ward")
|
|
904
|
+
self.standardize_check = self.add_bool("Standardize variables", True)
|
|
905
|
+
self.discriminant_method_combo = self.add_combo("Discriminant method", ["LDA", "QDA"], default="LDA")
|
|
906
|
+
self.cv_check = self.add_bool("Cross-validate discriminant model", True)
|
|
907
|
+
self.second_columns = self.add_multi("Canonical Y variables", numeric, numeric[-min(2, len(numeric)):])
|
|
908
|
+
|
|
909
|
+
def apply_kind(self, kind: str) -> None:
|
|
910
|
+
label = {
|
|
911
|
+
"pca": "PCA",
|
|
912
|
+
"kmeans": "K-Means",
|
|
913
|
+
"hierarchical_clustering": "Hierarchical Clustering",
|
|
914
|
+
"discriminant": "Discriminant Analysis",
|
|
915
|
+
"factor_analysis": "Factor Analysis",
|
|
916
|
+
"manova": "MANOVA",
|
|
917
|
+
"canonical_correlation": "Canonical Correlation",
|
|
918
|
+
}.get(kind)
|
|
919
|
+
if label:
|
|
920
|
+
self.type_combo.setCurrentText(label)
|
|
921
|
+
|
|
922
|
+
@staticmethod
|
|
923
|
+
def _set_checked(widget, values) -> None:
|
|
924
|
+
if values is None:
|
|
925
|
+
return
|
|
926
|
+
wanted = {str(value) for value in values}
|
|
927
|
+
for index in range(widget.count()):
|
|
928
|
+
item = widget.item(index)
|
|
929
|
+
item.setCheckState(Qt.CheckState.Checked if item.text() in wanted else Qt.CheckState.Unchecked)
|
|
930
|
+
|
|
931
|
+
def apply_params(self, params: dict | None) -> None:
|
|
932
|
+
super().apply_params(params)
|
|
933
|
+
params = params or {}
|
|
934
|
+
if params.get("n_components") is not None:
|
|
935
|
+
self.components_spin.setValue(int(params["n_components"]))
|
|
936
|
+
if params.get("n_clusters") is not None:
|
|
937
|
+
self.clusters_spin.setValue(int(params["n_clusters"]))
|
|
938
|
+
if params.get("n_factors") is not None:
|
|
939
|
+
self.factors_spin.setValue(int(params["n_factors"]))
|
|
940
|
+
if params.get("linkage_method") is not None:
|
|
941
|
+
self.linkage_combo.setCurrentText(str(params["linkage_method"]))
|
|
942
|
+
if params.get("method") is not None:
|
|
943
|
+
index = self.discriminant_method_combo.findText(str(params["method"]).upper())
|
|
944
|
+
if index >= 0:
|
|
945
|
+
self.discriminant_method_combo.setCurrentIndex(index)
|
|
946
|
+
if params.get("cross_validate") is not None:
|
|
947
|
+
self.cv_check.setChecked(bool(params["cross_validate"]))
|
|
948
|
+
response = params.get("response") or params.get("factor")
|
|
949
|
+
if response is not None:
|
|
950
|
+
index = self.class_combo.findData(response)
|
|
951
|
+
if index >= 0:
|
|
952
|
+
self.class_combo.setCurrentIndex(index)
|
|
953
|
+
if params.get("predictors") is not None:
|
|
954
|
+
self._set_checked(self.columns, params["predictors"])
|
|
955
|
+
if params.get("responses") is not None:
|
|
956
|
+
self._set_checked(self.columns, params["responses"])
|
|
957
|
+
if params.get("x_columns") is not None or params.get("y_columns") is not None:
|
|
958
|
+
x_columns = list(params.get("x_columns") or [])
|
|
959
|
+
y_columns = list(params.get("y_columns") or [])
|
|
960
|
+
self._set_checked(self.columns, x_columns + y_columns)
|
|
961
|
+
self._set_checked(self.second_columns, y_columns)
|
|
962
|
+
|
|
963
|
+
def _request(self):
|
|
964
|
+
return {
|
|
965
|
+
"df": self.df,
|
|
966
|
+
"kind": combo_value(self.type_combo),
|
|
967
|
+
"columns": self.columns.checked_items(),
|
|
968
|
+
"components": self.components_spin.value(),
|
|
969
|
+
"standardize": self.standardize_check.isChecked(),
|
|
970
|
+
"clusters": self.clusters_spin.value(),
|
|
971
|
+
"linkage": combo_value(self.linkage_combo) or "ward",
|
|
972
|
+
"class_column": combo_value(self.class_combo),
|
|
973
|
+
"method": (combo_value(self.discriminant_method_combo) or "LDA").lower(),
|
|
974
|
+
"cv": self.cv_check.isChecked(),
|
|
975
|
+
"factors": self.factors_spin.value(),
|
|
976
|
+
"second": self.second_columns.checked_items(),
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
@staticmethod
|
|
980
|
+
def _run_request(values):
|
|
981
|
+
df = values["df"]
|
|
982
|
+
kind = values["kind"]
|
|
983
|
+
columns = values["columns"]
|
|
984
|
+
if not columns:
|
|
985
|
+
raise ValueError("Choose at least one variable.")
|
|
986
|
+
if kind == "PCA":
|
|
987
|
+
return multivariate.pca(df, columns, values["components"], values["standardize"])
|
|
988
|
+
if kind == "K-Means":
|
|
989
|
+
return multivariate.kmeans_clustering(df, columns, values["clusters"], values["standardize"])
|
|
990
|
+
if kind == "Hierarchical Clustering":
|
|
991
|
+
return multivariate.hierarchical_clustering(df, columns, values["clusters"], values["linkage"])
|
|
992
|
+
if kind == "Discriminant Analysis":
|
|
993
|
+
class_column = values["class_column"]
|
|
994
|
+
if not class_column:
|
|
995
|
+
raise ValueError("Choose a class column.")
|
|
996
|
+
return multivariate.discriminant_analysis(df, class_column, [c for c in columns if c != class_column], values["method"], values["cv"])
|
|
997
|
+
if kind == "Factor Analysis":
|
|
998
|
+
return multivariate.factor_analysis(df, columns, values["factors"])
|
|
999
|
+
if kind == "MANOVA":
|
|
1000
|
+
class_column = values["class_column"]
|
|
1001
|
+
if not class_column:
|
|
1002
|
+
raise ValueError("Choose a factor column.")
|
|
1003
|
+
return multivariate.manova(df, [c for c in columns if c != class_column], class_column)
|
|
1004
|
+
if kind == "Canonical Correlation":
|
|
1005
|
+
second = values["second"]
|
|
1006
|
+
predictors = [c for c in columns if c not in second]
|
|
1007
|
+
if not second:
|
|
1008
|
+
raise ValueError("Choose at least one canonical Y variable.")
|
|
1009
|
+
if not predictors:
|
|
1010
|
+
raise ValueError("Choose at least one X variable that is not also a Y variable.")
|
|
1011
|
+
return multivariate.canonical_correlation(df, predictors, second)
|
|
1012
|
+
raise ValueError("Unknown analysis.")
|
|
1013
|
+
|
|
1014
|
+
def make_job(self):
|
|
1015
|
+
values = self._request()
|
|
1016
|
+
return lambda token, progress: self._run_request(values)
|
|
1017
|
+
|
|
1018
|
+
def compute(self) -> AnalysisResult:
|
|
1019
|
+
return self.finish(self._run_request(self._request()))
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
class TimeSeriesDialog(BaseDialog):
|
|
1023
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
1024
|
+
super().__init__(table, "Time Series", parent)
|
|
1025
|
+
self.type_combo = self.add_combo(
|
|
1026
|
+
"Analysis",
|
|
1027
|
+
[
|
|
1028
|
+
"Summary",
|
|
1029
|
+
"ACF / PACF",
|
|
1030
|
+
"Stationarity",
|
|
1031
|
+
"Seasonal Decomposition",
|
|
1032
|
+
"STL Decomposition",
|
|
1033
|
+
"ARIMA",
|
|
1034
|
+
"Exponential Smoothing",
|
|
1035
|
+
"Forecast",
|
|
1036
|
+
],
|
|
1037
|
+
default="Summary",
|
|
1038
|
+
)
|
|
1039
|
+
self.column_combo = self.add_combo("Series column", numeric_columns(table))
|
|
1040
|
+
self.period_spin = self.add_int("Period", 12, 0, 1000)
|
|
1041
|
+
self.model_combo = self.add_combo("Decomposition model", ["additive", "multiplicative"], default="additive")
|
|
1042
|
+
self.lags_spin = self.add_int("ACF lags", 20, 1, 500)
|
|
1043
|
+
self.add_page("ARIMA / Smoothing")
|
|
1044
|
+
self.p_spin = self.add_int("AR order p", 1, 0, 10)
|
|
1045
|
+
self.d_spin = self.add_int("Difference order d", 1, 0, 3)
|
|
1046
|
+
self.q_spin = self.add_int("MA order q", 0, 0, 10)
|
|
1047
|
+
self.seasonal_p_spin = self.add_int("Seasonal P", 0, 0, 5)
|
|
1048
|
+
self.seasonal_d_spin = self.add_int("Seasonal D", 0, 0, 2)
|
|
1049
|
+
self.seasonal_q_spin = self.add_int("Seasonal Q", 0, 0, 5)
|
|
1050
|
+
self.seasonal_period_spin = self.add_int("Seasonal period (SARIMA)", 0, 0, 365)
|
|
1051
|
+
self.steps_spin = self.add_int("Forecast / horizon periods", 12, 1, 1000)
|
|
1052
|
+
self.trend_combo = self.add_combo("Smoothing trend", ["add", "mul", "none"], default="add")
|
|
1053
|
+
self.seasonal_combo = self.add_combo("Smoothing seasonality", ["none", "add", "mul"], default="none")
|
|
1054
|
+
self.forecast_method_combo = self.add_combo(
|
|
1055
|
+
"Forecast method",
|
|
1056
|
+
["Auto (ETS)", "ARIMA", "STL", "Seasonal naive", "Naive", "Mean", "Drift"],
|
|
1057
|
+
default="Auto (ETS)",
|
|
1058
|
+
)
|
|
1059
|
+
self.add_page("Forecast / Interventions")
|
|
1060
|
+
self.term_combo = self.add_combo("ARIMA term", ["none", "constant", "trend", "constant+trend"], default="none")
|
|
1061
|
+
self.backtest_spin = self.add_int("Backtest windows", 0, 0, 50)
|
|
1062
|
+
self.pulse_edit = self.add_text("Pulse interventions (indices)", "")
|
|
1063
|
+
self.step_edit = self.add_text("Step interventions (indices)", "")
|
|
1064
|
+
self.robust_check = self.add_bool("Robust STL", False)
|
|
1065
|
+
self.stl_seasonal_spin = self.add_int("STL seasonal smoother", 7, 3, 101)
|
|
1066
|
+
|
|
1067
|
+
def _seasonal(self):
|
|
1068
|
+
if self.seasonal_period_spin.value() > 0:
|
|
1069
|
+
return (self.seasonal_p_spin.value(), self.seasonal_d_spin.value(), self.seasonal_q_spin.value(), self.seasonal_period_spin.value())
|
|
1070
|
+
return None
|
|
1071
|
+
|
|
1072
|
+
def apply_kind(self, kind: str) -> None:
|
|
1073
|
+
label = {
|
|
1074
|
+
"ts_summary": "Summary",
|
|
1075
|
+
"acf_pacf": "ACF / PACF",
|
|
1076
|
+
"stationarity": "Stationarity",
|
|
1077
|
+
"decomposition": "Seasonal Decomposition",
|
|
1078
|
+
"stl": "STL Decomposition",
|
|
1079
|
+
"arima": "ARIMA",
|
|
1080
|
+
"exponential_smoothing": "Exponential Smoothing",
|
|
1081
|
+
"forecast": "Forecast",
|
|
1082
|
+
}.get(kind)
|
|
1083
|
+
if label:
|
|
1084
|
+
self.type_combo.setCurrentText(label)
|
|
1085
|
+
|
|
1086
|
+
def apply_params(self, params: dict | None) -> None:
|
|
1087
|
+
super().apply_params(params)
|
|
1088
|
+
params = params or {}
|
|
1089
|
+
seasonal = params.get("seasonal")
|
|
1090
|
+
if isinstance(seasonal, int) and not isinstance(seasonal, bool):
|
|
1091
|
+
self.stl_seasonal_spin.setValue(int(seasonal))
|
|
1092
|
+
order = params.get("order")
|
|
1093
|
+
if order and len(order) >= 3:
|
|
1094
|
+
self.p_spin.setValue(int(order[0]))
|
|
1095
|
+
self.d_spin.setValue(int(order[1]))
|
|
1096
|
+
self.q_spin.setValue(int(order[2]))
|
|
1097
|
+
seasonal_order = params.get("seasonal_order")
|
|
1098
|
+
if seasonal_order and len(seasonal_order) >= 4:
|
|
1099
|
+
self.seasonal_p_spin.setValue(int(seasonal_order[0]))
|
|
1100
|
+
self.seasonal_d_spin.setValue(int(seasonal_order[1]))
|
|
1101
|
+
self.seasonal_q_spin.setValue(int(seasonal_order[2]))
|
|
1102
|
+
self.seasonal_period_spin.setValue(int(seasonal_order[3]))
|
|
1103
|
+
method = params.get("method")
|
|
1104
|
+
if method:
|
|
1105
|
+
label = {
|
|
1106
|
+
"auto": "Auto (ETS)",
|
|
1107
|
+
"arima": "ARIMA",
|
|
1108
|
+
"manual": "Manual ARIMA",
|
|
1109
|
+
"stl": "STL",
|
|
1110
|
+
"snaive": "Seasonal naive",
|
|
1111
|
+
"naive": "Naive",
|
|
1112
|
+
"mean": "Mean",
|
|
1113
|
+
"drift": "Drift",
|
|
1114
|
+
}.get(method)
|
|
1115
|
+
if label:
|
|
1116
|
+
self.forecast_method_combo.setCurrentText(label)
|
|
1117
|
+
manual_term = params.get("manual_term")
|
|
1118
|
+
if manual_term:
|
|
1119
|
+
label = {"none": "none", "c": "constant", "t": "trend", "ct": "constant+trend"}.get(manual_term)
|
|
1120
|
+
if label:
|
|
1121
|
+
self.term_combo.setCurrentText(label)
|
|
1122
|
+
if params.get("backtest") is not None:
|
|
1123
|
+
self.backtest_spin.setValue(int(params["backtest"]))
|
|
1124
|
+
if params.get("horizon") is not None:
|
|
1125
|
+
self.steps_spin.setValue(int(params["horizon"]))
|
|
1126
|
+
if params.get("steps") is not None:
|
|
1127
|
+
self.steps_spin.setValue(int(params["steps"]))
|
|
1128
|
+
if params.get("pulse") is not None:
|
|
1129
|
+
self.pulse_edit.setText(", ".join(str(value) for value in params["pulse"]))
|
|
1130
|
+
if params.get("step") is not None:
|
|
1131
|
+
self.step_edit.setText(", ".join(str(value) for value in params["step"]))
|
|
1132
|
+
if params.get("robust") is not None:
|
|
1133
|
+
self.robust_check.setChecked(bool(params["robust"]))
|
|
1134
|
+
|
|
1135
|
+
def _request(self):
|
|
1136
|
+
return {
|
|
1137
|
+
"df": self.df,
|
|
1138
|
+
"kind": combo_value(self.type_combo),
|
|
1139
|
+
"column": combo_value(self.column_combo) or "",
|
|
1140
|
+
"period": self.period_spin.value(),
|
|
1141
|
+
"model": combo_value(self.model_combo) or "additive",
|
|
1142
|
+
"lags": self.lags_spin.value(),
|
|
1143
|
+
"stl_seasonal": self.stl_seasonal_spin.value(),
|
|
1144
|
+
"robust": self.robust_check.isChecked(),
|
|
1145
|
+
"order": (self.p_spin.value(), self.d_spin.value(), self.q_spin.value()),
|
|
1146
|
+
"seasonal_order": self._seasonal(),
|
|
1147
|
+
"steps": self.steps_spin.value(),
|
|
1148
|
+
"trend": combo_value(self.trend_combo),
|
|
1149
|
+
"seasonal": combo_value(self.seasonal_combo),
|
|
1150
|
+
"forecast_method": combo_value(self.forecast_method_combo) or "Auto (ETS)",
|
|
1151
|
+
"term": combo_value(self.term_combo) or "none",
|
|
1152
|
+
"backtest": self.backtest_spin.value(),
|
|
1153
|
+
"pulse": text_value(self.pulse_edit),
|
|
1154
|
+
"step": text_value(self.step_edit),
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
@staticmethod
|
|
1158
|
+
def _run_request(values):
|
|
1159
|
+
kind = values["kind"]
|
|
1160
|
+
column = values["column"]
|
|
1161
|
+
df = values["df"]
|
|
1162
|
+
if kind == "Summary":
|
|
1163
|
+
return timeseries.time_series_summary(df, column, values["period"] or None)
|
|
1164
|
+
if kind == "ACF / PACF":
|
|
1165
|
+
return timeseries.acf_pacf(df, column, values["lags"])
|
|
1166
|
+
if kind == "Stationarity":
|
|
1167
|
+
return timeseries.stationarity_tests(df, column)
|
|
1168
|
+
if kind == "Seasonal Decomposition":
|
|
1169
|
+
return timeseries.decomposition(df, column, max(2, values["period"]), values["model"])
|
|
1170
|
+
if kind == "STL Decomposition":
|
|
1171
|
+
return timeseries.stl_decomposition(df, column, max(2, values["period"]), values["stl_seasonal"], values["robust"])
|
|
1172
|
+
if kind == "ARIMA":
|
|
1173
|
+
return timeseries.arima_forecast(df, column, values["order"], values["seasonal_order"], values["steps"])
|
|
1174
|
+
if kind == "Exponential Smoothing":
|
|
1175
|
+
trend = values["trend"]
|
|
1176
|
+
seasonal = values["seasonal"]
|
|
1177
|
+
return timeseries.exponential_smoothing(
|
|
1178
|
+
df,
|
|
1179
|
+
column,
|
|
1180
|
+
None if trend == "none" else trend,
|
|
1181
|
+
None if seasonal == "none" else seasonal,
|
|
1182
|
+
values["period"] if seasonal != "none" else None,
|
|
1183
|
+
values["steps"],
|
|
1184
|
+
)
|
|
1185
|
+
method = {
|
|
1186
|
+
"Auto (ETS)": "auto",
|
|
1187
|
+
"ARIMA": "arima",
|
|
1188
|
+
"STL": "stl",
|
|
1189
|
+
"Seasonal naive": "snaive",
|
|
1190
|
+
"Naive": "naive",
|
|
1191
|
+
"Mean": "mean",
|
|
1192
|
+
"Drift": "drift",
|
|
1193
|
+
}.get(values["forecast_method"], "auto")
|
|
1194
|
+
term = {"none": "none", "constant": "c", "trend": "t", "constant+trend": "ct"}.get(values["term"], "none")
|
|
1195
|
+
from statstudio.ui.dialogs.extended_dialogs import _parse_int_list
|
|
1196
|
+
|
|
1197
|
+
return timeseries.forecast(
|
|
1198
|
+
df,
|
|
1199
|
+
column,
|
|
1200
|
+
method=method,
|
|
1201
|
+
period=values["period"] or None,
|
|
1202
|
+
horizon=values["steps"],
|
|
1203
|
+
order=values["order"],
|
|
1204
|
+
seasonal_order=values["seasonal_order"],
|
|
1205
|
+
manual_term=term,
|
|
1206
|
+
backtest=values["backtest"],
|
|
1207
|
+
pulse=_parse_int_list(values["pulse"]),
|
|
1208
|
+
step=_parse_int_list(values["step"]),
|
|
1209
|
+
robust=values["robust"],
|
|
1210
|
+
)
|
|
1211
|
+
|
|
1212
|
+
def make_job(self):
|
|
1213
|
+
values = self._request()
|
|
1214
|
+
return lambda token, progress: self._run_request(values)
|
|
1215
|
+
|
|
1216
|
+
def compute(self) -> AnalysisResult:
|
|
1217
|
+
return self.finish(self._run_request(self._request()))
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
class SurvivalDialog(BaseDialog):
|
|
1221
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
1222
|
+
super().__init__(table, "Survival Analysis", parent)
|
|
1223
|
+
self.type_combo = self.add_combo(
|
|
1224
|
+
"Analysis",
|
|
1225
|
+
["Kaplan-Meier", "Cox Regression", "Log-Rank", "Competing Risks", "Weibull / AFT", "Interval-Censored Weibull"],
|
|
1226
|
+
default="Kaplan-Meier",
|
|
1227
|
+
)
|
|
1228
|
+
numeric = numeric_columns(table)
|
|
1229
|
+
binaries = binary_columns(table)
|
|
1230
|
+
self.time_combo = self.add_combo("Time column", numeric, default=numeric[0] if numeric else None)
|
|
1231
|
+
self.upper_combo = self.add_combo("Upper time (interval-censored)", numeric, allow_none=True, default=numeric[1] if len(numeric) > 1 else None)
|
|
1232
|
+
self.event_combo = self.add_combo("Event / censor column", all_columns(table), allow_none=True, default=binaries[0] if binaries else None)
|
|
1233
|
+
if not binaries:
|
|
1234
|
+
self.event_combo.setCurrentIndex(0)
|
|
1235
|
+
self.event_value_edit = self.add_text("Event value (blank = auto)", "")
|
|
1236
|
+
self.competing_value_edit = self.add_text("Competing event value (competing risks)", "2")
|
|
1237
|
+
self.group_combo = self.add_combo("Group (optional)", all_columns(table), allow_none=True, default=first_categorical(table, exclude=binaries[:1]))
|
|
1238
|
+
self.dist_combo = self.add_combo("AFT distribution", ["Weibull", "Exponential", "Lognormal", "Loglogistic"], default="Weibull")
|
|
1239
|
+
self.predictors = self.add_multi("Predictors / covariates", all_columns(table), [])
|
|
1240
|
+
self.predictors.setMaximumHeight(110)
|
|
1241
|
+
|
|
1242
|
+
def apply_params(self, params: dict | None) -> None:
|
|
1243
|
+
params = dict(params or {})
|
|
1244
|
+
distribution = params.pop("distribution", None)
|
|
1245
|
+
if distribution:
|
|
1246
|
+
self.dist_combo.setCurrentText(str(distribution).title())
|
|
1247
|
+
super().apply_params(params)
|
|
1248
|
+
|
|
1249
|
+
def apply_kind(self, kind: str) -> None:
|
|
1250
|
+
label = {
|
|
1251
|
+
"kaplan_meier": "Kaplan-Meier",
|
|
1252
|
+
"cox": "Cox Regression",
|
|
1253
|
+
"cox_regression": "Cox Regression",
|
|
1254
|
+
"logrank": "Log-Rank",
|
|
1255
|
+
"competing_risk": "Competing Risks",
|
|
1256
|
+
"cumulative_incidence": "Competing Risks",
|
|
1257
|
+
"weibull_aft": "Weibull / AFT",
|
|
1258
|
+
"interval_censored_weibull": "Interval-Censored Weibull",
|
|
1259
|
+
}.get(kind)
|
|
1260
|
+
if label:
|
|
1261
|
+
self.type_combo.setCurrentText(label)
|
|
1262
|
+
|
|
1263
|
+
def _request(self):
|
|
1264
|
+
kind = combo_value(self.type_combo)
|
|
1265
|
+
return {
|
|
1266
|
+
"df": self.df,
|
|
1267
|
+
"kind": kind,
|
|
1268
|
+
"event_value": text_value(self.event_value_edit) or None,
|
|
1269
|
+
"time": combo_value(self.time_combo) or "",
|
|
1270
|
+
"event": combo_value(self.event_combo) or "",
|
|
1271
|
+
"predictors": self.predictors.checked_items(),
|
|
1272
|
+
"group": combo_value(self.group_combo),
|
|
1273
|
+
"distribution": (combo_value(self.dist_combo) or "weibull").lower(),
|
|
1274
|
+
"upper": combo_value(self.upper_combo) or combo_value(self.time_combo) or "",
|
|
1275
|
+
"competing_value": text_value(self.competing_value_edit) or None,
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
@staticmethod
|
|
1279
|
+
def _run_request(values):
|
|
1280
|
+
df = values["df"]
|
|
1281
|
+
kind = values["kind"]
|
|
1282
|
+
event_value = values["event_value"]
|
|
1283
|
+
time = values["time"]
|
|
1284
|
+
event = values["event"]
|
|
1285
|
+
if kind == "Interval-Censored Weibull":
|
|
1286
|
+
return survival.interval_censored_weibull(df, time, values["upper"], values["distribution"])
|
|
1287
|
+
if kind == "Cox Regression":
|
|
1288
|
+
predictors = [p for p in values["predictors"] if p not in {time, event, values["group"]}]
|
|
1289
|
+
return survival.cox_regression(df, time, event, predictors, event_value)
|
|
1290
|
+
if kind == "Log-Rank":
|
|
1291
|
+
return survival.logrank_test(df, time, event, values["group"] or "", event_value)
|
|
1292
|
+
if kind == "Competing Risks":
|
|
1293
|
+
return survival.cumulative_incidence(df, time, event, event_value, values["competing_value"], values["group"])
|
|
1294
|
+
if kind == "Weibull / AFT":
|
|
1295
|
+
predictors = [p for p in values["predictors"] if p not in {time, event, values["group"]}]
|
|
1296
|
+
return survival.weibull_aft(df, time, event, predictors, values["distribution"], event_value)
|
|
1297
|
+
return survival.kaplan_meier(df, time, event, values["group"], event_value)
|
|
1298
|
+
|
|
1299
|
+
def make_job(self):
|
|
1300
|
+
values = self._request()
|
|
1301
|
+
return lambda token, progress: self._run_request(values)
|
|
1302
|
+
|
|
1303
|
+
def compute(self) -> AnalysisResult:
|
|
1304
|
+
return self.finish(self._run_request(self._request()))
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
class QualityDialog(BaseDialog):
|
|
1308
|
+
def help_topic(self) -> str:
|
|
1309
|
+
kind = combo_value(self.type_combo)
|
|
1310
|
+
if kind in {"Gage R&R", "Attribute Agreement"}:
|
|
1311
|
+
return "measurement-systems"
|
|
1312
|
+
return "quality-spc"
|
|
1313
|
+
|
|
1314
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
1315
|
+
super().__init__(table, "Quality / SPC", parent)
|
|
1316
|
+
self.type_combo = self.add_combo(
|
|
1317
|
+
"Analysis",
|
|
1318
|
+
[
|
|
1319
|
+
"Individuals / Moving Range",
|
|
1320
|
+
"X-bar / R Chart",
|
|
1321
|
+
"X-bar / S Chart",
|
|
1322
|
+
"p Chart",
|
|
1323
|
+
"np Chart",
|
|
1324
|
+
"c Chart",
|
|
1325
|
+
"u Chart",
|
|
1326
|
+
"CUSUM Chart",
|
|
1327
|
+
"EWMA Chart",
|
|
1328
|
+
"Laney P' Chart",
|
|
1329
|
+
"Laney U' Chart",
|
|
1330
|
+
"Process Capability",
|
|
1331
|
+
"Pareto Chart",
|
|
1332
|
+
"Gage R&R",
|
|
1333
|
+
"Attribute Agreement",
|
|
1334
|
+
],
|
|
1335
|
+
default="Individuals / Moving Range",
|
|
1336
|
+
)
|
|
1337
|
+
numeric = numeric_columns(table)
|
|
1338
|
+
self.column_combo = self.add_combo("Measurement", numeric)
|
|
1339
|
+
self.subgroup_combo = self.add_combo("Subgroup (X-bar/R/S)", all_columns(table), allow_none=True, default=first_categorical(table))
|
|
1340
|
+
self.sample_size_spin = self.add_int("Sample size (attribute charts)", 50, 1, 1_000_000)
|
|
1341
|
+
self.sample_size_combo = self.add_combo("Sample-size column (variable N)", numeric, allow_none=True)
|
|
1342
|
+
self.sigma_combo = self.add_combo("Within sigma method", ["Moving range", "Overall", "R-bar", "S-bar", "Pooled", "Median MR"], default="Moving range")
|
|
1343
|
+
self.rules_spin = self.add_int("Nelson rules to apply", 8, 1, 8)
|
|
1344
|
+
self.add_page("Capability / Advanced")
|
|
1345
|
+
self.historical_sigma_edit = self.add_text("Historical sigma (optional)", "")
|
|
1346
|
+
self.nonnormal_combo = self.add_combo("Capability distribution", ["Normal", "Box-Cox"], default="Normal")
|
|
1347
|
+
self.confidence_spin = self.add_float("Capability confidence (%)", 95.0, 50.0, 99.9, 2)
|
|
1348
|
+
self.lsl_edit = self.add_text("LSL (optional)", "")
|
|
1349
|
+
self.usl_edit = self.add_text("USL (optional)", "")
|
|
1350
|
+
self.target_edit = self.add_text("Target (optional)", "")
|
|
1351
|
+
self.add_page("Gage / Agreement")
|
|
1352
|
+
self.gage_tolerance_edit = self.add_text("Gage tolerance (optional)", "")
|
|
1353
|
+
low_card = low_cardinality_columns(table)
|
|
1354
|
+
self.part_combo = self.add_combo("Gage R&R: Part", all_columns(table), allow_none=True, default=low_card[0] if low_card else None)
|
|
1355
|
+
self.operator_combo = self.add_combo("Gage R&R: Operator", all_columns(table), allow_none=True, default=low_card[1] if len(low_card) > 1 else None)
|
|
1356
|
+
self.gage_design_combo = self.add_combo("Gage R&R design", ["Crossed", "Nested", "Expanded"], default="Crossed")
|
|
1357
|
+
self.batch_combo = self.add_combo("Gage R&R: Batch (expanded)", all_columns(table), allow_none=True, default=low_card[2] if len(low_card) > 2 else None)
|
|
1358
|
+
self.gage_interaction_check = self.add_bool("Gage R&R interaction", True)
|
|
1359
|
+
self.appraiser_combo = self.add_combo("Attribute appraiser", all_columns(table), allow_none=True, default=low_card[1] if len(low_card) > 1 else None)
|
|
1360
|
+
self.rating_combo = self.add_combo("Attribute rating", all_columns(table), allow_none=True, default=low_card[2] if len(low_card) > 2 else None)
|
|
1361
|
+
|
|
1362
|
+
def apply_kind(self, kind: str) -> None:
|
|
1363
|
+
label = {
|
|
1364
|
+
"capability": "Process Capability",
|
|
1365
|
+
"gage_rr": "Gage R&R",
|
|
1366
|
+
"attribute_agreement": "Attribute Agreement",
|
|
1367
|
+
"pareto": "Pareto Chart",
|
|
1368
|
+
}.get(kind)
|
|
1369
|
+
if label:
|
|
1370
|
+
self.type_combo.setCurrentText(label)
|
|
1371
|
+
elif kind == "control_chart":
|
|
1372
|
+
self.type_combo.setCurrentText("Individuals / Moving Range")
|
|
1373
|
+
|
|
1374
|
+
def apply_params(self, params: dict | None) -> None:
|
|
1375
|
+
params = dict(params or {})
|
|
1376
|
+
chart = params.get("chart")
|
|
1377
|
+
label = {
|
|
1378
|
+
"individuals": "Individuals / Moving Range",
|
|
1379
|
+
"imr": "Individuals / Moving Range",
|
|
1380
|
+
"xbar_r": "X-bar / R Chart",
|
|
1381
|
+
"xbar_s": "X-bar / S Chart",
|
|
1382
|
+
"p": "p Chart",
|
|
1383
|
+
"np": "np Chart",
|
|
1384
|
+
"c": "c Chart",
|
|
1385
|
+
"u": "u Chart",
|
|
1386
|
+
"cusum": "CUSUM Chart",
|
|
1387
|
+
"ewma": "EWMA Chart",
|
|
1388
|
+
"laney_p": "Laney P' Chart",
|
|
1389
|
+
"laney_u": "Laney U' Chart",
|
|
1390
|
+
}.get(chart)
|
|
1391
|
+
if label:
|
|
1392
|
+
self.type_combo.setCurrentText(label)
|
|
1393
|
+
measurement = params.pop("measurement", None)
|
|
1394
|
+
if measurement:
|
|
1395
|
+
index = self.column_combo.findData(measurement)
|
|
1396
|
+
if index >= 0:
|
|
1397
|
+
self.column_combo.setCurrentIndex(index)
|
|
1398
|
+
column = params.pop("column", None)
|
|
1399
|
+
if column and column != measurement:
|
|
1400
|
+
index = self.column_combo.findData(column)
|
|
1401
|
+
if index >= 0:
|
|
1402
|
+
self.column_combo.setCurrentIndex(index)
|
|
1403
|
+
sigma_method = params.pop("sigma_method", None)
|
|
1404
|
+
if sigma_method:
|
|
1405
|
+
label = {
|
|
1406
|
+
"overall": "Overall",
|
|
1407
|
+
"moving_range": "Moving range",
|
|
1408
|
+
"rbar": "R-bar",
|
|
1409
|
+
"sbar": "S-bar",
|
|
1410
|
+
"pooled": "Pooled",
|
|
1411
|
+
"median_mr": "Median MR",
|
|
1412
|
+
}.get(sigma_method)
|
|
1413
|
+
if label:
|
|
1414
|
+
self.sigma_combo.setCurrentText(label)
|
|
1415
|
+
nonnormal = params.pop("nonnormal", None)
|
|
1416
|
+
if nonnormal:
|
|
1417
|
+
if nonnormal == "boxcox":
|
|
1418
|
+
self.nonnormal_combo.setCurrentText("Box-Cox")
|
|
1419
|
+
confidence = params.pop("confidence", None)
|
|
1420
|
+
if confidence is not None:
|
|
1421
|
+
value = float(confidence)
|
|
1422
|
+
if value <= 1.0:
|
|
1423
|
+
value *= 100.0
|
|
1424
|
+
self.confidence_spin.setValue(value)
|
|
1425
|
+
design = params.pop("design", None)
|
|
1426
|
+
if design:
|
|
1427
|
+
self.gage_design_combo.setCurrentText(str(design).title())
|
|
1428
|
+
interaction = params.pop("interaction", None)
|
|
1429
|
+
if interaction is not None:
|
|
1430
|
+
self.gage_interaction_check.setChecked(bool(interaction))
|
|
1431
|
+
tolerance = params.pop("tolerance", None)
|
|
1432
|
+
if tolerance is not None:
|
|
1433
|
+
self.gage_tolerance_edit.setText(f"{float(tolerance):g}")
|
|
1434
|
+
for key, widget in (("lsl", self.lsl_edit), ("usl", self.usl_edit), ("target", self.target_edit)):
|
|
1435
|
+
value = params.pop(key, None)
|
|
1436
|
+
if value is not None:
|
|
1437
|
+
widget.setText("" if value == "" else f"{float(value):g}")
|
|
1438
|
+
super().apply_params(params)
|
|
1439
|
+
|
|
1440
|
+
def _optional_float(self, text: str) -> float | None:
|
|
1441
|
+
text = text.strip()
|
|
1442
|
+
if not text:
|
|
1443
|
+
return None
|
|
1444
|
+
return float(text)
|
|
1445
|
+
|
|
1446
|
+
def compute(self) -> AnalysisResult:
|
|
1447
|
+
kind = combo_value(self.type_combo)
|
|
1448
|
+
column = combo_value(self.column_combo) or ""
|
|
1449
|
+
if kind == "Pareto Chart":
|
|
1450
|
+
return self.finish(quality.pareto_chart(self.df, column))
|
|
1451
|
+
if kind == "Process Capability":
|
|
1452
|
+
return self.finish(
|
|
1453
|
+
quality.capability(
|
|
1454
|
+
self.df,
|
|
1455
|
+
column,
|
|
1456
|
+
self._optional_float(text_value(self.lsl_edit)),
|
|
1457
|
+
self._optional_float(text_value(self.usl_edit)),
|
|
1458
|
+
self._optional_float(text_value(self.target_edit)),
|
|
1459
|
+
{
|
|
1460
|
+
"Overall": "overall",
|
|
1461
|
+
"Moving range": "moving_range",
|
|
1462
|
+
"R-bar": "rbar",
|
|
1463
|
+
"S-bar": "sbar",
|
|
1464
|
+
"Pooled": "pooled",
|
|
1465
|
+
"Median MR": "median_mr",
|
|
1466
|
+
}.get(combo_value(self.sigma_combo) or "Moving range", "moving_range"),
|
|
1467
|
+
combo_value(self.subgroup_combo),
|
|
1468
|
+
self._optional_float(text_value(self.historical_sigma_edit)),
|
|
1469
|
+
None if combo_value(self.nonnormal_combo) == "Normal" else "boxcox",
|
|
1470
|
+
self.confidence_spin.value() / 100.0,
|
|
1471
|
+
)
|
|
1472
|
+
)
|
|
1473
|
+
if kind == "Attribute Agreement":
|
|
1474
|
+
appraiser = combo_value(self.appraiser_combo)
|
|
1475
|
+
rating = combo_value(self.rating_combo)
|
|
1476
|
+
part = combo_value(self.part_combo)
|
|
1477
|
+
if not appraiser or not rating or not part:
|
|
1478
|
+
raise ValueError("Choose part, appraiser, and rating columns.")
|
|
1479
|
+
return self.finish(quality.attribute_agreement(self.df, part, appraiser, rating))
|
|
1480
|
+
if kind == "Gage R&R":
|
|
1481
|
+
return self.finish(
|
|
1482
|
+
quality.gage_rr(
|
|
1483
|
+
self.df,
|
|
1484
|
+
column,
|
|
1485
|
+
combo_value(self.part_combo) or "",
|
|
1486
|
+
combo_value(self.operator_combo) or "",
|
|
1487
|
+
(combo_value(self.gage_design_combo) or "crossed").lower(),
|
|
1488
|
+
self.gage_interaction_check.isChecked(),
|
|
1489
|
+
combo_value(self.batch_combo),
|
|
1490
|
+
self._optional_float(text_value(self.gage_tolerance_edit)),
|
|
1491
|
+
)
|
|
1492
|
+
)
|
|
1493
|
+
chart_map = {
|
|
1494
|
+
"Individuals / Moving Range": "imr",
|
|
1495
|
+
"X-bar / R Chart": "xbar_r",
|
|
1496
|
+
"X-bar / S Chart": "xbar_s",
|
|
1497
|
+
"p Chart": "p",
|
|
1498
|
+
"np Chart": "np",
|
|
1499
|
+
"c Chart": "c",
|
|
1500
|
+
"u Chart": "u",
|
|
1501
|
+
"CUSUM Chart": "cusum",
|
|
1502
|
+
"EWMA Chart": "ewma",
|
|
1503
|
+
"Laney P' Chart": "laney_p",
|
|
1504
|
+
"Laney U' Chart": "laney_u",
|
|
1505
|
+
}
|
|
1506
|
+
chart = chart_map.get(kind, "imr")
|
|
1507
|
+
size_column = combo_value(self.sample_size_combo)
|
|
1508
|
+
sample_size = self.sample_size_spin.value() if chart in {"p", "np", "u", "laney_p", "laney_u"} and not size_column else None
|
|
1509
|
+
return self.finish(
|
|
1510
|
+
quality.spc_chart(
|
|
1511
|
+
self.df,
|
|
1512
|
+
column,
|
|
1513
|
+
chart,
|
|
1514
|
+
combo_value(self.subgroup_combo),
|
|
1515
|
+
sample_size=sample_size,
|
|
1516
|
+
sample_size_column=size_column,
|
|
1517
|
+
rules=self.rules_spin.value(),
|
|
1518
|
+
)
|
|
1519
|
+
)
|
|
1520
|
+
|
|
1521
|
+
|
|
1522
|
+
class PowerDialog(BaseDialog):
|
|
1523
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
1524
|
+
super().__init__(table, "Power and Sample Size", parent)
|
|
1525
|
+
self.type_combo = self.add_combo(
|
|
1526
|
+
"Calculation",
|
|
1527
|
+
[
|
|
1528
|
+
"Sample size: t test",
|
|
1529
|
+
"Power: t test",
|
|
1530
|
+
"Sample size: paired t",
|
|
1531
|
+
"Sample size: proportions",
|
|
1532
|
+
"Sample size: ANOVA",
|
|
1533
|
+
"Sample size: equivalence",
|
|
1534
|
+
"Sample size: variance",
|
|
1535
|
+
"Power curve: t test",
|
|
1536
|
+
],
|
|
1537
|
+
default="Sample size: t test",
|
|
1538
|
+
)
|
|
1539
|
+
self.effect_spin = self.add_float("Effect size", 0.5, 0.0001, 100)
|
|
1540
|
+
self.nobs_spin = self.add_int("N per group (power)", 30, 2, 1_000_000)
|
|
1541
|
+
self.alpha_spin = self.add_float("Alpha", 0.05, 0.000001, 0.9999, 4)
|
|
1542
|
+
self.power_spin = self.add_float("Power", 0.8, 0.0001, 0.9999, 4)
|
|
1543
|
+
self.ratio_spin = self.add_float("Allocation ratio", 1.0, 0.0001, 100)
|
|
1544
|
+
self.baseline_spin = self.add_float("Baseline proportion", 0.2, 0.0001, 0.9999, 4)
|
|
1545
|
+
self.alternative_spin = self.add_float("Alternative proportion", 0.3, 0.0001, 0.9999, 4)
|
|
1546
|
+
self.groups_spin = self.add_int("Groups (ANOVA)", 3, 2, 100)
|
|
1547
|
+
self.difference_spin = self.add_float("Observed difference", 0.2, -1000, 1000)
|
|
1548
|
+
self.margin_spin = self.add_float("Equivalence margin", 0.5, 0.0001, 1000)
|
|
1549
|
+
self.sd_spin = self.add_float("Standard deviation", 1.0, 0.0001, 1000)
|
|
1550
|
+
self.variance_ratio_spin = self.add_float("Variance ratio (variance test)", 1.5, 1.0001, 1000)
|
|
1551
|
+
self.curve_max_spin = self.add_int("Max N per group (power curve)", 100, 2, 1_000_000)
|
|
1552
|
+
|
|
1553
|
+
def apply_params(self, params: dict | None) -> None:
|
|
1554
|
+
params = dict(params or {})
|
|
1555
|
+
aliases = {
|
|
1556
|
+
"effect_size": self.effect_spin,
|
|
1557
|
+
"nobs1": self.nobs_spin,
|
|
1558
|
+
"standard_deviation": self.sd_spin,
|
|
1559
|
+
"max_n": self.curve_max_spin,
|
|
1560
|
+
}
|
|
1561
|
+
for key, widget in aliases.items():
|
|
1562
|
+
if params.get(key) is not None:
|
|
1563
|
+
widget.setValue(params.pop(key))
|
|
1564
|
+
if params.get("ratio") is not None:
|
|
1565
|
+
kind = combo_value(self.type_combo)
|
|
1566
|
+
target = self.variance_ratio_spin if kind == "Sample size: variance" else self.ratio_spin
|
|
1567
|
+
target.setValue(float(params.pop("ratio")))
|
|
1568
|
+
super().apply_params(params)
|
|
1569
|
+
|
|
1570
|
+
def apply_kind(self, kind: str) -> None:
|
|
1571
|
+
label = {
|
|
1572
|
+
"power_t": "Power: t test",
|
|
1573
|
+
"power_t_sample_size": "Sample size: t test",
|
|
1574
|
+
"power_proportion": "Sample size: proportions",
|
|
1575
|
+
"power_anova": "Sample size: ANOVA",
|
|
1576
|
+
"power_paired_t": "Sample size: paired t",
|
|
1577
|
+
"power_equivalence": "Sample size: equivalence",
|
|
1578
|
+
"power_variance": "Sample size: variance",
|
|
1579
|
+
"power_curve": "Power curve: t test",
|
|
1580
|
+
}.get(kind)
|
|
1581
|
+
if label:
|
|
1582
|
+
self.type_combo.setCurrentText(label)
|
|
1583
|
+
|
|
1584
|
+
def _request(self):
|
|
1585
|
+
return {
|
|
1586
|
+
"kind": combo_value(self.type_combo),
|
|
1587
|
+
"effect": self.effect_spin.value(),
|
|
1588
|
+
"alpha": self.alpha_spin.value(),
|
|
1589
|
+
"power": self.power_spin.value(),
|
|
1590
|
+
"ratio": self.ratio_spin.value(),
|
|
1591
|
+
"nobs": self.nobs_spin.value(),
|
|
1592
|
+
"baseline": self.baseline_spin.value(),
|
|
1593
|
+
"alternative": self.alternative_spin.value(),
|
|
1594
|
+
"groups": self.groups_spin.value(),
|
|
1595
|
+
"difference": self.difference_spin.value(),
|
|
1596
|
+
"margin": self.margin_spin.value(),
|
|
1597
|
+
"sd": self.sd_spin.value(),
|
|
1598
|
+
"variance_ratio": self.variance_ratio_spin.value(),
|
|
1599
|
+
"curve_max": self.curve_max_spin.value(),
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
@staticmethod
|
|
1603
|
+
def _run_request(values):
|
|
1604
|
+
kind = values["kind"]
|
|
1605
|
+
if kind == "Sample size: t test":
|
|
1606
|
+
return power.sample_size_t_test(values["effect"], values["alpha"], values["power"], values["ratio"])
|
|
1607
|
+
if kind == "Power: t test":
|
|
1608
|
+
return power.power_t_test(values["effect"], values["nobs"], values["alpha"], values["ratio"])
|
|
1609
|
+
if kind == "Sample size: proportions":
|
|
1610
|
+
return power.sample_size_proportion(values["baseline"], values["alternative"], values["alpha"], values["power"], values["ratio"])
|
|
1611
|
+
if kind == "Sample size: paired t":
|
|
1612
|
+
return power.sample_size_paired_t(values["effect"], values["alpha"], values["power"])
|
|
1613
|
+
if kind == "Sample size: ANOVA":
|
|
1614
|
+
return power.sample_size_anova(values["effect"], values["groups"], values["alpha"], values["power"])
|
|
1615
|
+
if kind == "Sample size: equivalence":
|
|
1616
|
+
return power.sample_size_equivalence(values["difference"], values["margin"], values["sd"], values["alpha"], values["power"])
|
|
1617
|
+
if kind == "Sample size: variance":
|
|
1618
|
+
return power.sample_size_variance(values["variance_ratio"], values["alpha"], values["power"])
|
|
1619
|
+
return power.power_curve(values["effect"], values["alpha"], values["curve_max"], values["ratio"])
|
|
1620
|
+
|
|
1621
|
+
def make_job(self):
|
|
1622
|
+
values = self._request()
|
|
1623
|
+
return lambda token, progress: self._run_request(values)
|
|
1624
|
+
|
|
1625
|
+
def compute(self) -> AnalysisResult:
|
|
1626
|
+
return self.finish(self._run_request(self._request()))
|
|
1627
|
+
|
|
1628
|
+
|
|
1629
|
+
class DOEAnalysisDialog(BaseDialog):
|
|
1630
|
+
def __init__(self, table: DataTable, parent=None) -> None:
|
|
1631
|
+
super().__init__(table, "DOE Analysis", parent)
|
|
1632
|
+
info = doe.design_info(table)
|
|
1633
|
+
if info:
|
|
1634
|
+
self.add_label(f"Design: {info.get('design_type')} | Resolution: {info.get('resolution') or 'n/a'}")
|
|
1635
|
+
numeric = numeric_columns(table)
|
|
1636
|
+
self.response_combo = self.add_combo("Response", numeric or all_columns(table), default=(numeric[-1] if numeric else table.columns[-1]))
|
|
1637
|
+
self.order_combo = self.add_combo("Model order", ["Main effects", "Full quadratic (RSM)", "Full quadratic + 3-way"], default="Full quadratic (RSM)")
|
|
1638
|
+
self.optimize_combo = self.add_combo("Optimization", ["None", "Maximize", "Minimize"], default="None")
|
|
1639
|
+
if info and info.get("design_type") == "Custom":
|
|
1640
|
+
self.add_label(
|
|
1641
|
+
f"Custom design terms: {', '.join(info.get('terms', [])) or 'main effects'}. "
|
|
1642
|
+
f"Criterion: {info.get('criterion', 'D')}."
|
|
1643
|
+
)
|
|
1644
|
+
self.order_combo.setEnabled(False)
|
|
1645
|
+
self.optimize_combo.setEnabled(False)
|
|
1646
|
+
|
|
1647
|
+
def apply_params(self, params: dict | None) -> None:
|
|
1648
|
+
params = dict(params or {})
|
|
1649
|
+
order = params.pop("order", None)
|
|
1650
|
+
if order is not None:
|
|
1651
|
+
self.order_combo.setCurrentText(
|
|
1652
|
+
{1: "Main effects", 2: "Full quadratic (RSM)", 3: "Full quadratic + 3-way"}.get(int(order), "Full quadratic (RSM)")
|
|
1653
|
+
)
|
|
1654
|
+
optimize = params.pop("optimize", None)
|
|
1655
|
+
if optimize is not None:
|
|
1656
|
+
self.optimize_combo.setCurrentText({"max": "Maximize", "min": "Minimize"}.get(str(optimize).lower(), "None"))
|
|
1657
|
+
super().apply_params(params)
|
|
1658
|
+
|
|
1659
|
+
def _request(self):
|
|
1660
|
+
info = doe.design_info(self.table) or {}
|
|
1661
|
+
return {
|
|
1662
|
+
"table": self.table,
|
|
1663
|
+
"design_type": info.get("design_type"),
|
|
1664
|
+
"response": combo_value(self.response_combo) or "",
|
|
1665
|
+
"order": {"Main effects": 1, "Full quadratic (RSM)": 2, "Full quadratic + 3-way": 3}.get(combo_value(self.order_combo) or "", 2),
|
|
1666
|
+
"optimize": {"Maximize": "max", "Minimize": "min"}.get(combo_value(self.optimize_combo) or "", None),
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
@staticmethod
|
|
1670
|
+
def _run_request(values):
|
|
1671
|
+
table = values["table"]
|
|
1672
|
+
design_type = values["design_type"]
|
|
1673
|
+
if design_type == "Custom":
|
|
1674
|
+
result = custom_doe.analyze_custom_design(table, values["response"])
|
|
1675
|
+
result.source_table = table.name
|
|
1676
|
+
return result
|
|
1677
|
+
if design_type == "Mixture":
|
|
1678
|
+
return optimal_doe.analyze_mixture(table, values["response"], values["order"])
|
|
1679
|
+
result = doe.analyze_design(table, values["response"], values["order"], values["optimize"])
|
|
1680
|
+
result.source_table = table.name
|
|
1681
|
+
return result
|
|
1682
|
+
|
|
1683
|
+
def make_job(self):
|
|
1684
|
+
values = self._request()
|
|
1685
|
+
return lambda token, progress: self._run_request(values)
|
|
1686
|
+
|
|
1687
|
+
def compute(self) -> AnalysisResult:
|
|
1688
|
+
return self.finish(self._run_request(self._request()))
|