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,285 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
8
+ from PySide6.QtGui import QBrush, QColor, QFont
9
+
10
+ from statstudio.core.table import DataTable, format_value
11
+
12
+
13
+ class DataFrameModel(QAbstractTableModel):
14
+ cell_edited = Signal(object, str, object, object) # row_id, column, old, new
15
+ sort_changed = Signal(list, list) # previous sort spec, new sort spec
16
+
17
+ def __init__(self, table: DataTable, parent=None) -> None:
18
+ super().__init__(parent)
19
+ self.table = table
20
+ self._frame = pd.DataFrame()
21
+ self._columns: list[str] = []
22
+ self._virtual_rows = 100
23
+ self._virtual_cols = 10
24
+ self.refresh()
25
+
26
+ def refresh(self) -> None:
27
+ self.beginResetModel()
28
+ self.table.prune_row_states()
29
+ self._frame = self.table.display_df()
30
+ self._columns = [c for c in self.table.columns if c not in self.table.hidden_columns]
31
+ self.endResetModel()
32
+
33
+ def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
34
+ return 0 if parent.isValid() else len(self._frame) + self._virtual_rows
35
+
36
+ def columnCount(self, parent: QModelIndex = QModelIndex()) -> int:
37
+ return 0 if parent.isValid() else len(self._columns) + self._virtual_cols
38
+
39
+ def _can_edit_virtual(self) -> bool:
40
+ return not self.table.row_filter and not self.table.sort_spec and not self.table.hidden_columns
41
+
42
+ def expand_rows(self, count: int = 200) -> None:
43
+ start = self.rowCount()
44
+ self.beginInsertRows(QModelIndex(), start, start + count - 1)
45
+ self._virtual_rows += count
46
+ self.endInsertRows()
47
+
48
+ def expand_columns(self, count: int = 10) -> None:
49
+ start = self.columnCount()
50
+ self.beginInsertColumns(QModelIndex(), start, start + count - 1)
51
+ self._virtual_cols += count
52
+ self.endInsertColumns()
53
+
54
+ def flags(self, index: QModelIndex):
55
+ flags = super().flags(index)
56
+ if not index.isValid():
57
+ return flags
58
+ if index.row() >= len(self._frame) or index.column() >= len(self._columns):
59
+ if self._can_edit_virtual():
60
+ flags |= Qt.ItemFlag.ItemIsEditable
61
+ return flags
62
+ spec = self.table.specs.get(self._columns[index.column()])
63
+ if spec is None or not spec.formula:
64
+ flags |= Qt.ItemFlag.ItemIsEditable
65
+ return flags
66
+
67
+ def ensure_columns(self, col: int) -> bool:
68
+ if not self._can_edit_virtual() or col < len(self._columns):
69
+ return False
70
+ for _ in range(col - len(self._columns) + 1):
71
+ name = f"Column {len(self.table.columns) + 1}"
72
+ while name in self.table.columns:
73
+ name = f"{name} (2)"
74
+ self.table.insert_column(
75
+ name,
76
+ pd.Series([None] * len(self.table.data), index=self.table.data.index, dtype=object),
77
+ )
78
+ self.refresh()
79
+ return True
80
+
81
+ def _materialize(self, row: int, col: int) -> tuple[Any, str] | None:
82
+ if not self._can_edit_virtual():
83
+ return None
84
+ if col >= len(self._columns):
85
+ if not self.ensure_columns(col):
86
+ return None
87
+ if row >= len(self._frame):
88
+ self.table.ensure_rows(row + 1)
89
+ self.refresh()
90
+ if row >= len(self._frame) or col >= len(self._columns):
91
+ return None
92
+ return self._frame.index[row], self._columns[col]
93
+
94
+ def _parse(self, column: str, text: str) -> Any:
95
+ series = self.table.data[column]
96
+ if pd.api.types.is_datetime64_any_dtype(series):
97
+ return pd.to_datetime(text) if text else pd.NaT
98
+ if pd.api.types.is_integer_dtype(series):
99
+ if not text:
100
+ return np.nan
101
+ try:
102
+ return int(text)
103
+ except ValueError:
104
+ return float(text)
105
+ if pd.api.types.is_numeric_dtype(series):
106
+ return float(text) if text else np.nan
107
+ return text
108
+
109
+ def setData(self, index: QModelIndex, value: Any, role: int = Qt.ItemDataRole.EditRole) -> bool:
110
+ if role != Qt.ItemDataRole.EditRole or not index.isValid():
111
+ return False
112
+ row, col = index.row(), index.column()
113
+ if row >= len(self._frame) or col >= len(self._columns):
114
+ materialized = self._materialize(row, col)
115
+ if materialized is None:
116
+ return False
117
+ label, column = materialized
118
+ row = list(self._frame.index).index(label)
119
+ col = self._columns.index(column)
120
+ column = self._columns[col]
121
+ spec = self.table.specs.get(column)
122
+ if spec is not None and spec.formula:
123
+ return False
124
+ label = self._frame.index[row]
125
+ text = str(value).strip() if value is not None else ""
126
+ try:
127
+ parsed = self._parse(column, text)
128
+ except Exception:
129
+ return False
130
+ old = self.table.data.at[label, column]
131
+ if pd.api.types.is_integer_dtype(self.table.data[column]):
132
+ if isinstance(parsed, float) and float(parsed).is_integer():
133
+ parsed = int(parsed)
134
+ elif isinstance(parsed, float):
135
+ self.table.data[column] = self.table.data[column].astype(float)
136
+ self.table.data.at[label, column] = parsed
137
+ self.table.formula_errors.pop(column, None)
138
+ self.table.modified = True
139
+ self.table.recompute_formulas()
140
+ self.refresh()
141
+ self.cell_edited.emit(label, column, old, parsed)
142
+ return True
143
+
144
+ def set_cell(self, row_id: Any, column: str, value: Any) -> bool:
145
+ if column not in self.table.data.columns or row_id not in self.table.data.index:
146
+ return False
147
+ self.table.data.at[row_id, column] = value
148
+ self.table.recompute_formulas()
149
+ self.refresh()
150
+ return True
151
+
152
+ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
153
+ if not index.isValid():
154
+ return None
155
+ row, col = index.row(), index.column()
156
+ if row < 0 or col < 0:
157
+ return None
158
+ if row >= len(self._frame) or col >= len(self._columns):
159
+ if role == Qt.ItemDataRole.DisplayRole:
160
+ return ""
161
+ return None
162
+ column = self._columns[col]
163
+ value = self._frame.iloc[row][column]
164
+ row_id = self._frame.index[row]
165
+ state = self.table.row_state(row_id)
166
+ color = state.get("color")
167
+ if role == Qt.ItemDataRole.DisplayRole:
168
+ spec = self.table.specs.get(column)
169
+ return format_value(spec, value)
170
+ if role == Qt.ItemDataRole.TextAlignmentRole:
171
+ if pd.api.types.is_numeric_dtype(self._frame[column]):
172
+ return int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
173
+ return int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
174
+ if role == Qt.ItemDataRole.BackgroundRole:
175
+ if self.table.formula_errors.get(column):
176
+ return QBrush(QColor("#fde8e8"))
177
+ if state.get("excluded"):
178
+ return QBrush(QColor("#ececec"))
179
+ if color:
180
+ return QBrush(QColor(color))
181
+ if role == Qt.ItemDataRole.ForegroundRole:
182
+ if state.get("excluded") or state.get("hidden"):
183
+ return QBrush(QColor("#999999"))
184
+ if role == Qt.ItemDataRole.FontRole and state.get("hidden"):
185
+ font = QFont()
186
+ font.setItalic(True)
187
+ return font
188
+ if role == Qt.ItemDataRole.AccessibleTextRole:
189
+ spec = self.table.specs.get(column)
190
+ text = format_value(spec, value)
191
+ state_bits = []
192
+ if state.get("label"):
193
+ state_bits.append(f"label {state['label']}")
194
+ if state.get("excluded"):
195
+ state_bits.append("excluded")
196
+ if state.get("hidden"):
197
+ state_bits.append("hidden")
198
+ suffix = f", {', '.join(state_bits)}" if state_bits else ""
199
+ return f"{column} row {row_id}: {text}{suffix}"
200
+ if role == Qt.ItemDataRole.ToolTipRole:
201
+ spec = self.table.specs.get(column)
202
+ pieces = [f"Row {row_id}"]
203
+ if spec:
204
+ pieces.append(f"{column} ({spec.modeling_type})")
205
+ if spec.units:
206
+ pieces.append(f"Units: {spec.units}")
207
+ if spec.formula:
208
+ pieces.append(f"Formula: {spec.formula}")
209
+ pieces.append("Edit the formula in the formula bar; calculated cells are read-only.")
210
+ if spec.notes:
211
+ pieces.append(spec.notes)
212
+ error = self.table.formula_errors.get(column)
213
+ if error:
214
+ pieces.append(f"Formula error: {error}")
215
+ if state.get("label"):
216
+ pieces.append(f"Label: {state['label']}")
217
+ if state.get("excluded"):
218
+ pieces.append("Excluded from analyses")
219
+ if state.get("hidden"):
220
+ pieces.append("Hidden from plots")
221
+ return "\n".join(pieces)
222
+ return None
223
+
224
+ def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
225
+ if role == Qt.ItemDataRole.DisplayRole:
226
+ if orientation == Qt.Orientation.Horizontal:
227
+ if 0 <= section < len(self._columns):
228
+ name = self._columns[section]
229
+ return f"(!) {name}" if self.table.formula_errors.get(name) else name
230
+ if section >= len(self._columns):
231
+ return f"Column {len(self.table.columns) + section - len(self._columns) + 1}"
232
+ if orientation == Qt.Orientation.Vertical and section >= 0:
233
+ if section >= len(self._frame):
234
+ return str(section + 1)
235
+ row_id = self._frame.index[section]
236
+ state = self.table.row_state(row_id)
237
+ marks = []
238
+ if state.get("excluded"):
239
+ marks.append("E")
240
+ if state.get("hidden"):
241
+ marks.append("H")
242
+ return f"{section + 1} {''.join(marks)}".strip()
243
+ if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Vertical:
244
+ if 0 <= section < len(self._frame):
245
+ row_id = self._frame.index[section]
246
+ state = self.table.row_state(row_id)
247
+ pieces = [f"Row {row_id}"]
248
+ if state.get("label"):
249
+ pieces.append(f"Label: {state['label']}")
250
+ if state.get("excluded"):
251
+ pieces.append("Excluded from analyses")
252
+ if state.get("hidden"):
253
+ pieces.append("Hidden from plots")
254
+ return "\n".join(pieces)
255
+ if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Horizontal:
256
+ if 0 <= section < len(self._columns):
257
+ name = self._columns[section]
258
+ spec = self.table.specs.get(name)
259
+ if self.table.formula_errors.get(name):
260
+ return f"{name}: formula error: {self.table.formula_errors[name]}"
261
+ if spec:
262
+ return f"{spec.name}: {spec.modeling_type} ({spec.data_type})"
263
+ return None
264
+
265
+ def sort(self, column: int, order: Qt.SortOrder = Qt.SortOrder.AscendingOrder) -> None:
266
+ if self._frame.empty or column < 0 or column >= len(self._columns):
267
+ return
268
+ self.apply_sort([(self._columns[column], order == Qt.SortOrder.AscendingOrder)])
269
+
270
+ def apply_sort(self, spec: list[tuple[str, bool]]) -> None:
271
+ previous = list(self.table.sort_spec)
272
+ self.table.sort_by(spec)
273
+ self.refresh()
274
+ self.sort_changed.emit(previous, list(spec))
275
+
276
+ def column_name(self, section: int) -> str | None:
277
+ if 0 <= section < len(self._columns):
278
+ return self._columns[section]
279
+ return None
280
+
281
+ def row_ids(self, rows: list[int]) -> list[Any]:
282
+ return [self._frame.index[row] for row in rows if 0 <= row < len(self._frame)]
283
+
284
+ def frame(self) -> pd.DataFrame:
285
+ return self._frame
@@ -0,0 +1,285 @@
1
+ from __future__ import annotations
2
+
3
+ import pandas as pd
4
+ from PySide6.QtCore import QItemSelection, QItemSelectionModel, QModelIndex, QPoint, Qt, Signal
5
+ from PySide6.QtGui import QKeySequence
6
+ from PySide6.QtWidgets import QApplication, QHeaderView, QMenu, QTableView, QToolTip, QWidget
7
+
8
+ from statstudio.core.table import DataTable
9
+ from statstudio.ui.table_model import DataFrameModel
10
+
11
+
12
+ class ColumnHeaderView(QHeaderView):
13
+ column_clicked = Signal(int)
14
+ column_double_clicked = Signal(int)
15
+
16
+ def mouseReleaseEvent(self, event) -> None:
17
+ if event.button() == Qt.MouseButton.LeftButton:
18
+ section = self.logicalIndexAt(event.position().toPoint())
19
+ if section >= 0:
20
+ self.column_clicked.emit(section)
21
+ event.accept()
22
+ return
23
+ super().mouseReleaseEvent(event)
24
+
25
+ def mouseDoubleClickEvent(self, event) -> None:
26
+ section = self.logicalIndexAt(event.position().toPoint())
27
+ if section >= 0:
28
+ self.column_double_clicked.emit(section)
29
+ event.accept()
30
+ return
31
+ super().mouseDoubleClickEvent(event)
32
+
33
+
34
+ class DataTableView(QTableView):
35
+ column_properties_requested = Signal(str)
36
+ rename_column_requested = Signal(str)
37
+ delete_column_requested = Signal(str)
38
+ hide_column_requested = Signal(str)
39
+ move_column_requested = Signal(str, int)
40
+ unhide_columns_requested = Signal()
41
+ find_replace_requested = Signal()
42
+ exclude_rows_requested = Signal(list)
43
+ include_rows_requested = Signal(list)
44
+ clear_exclusions_requested = Signal()
45
+ hide_rows_requested = Signal(list)
46
+ unhide_rows_requested = Signal(list)
47
+ label_rows_requested = Signal(list)
48
+ color_rows_requested = Signal(list, str)
49
+ marker_rows_requested = Signal(list, str)
50
+ clear_row_states_requested = Signal()
51
+ duplicate_rows_requested = Signal(list)
52
+ delete_rows_requested = Signal(list)
53
+ create_subset_requested = Signal()
54
+ selection_changed = Signal(list)
55
+ cell_edited = Signal(object, str, object, object)
56
+ sort_changed = Signal(list, list)
57
+
58
+ def __init__(self, table: DataTable, parent: QWidget | None = None) -> None:
59
+ super().__init__(parent)
60
+ self.table = table
61
+ self.data_model = DataFrameModel(table, self)
62
+ self.data_model.cell_edited.connect(self.cell_edited)
63
+ self.data_model.sort_changed.connect(self.sort_changed)
64
+ header = ColumnHeaderView(Qt.Orientation.Horizontal, self)
65
+ self.setHorizontalHeader(header)
66
+ header.column_clicked.connect(self._header_clicked)
67
+ header.column_double_clicked.connect(self._header_double_clicked)
68
+ self.setModel(self.data_model)
69
+ had_sort = bool(table.sort_spec)
70
+ was_modified = table.modified
71
+ self.setSortingEnabled(True)
72
+ if not had_sort:
73
+ table.sort_spec = []
74
+ table.modified = was_modified
75
+ header.setSortIndicator(-1, Qt.SortOrder.AscendingOrder)
76
+ self.data_model.refresh()
77
+ self.setSelectionBehavior(QTableView.SelectionBehavior.SelectItems)
78
+ self.setSelectionMode(QTableView.SelectionMode.ExtendedSelection)
79
+ self.selectionModel().selectionChanged.connect(self._emit_selection_changed)
80
+ self.setAlternatingRowColors(True)
81
+ self.setWordWrap(False)
82
+ self.verticalHeader().setDefaultSectionSize(23)
83
+ self.horizontalHeader().setStretchLastSection(True)
84
+ self.horizontalHeader().setDefaultSectionSize(130)
85
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
86
+ self.customContextMenuRequested.connect(self._show_context_menu)
87
+ self.verticalScrollBar().valueChanged.connect(self._expand_rows_near_end)
88
+ self.horizontalScrollBar().valueChanged.connect(self._expand_columns_near_end)
89
+
90
+ def _header_clicked(self, section: int) -> None:
91
+ self.select_column(section)
92
+
93
+ def select_column(self, section: int) -> None:
94
+ if section < 0:
95
+ return
96
+ if section >= len(self.data_model._columns):
97
+ if not self.data_model.ensure_columns(section):
98
+ return
99
+ rows = len(self.data_model.frame())
100
+ selection = QItemSelection()
101
+ if rows:
102
+ selection.select(
103
+ self.data_model.index(0, section),
104
+ self.data_model.index(rows - 1, section),
105
+ )
106
+ self.selectionModel().select(
107
+ selection,
108
+ QItemSelectionModel.SelectionFlag.ClearAndSelect,
109
+ )
110
+ self.selectionModel().setCurrentIndex(
111
+ self.data_model.index(0, section),
112
+ QItemSelectionModel.SelectionFlag.NoUpdate,
113
+ )
114
+ self.scrollTo(self.data_model.index(0, section))
115
+
116
+ def _header_double_clicked(self, section: int) -> None:
117
+ column = self.data_model.column_name(section)
118
+ if column is not None:
119
+ self.column_properties_requested.emit(column)
120
+ return
121
+ if self.data_model.ensure_columns(section):
122
+ column = self.data_model.column_name(section)
123
+ if column is not None:
124
+ self.column_properties_requested.emit(column)
125
+
126
+ def _expand_rows_near_end(self, value: int) -> None:
127
+ bar = self.verticalScrollBar()
128
+ if bar.maximum() > 0 and value >= bar.maximum() - 2:
129
+ self.data_model.expand_rows()
130
+
131
+ def _expand_columns_near_end(self, value: int) -> None:
132
+ bar = self.horizontalScrollBar()
133
+ if bar.maximum() > 0 and value >= bar.maximum() - 2:
134
+ self.data_model.expand_columns()
135
+
136
+ def refresh(self) -> None:
137
+ self.data_model.refresh()
138
+
139
+ def copy_selection(self, *, include_headers: bool = False) -> None:
140
+ ranges = self.selectionModel().selection()
141
+ if not ranges:
142
+ return
143
+ blocks: list[str] = []
144
+ for selection in ranges:
145
+ rows = range(selection.top(), selection.bottom() + 1)
146
+ columns = range(selection.left(), selection.right() + 1)
147
+ lines: list[str] = []
148
+ if include_headers:
149
+ headers = [
150
+ str(self.data_model.headerData(column, Qt.Orientation.Horizontal) or "")
151
+ for column in columns
152
+ ]
153
+ lines.append("\t".join(headers))
154
+ for row in rows:
155
+ cells = []
156
+ for column in columns:
157
+ index = self.data_model.index(row, column)
158
+ cells.append(str(self.data_model.data(index, Qt.ItemDataRole.DisplayRole) or ""))
159
+ lines.append("\t".join(cells))
160
+ blocks.append("\n".join(lines))
161
+ text = "\n".join(blocks)
162
+ if text:
163
+ QApplication.clipboard().setText(text)
164
+ QToolTip.showText(self.viewport().mapToGlobal(self.viewport().rect().center()), "Copied", self)
165
+
166
+ def keyPressEvent(self, event) -> None: # type: ignore[override]
167
+ if event.matches(QKeySequence.StandardKey.Copy):
168
+ self.copy_selection()
169
+ event.accept()
170
+ return
171
+ super().keyPressEvent(event)
172
+
173
+ def selected_rows(self) -> list[int]:
174
+ return sorted({index.row() for index in self.selectionModel().selectedIndexes()})
175
+
176
+ def selected_row_ids(self) -> list[object]:
177
+ return self.data_model.row_ids(self.selected_rows())
178
+
179
+ def _emit_selection_changed(self, *_args) -> None:
180
+ self.selection_changed.emit(self.selected_row_ids())
181
+
182
+ def _select_row_positions(self, rows: list[int]) -> None:
183
+ if not rows:
184
+ return
185
+ selection = QItemSelection()
186
+ last_column = self.data_model.columnCount() - 1
187
+ for row in rows:
188
+ left = self.data_model.index(row, 0)
189
+ right = self.data_model.index(row, last_column)
190
+ selection.select(left, right)
191
+ self.selectionModel().select(
192
+ selection,
193
+ QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows,
194
+ )
195
+ self.scrollTo(self.data_model.index(rows[0], 0))
196
+
197
+ def select_rows_by_id(self, row_ids) -> None:
198
+ frame = self.data_model.frame()
199
+ wanted = set(row_ids)
200
+ rows = [position for position, index in enumerate(frame.index) if index in wanted]
201
+ self._select_row_positions(rows)
202
+
203
+ def select_all_rows(self) -> None:
204
+ self._select_row_positions(list(range(len(self.data_model.frame()))))
205
+
206
+ def select_rows_matching(self, column: str, value: object) -> None:
207
+ frame = self.data_model.frame()
208
+ if column not in frame.columns:
209
+ return
210
+ series = frame[column]
211
+ if pd.isna(value):
212
+ mask = series.isna()
213
+ else:
214
+ mask = series == value
215
+ rows = [position for position, flag in enumerate(mask.fillna(False).tolist()) if bool(flag)]
216
+ self._select_row_positions(rows)
217
+
218
+ def _cell_value(self, index: QModelIndex) -> tuple[str, object] | None:
219
+ column = self.data_model.column_name(index.column())
220
+ frame = self.data_model.frame()
221
+ if column is None or column not in frame.columns or not 0 <= index.row() < len(frame):
222
+ return None
223
+ return column, frame[column].iloc[index.row()]
224
+
225
+ def _show_context_menu(self, position: QPoint) -> None:
226
+ index = self.indexAt(position)
227
+ if index.isValid() and not self.selectionModel().isSelected(index):
228
+ self.selectionModel().select(
229
+ index,
230
+ QItemSelectionModel.SelectionFlag.ClearAndSelect,
231
+ )
232
+ menu = QMenu(self)
233
+ if index.isValid():
234
+ column = self.data_model.column_name(index.column())
235
+ if column:
236
+ menu.addAction("Column Properties...", lambda: self.column_properties_requested.emit(column))
237
+ menu.addAction("Rename Column...", lambda: self.rename_column_requested.emit(column))
238
+ menu.addAction("Move Column Left", lambda: self.move_column_requested.emit(column, -1))
239
+ menu.addAction("Move Column Right", lambda: self.move_column_requested.emit(column, 1))
240
+ menu.addAction("Hide Column", lambda: self.hide_column_requested.emit(column))
241
+ menu.addAction("Delete Column", lambda: self.delete_column_requested.emit(column))
242
+ menu.addSeparator()
243
+ cell = self._cell_value(index)
244
+ if cell is not None:
245
+ cell_column, cell_value = cell
246
+ menu.addAction(
247
+ "Select Rows Matching This Value",
248
+ lambda c=cell_column, v=cell_value: self.select_rows_matching(c, v),
249
+ )
250
+ menu.addAction("Select All Rows", self.select_all_rows)
251
+ menu.addAction("Copy Selection", self.copy_selection)
252
+ menu.addAction("Copy Selection with Headers", lambda: self.copy_selection(include_headers=True))
253
+ menu.addSeparator()
254
+ menu.addAction("Find && Replace...", self.find_replace_requested.emit)
255
+ menu.addAction("Unhide All Columns", self.unhide_columns_requested.emit)
256
+ menu.addSeparator()
257
+ rows = self.selected_row_ids()
258
+ if rows:
259
+ menu.addAction("Create Subset from Selected Rows", self.create_subset_requested.emit)
260
+ menu.addSeparator()
261
+ menu.addAction("Duplicate Selected Rows", lambda: self.duplicate_rows_requested.emit(rows))
262
+ menu.addAction("Delete Selected Rows", lambda: self.delete_rows_requested.emit(rows))
263
+ menu.addSeparator()
264
+ menu.addAction("Exclude Selected Rows", lambda: self.exclude_rows_requested.emit(rows))
265
+ menu.addAction("Include Selected Rows", lambda: self.include_rows_requested.emit(rows))
266
+ menu.addAction("Hide Selected Rows", lambda: self.hide_rows_requested.emit(rows))
267
+ menu.addAction("Unhide Selected Rows", lambda: self.unhide_rows_requested.emit(rows))
268
+ menu.addAction("Label Selected Rows...", lambda: self.label_rows_requested.emit(rows))
269
+ colors = menu.addMenu("Color Selected Rows")
270
+ from statstudio.core.table import ROW_COLORS
271
+
272
+ for name, value in zip(
273
+ ["Red", "Blue", "Green", "Purple", "Orange", "Yellow", "Brown", "Gray"], ROW_COLORS
274
+ ):
275
+ colors.addAction(name, lambda v=value, r=rows: self.color_rows_requested.emit(r, v))
276
+ colors.addAction("Clear", lambda r=rows: self.color_rows_requested.emit(r, ""))
277
+ markers = menu.addMenu("Marker Selected Rows")
278
+ from statstudio.core.table import ROW_MARKERS
279
+
280
+ for marker in ROW_MARKERS:
281
+ markers.addAction(marker.title(), lambda m=marker, r=rows: self.marker_rows_requested.emit(r, m))
282
+ markers.addAction("Clear", lambda r=rows: self.marker_rows_requested.emit(r, ""))
283
+ menu.addSeparator()
284
+ menu.addAction("Clear All Row States", self.clear_row_states_requested.emit)
285
+ menu.exec(self.viewport().mapToGlobal(position))