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,796 @@
1
+ from __future__ import annotations
2
+
3
+ import uuid
4
+ from dataclasses import asdict, dataclass, field
5
+ from datetime import datetime
6
+ from typing import Any, Iterable, Sequence
7
+
8
+ import math
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from pandas.api import types as ptypes
13
+
14
+
15
+ @dataclass
16
+ class ColumnSpec:
17
+ name: str
18
+ data_type: str = "numeric"
19
+ modeling_type: str = "continuous"
20
+ formula: str | None = None
21
+ format: str | None = None
22
+ units: str = ""
23
+ notes: str = ""
24
+ missing_values: list[Any] = field(default_factory=list)
25
+
26
+ def to_dict(self) -> dict[str, Any]:
27
+ return asdict(self)
28
+
29
+ @classmethod
30
+ def from_dict(cls, payload: dict[str, Any]) -> "ColumnSpec":
31
+ known = {f.name for f in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
32
+ return cls(**{k: v for k, v in payload.items() if k in known})
33
+
34
+
35
+ @dataclass
36
+ class TableScript:
37
+ name: str
38
+ code: str
39
+ created: str = field(default_factory=lambda: datetime.now().isoformat(timespec="seconds"))
40
+ analysis_type: str = ""
41
+ params: dict[str, Any] = field(default_factory=dict)
42
+ journal_id: str = ""
43
+ data_hash: str = ""
44
+ role: str = "source"
45
+ id: str = field(default_factory=lambda: uuid.uuid4().hex)
46
+
47
+ def to_dict(self) -> dict[str, Any]:
48
+ return asdict(self)
49
+
50
+ @classmethod
51
+ def from_dict(cls, payload: dict[str, Any]) -> "TableScript":
52
+ known = {f.name for f in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
53
+ return cls(**{key: value for key, value in payload.items() if key in known})
54
+
55
+
56
+ def format_value(spec: ColumnSpec | None, value: Any) -> str:
57
+ """Render a cell using the column format with a safe fallback."""
58
+ if value is None:
59
+ return ""
60
+ try:
61
+ if pd.isna(value):
62
+ return ""
63
+ except (TypeError, ValueError):
64
+ pass
65
+ pattern = (spec.format or "").strip() if spec is not None else ""
66
+ if pattern:
67
+ try:
68
+ if hasattr(value, "strftime") and "%" in pattern:
69
+ return value.strftime(pattern)
70
+ return format(value, pattern)
71
+ except (TypeError, ValueError):
72
+ pass
73
+ if isinstance(value, (float, np.floating)):
74
+ return f"{value: .6g}"
75
+ return str(value)
76
+
77
+
78
+ def apply_missing_values(frame: pd.DataFrame, specs: dict[str, ColumnSpec]) -> pd.DataFrame:
79
+ """Replace user-declared missing-value tokens without mutating raw data."""
80
+ result = frame
81
+ for column, spec in specs.items():
82
+ if not spec.missing_values or column not in result.columns:
83
+ continue
84
+ tokens = list(spec.missing_values)
85
+ if not tokens:
86
+ continue
87
+ if result is frame:
88
+ result = frame.copy()
89
+ result[column] = result[column].replace(tokens, np.nan)
90
+ return result
91
+
92
+
93
+ def _infer_data_type(series: pd.Series) -> str:
94
+ if ptypes.is_bool_dtype(series.dtype):
95
+ return "categorical"
96
+ if ptypes.is_numeric_dtype(series.dtype):
97
+ return "numeric"
98
+ if ptypes.is_datetime64_any_dtype(series.dtype):
99
+ return "date"
100
+ if isinstance(series.dtype, pd.CategoricalDtype):
101
+ return "categorical"
102
+ return "text"
103
+
104
+
105
+ def _infer_modeling_type(series: pd.Series) -> str:
106
+ if ptypes.is_numeric_dtype(series.dtype) and not ptypes.is_bool_dtype(series.dtype):
107
+ return "continuous"
108
+ if ptypes.is_datetime64_any_dtype(series.dtype):
109
+ return "continuous"
110
+ return "nominal"
111
+
112
+
113
+ def infer_specs(df: pd.DataFrame, specs: dict[str, ColumnSpec] | None = None) -> dict[str, ColumnSpec]:
114
+ specs = dict(specs or {})
115
+ for column in df.columns:
116
+ if column in specs:
117
+ specs[column].name = str(column)
118
+ continue
119
+ series = df[column]
120
+ specs[column] = ColumnSpec(
121
+ name=str(column),
122
+ data_type=_infer_data_type(series),
123
+ modeling_type=_infer_modeling_type(series),
124
+ )
125
+ return {name: specs[name] for name in df.columns}
126
+
127
+
128
+ ROW_COLORS = ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#ffff33", "#a65628", "#999999"]
129
+ ROW_MARKERS = ["circle", "square", "diamond", "triangle", "cross", "x"]
130
+
131
+
132
+ class DataTable:
133
+ """A DataFrame plus column and row metadata."""
134
+
135
+ def __init__(
136
+ self,
137
+ df: pd.DataFrame,
138
+ name: str,
139
+ source: str | None = None,
140
+ specs: dict[str, ColumnSpec] | None = None,
141
+ metadata: dict[str, Any] | None = None,
142
+ row_filter: str | None = None,
143
+ sort_spec: list[tuple[str, bool]] | None = None,
144
+ excluded_rows: Iterable[Any] | None = None,
145
+ hidden_columns: Iterable[str] | None = None,
146
+ hidden_rows: Iterable[Any] | None = None,
147
+ row_labels: dict[Any, str] | None = None,
148
+ row_colors: dict[Any, str] | None = None,
149
+ row_markers: dict[Any, str] | None = None,
150
+ scripts: Iterable[TableScript] | None = None,
151
+ formula_errors: dict[str, str] | None = None,
152
+ ) -> None:
153
+ df = df.copy()
154
+ names: list[str] = []
155
+ seen: dict[str, int] = {}
156
+ for index, column in enumerate(df.columns):
157
+ col_name = str(column).strip() or f"Column {index + 1}"
158
+ if col_name in seen:
159
+ seen[col_name] += 1
160
+ col_name = f"{col_name}_{seen[col_name]}"
161
+ else:
162
+ seen[col_name] = 1
163
+ names.append(col_name)
164
+ df.columns = names
165
+ if df.index.has_duplicates:
166
+ df = df.reset_index(drop=True)
167
+ self._df = df
168
+ self.name = name
169
+ self.source = source
170
+ self.specs = infer_specs(df, specs)
171
+ self.metadata = dict(metadata or {})
172
+ self.row_filter = row_filter
173
+ self.sort_spec = list(sort_spec or [])
174
+ self.excluded_rows = set(excluded_rows or [])
175
+ self.hidden_columns = set(hidden_columns or [])
176
+ self.hidden_rows = set(hidden_rows or [])
177
+ self.row_labels = {k: str(v) for k, v in (row_labels or {}).items()}
178
+ self.row_colors = {k: str(v) for k, v in (row_colors or {}).items()}
179
+ self.row_markers = {k: str(v) for k, v in (row_markers or {}).items()}
180
+ self.scripts = [TableScript.from_dict(script.to_dict()) for script in (scripts or [])]
181
+ self.formula_errors: dict[str, str] = dict(formula_errors or {})
182
+ self.modified = False
183
+
184
+ @property
185
+ def data(self) -> pd.DataFrame:
186
+ return self._df
187
+
188
+ @property
189
+ def columns(self) -> list[str]:
190
+ return [str(c) for c in self._df.columns]
191
+
192
+ @property
193
+ def shape(self) -> tuple[int, int]:
194
+ return self._df.shape
195
+
196
+ def __len__(self) -> int:
197
+ return len(self._df)
198
+
199
+ def spec(self, column: str) -> ColumnSpec:
200
+ return self.specs[column]
201
+
202
+ def set_modeling_type(self, column: str, modeling_type: str) -> None:
203
+ if column not in self.specs:
204
+ raise KeyError(column)
205
+ self.specs[column].modeling_type = modeling_type
206
+ self.modified = True
207
+
208
+ def set_column_notes(self, column: str, notes: str) -> None:
209
+ self.specs[column].notes = notes
210
+ self.modified = True
211
+
212
+ def set_formula(self, column: str, formula: str | None) -> bool:
213
+ if column not in self.specs:
214
+ raise KeyError(column)
215
+ self.specs[column].formula = formula or None
216
+ if not formula:
217
+ self.formula_errors.pop(column, None)
218
+ self.modified = True
219
+ return self.recompute_formulas()
220
+
221
+ def set_column_format(self, column: str, pattern: str | None) -> None:
222
+ if column not in self.specs:
223
+ raise KeyError(column)
224
+ self.specs[column].format = pattern or None
225
+ self.modified = True
226
+
227
+ def set_missing_values(self, column: str, values: Sequence[Any]) -> None:
228
+ if column not in self.specs:
229
+ raise KeyError(column)
230
+ self.specs[column].missing_values = list(values)
231
+ self.modified = True
232
+
233
+ def convert_column(self, column: str, data_type: str, modeling_type: str | None = None) -> int:
234
+ """Convert a column's values to a new data type; returns the count of newly missing values."""
235
+ if column not in self._df.columns:
236
+ raise KeyError(column)
237
+ series = self._df[column]
238
+ before_missing = int(series.isna().sum())
239
+ if data_type == "numeric":
240
+ converted = pd.to_numeric(series, errors="coerce")
241
+ elif data_type == "date":
242
+ converted = pd.to_datetime(series, errors="coerce")
243
+ elif data_type == "categorical":
244
+ converted = series.astype(object).where(series.notna(), None)
245
+ else:
246
+ converted = series.astype(object).where(series.notna(), None)
247
+ converted = converted.map(lambda value: value if pd.isna(value) else str(value))
248
+ self._df[column] = converted
249
+ spec = self.specs[column]
250
+ spec.data_type = data_type
251
+ if modeling_type:
252
+ spec.modeling_type = modeling_type
253
+ elif data_type in {"text", "categorical"}:
254
+ spec.modeling_type = "nominal"
255
+ else:
256
+ spec.modeling_type = "continuous"
257
+ self.modified = True
258
+ return max(0, int(converted.isna().sum()) - before_missing)
259
+
260
+ def latest(self, column: str | None = None) -> pd.Series:
261
+ if column is not None:
262
+ return self._df[column]
263
+ return self._df.iloc[:, -1]
264
+
265
+ def _source_frame(self) -> pd.DataFrame:
266
+ return apply_missing_values(self._df, self.specs)
267
+
268
+ def _filtered(self) -> pd.DataFrame:
269
+ frame = self._source_frame()
270
+ if self.row_filter:
271
+ from statstudio.core.formulas import evaluate_formula
272
+
273
+ mask = evaluate_formula(frame, self.row_filter)
274
+ if not isinstance(mask, pd.Series):
275
+ raise ValueError("Filter must produce a boolean column expression.")
276
+ frame = frame.loc[mask.fillna(False).astype(bool)]
277
+ return frame
278
+
279
+ def analysis_df(self, include_excluded: bool = False, honor_modeling: bool = False) -> pd.DataFrame:
280
+ frame = self._filtered()
281
+ if not include_excluded and self.excluded_rows:
282
+ frame = frame.loc[~frame.index.isin(self.excluded_rows)]
283
+ if honor_modeling:
284
+ frame = apply_modeling_types(frame, self.specs)
285
+ return frame
286
+
287
+ def visible_df(self, include_excluded: bool = True) -> pd.DataFrame:
288
+ """Visible rows: filter applied and hidden rows removed.
289
+
290
+ Excluded rows remain visible in the data table, so they are kept unless
291
+ ``include_excluded`` is explicitly False.
292
+ """
293
+ frame = self._filtered()
294
+ drop = set(self.hidden_rows)
295
+ if not include_excluded:
296
+ drop |= set(self.excluded_rows)
297
+ if drop:
298
+ frame = frame.loc[~frame.index.isin(drop)]
299
+ return frame
300
+
301
+ def plot_df(self) -> pd.DataFrame:
302
+ """Rows used for plotting: filter applied, hidden and excluded removed."""
303
+ frame = self._filtered()
304
+ drop = set(self.excluded_rows) | set(self.hidden_rows)
305
+ if drop:
306
+ frame = frame.loc[~frame.index.isin(drop)]
307
+ return frame
308
+
309
+ def display_df(self) -> pd.DataFrame:
310
+ frame = self._filtered()
311
+ for column, ascending in reversed(self.sort_spec):
312
+ if column not in frame.columns:
313
+ continue
314
+ spec = self.specs.get(column)
315
+ if (
316
+ spec is not None
317
+ and spec.modeling_type == "continuous"
318
+ and not ptypes.is_numeric_dtype(frame[column])
319
+ ):
320
+ key = "__statstudio_sort_key__"
321
+ work = frame.copy()
322
+ work[key] = pd.to_numeric(work[column], errors="coerce")
323
+ work = work.sort_values(key, ascending=ascending, kind="stable", na_position="last")
324
+ frame = work.drop(columns=[key])
325
+ else:
326
+ frame = frame.sort_values(column, ascending=ascending, kind="stable", na_position="last")
327
+ return frame
328
+
329
+ def set_filter(self, expression: str | None) -> None:
330
+ if expression:
331
+ from statstudio.core.formulas import evaluate_formula
332
+
333
+ mask = evaluate_formula(self._df, expression)
334
+ if not isinstance(mask, pd.Series):
335
+ raise ValueError("Filter must produce a boolean column expression.")
336
+ mask = mask.reindex(self._df.index, fill_value=False).fillna(False).astype(bool)
337
+ if len(mask) != len(self._df):
338
+ raise ValueError("Filter returned an unexpected number of rows.")
339
+ self.row_filter = expression or None
340
+ self.modified = True
341
+
342
+ def sort_by(self, columns: Sequence[tuple[str, bool]]) -> None:
343
+ for column, _ in columns:
344
+ if column not in self._df.columns:
345
+ raise KeyError(column)
346
+ self.sort_spec = list(columns)
347
+ self.modified = True
348
+
349
+ def add_column(
350
+ self,
351
+ name: str,
352
+ values: pd.Series | Sequence[Any] | np.ndarray,
353
+ spec: ColumnSpec | None = None,
354
+ formula: str | None = None,
355
+ ) -> None:
356
+ if name in self._df.columns:
357
+ raise ValueError(f"Column {name!r} already exists.")
358
+ if isinstance(values, pd.Series):
359
+ if len(values) == len(self._df):
360
+ if values.index.equals(self._df.index):
361
+ series = values
362
+ else:
363
+ series = pd.Series(values.to_numpy(), index=self._df.index)
364
+ else:
365
+ series = values
366
+ else:
367
+ series = pd.Series(list(values), index=self._df.index)
368
+ if len(series) != len(self._df):
369
+ raise ValueError("New column length does not match table.")
370
+ self._df[name] = series
371
+ if spec is None:
372
+ spec = ColumnSpec(
373
+ name=name,
374
+ data_type=_infer_data_type(series),
375
+ modeling_type=_infer_modeling_type(series),
376
+ formula=formula,
377
+ )
378
+ spec.name = name
379
+ if formula is not None:
380
+ spec.formula = formula
381
+ self.specs[name] = spec
382
+ self.modified = True
383
+
384
+ def insert_column(
385
+ self,
386
+ name: str,
387
+ values: pd.Series | Sequence[Any] | np.ndarray | None = None,
388
+ position: int | None = None,
389
+ spec: ColumnSpec | None = None,
390
+ ) -> None:
391
+ if name in self._df.columns:
392
+ raise ValueError(f"Column {name!r} already exists.")
393
+ if values is None:
394
+ series = pd.Series([None] * len(self._df), index=self._df.index, dtype=object)
395
+ elif isinstance(values, pd.Series):
396
+ if len(values) == len(self._df):
397
+ series = pd.Series(values.to_numpy(), index=self._df.index) if not values.index.equals(self._df.index) else values
398
+ else:
399
+ raise ValueError("New column length does not match table.")
400
+ else:
401
+ series = pd.Series(list(values), index=self._df.index)
402
+ if len(series) != len(self._df):
403
+ raise ValueError("New column length does not match table.")
404
+ self._df[name] = series
405
+ if position is not None:
406
+ columns = list(self._df.columns)
407
+ columns.remove(name)
408
+ position = max(0, min(int(position), len(columns)))
409
+ columns.insert(position, name)
410
+ self._df = self._df.loc[:, columns]
411
+ if spec is None:
412
+ spec = ColumnSpec(
413
+ name=name,
414
+ data_type=_infer_data_type(series),
415
+ modeling_type=_infer_modeling_type(series),
416
+ )
417
+ spec.name = name
418
+ self.specs[name] = spec
419
+ self.modified = True
420
+
421
+ def ensure_rows(self, count: int) -> None:
422
+ missing = int(count) - len(self._df)
423
+ if missing > 0:
424
+ add_rows(self, missing)
425
+
426
+ def ensure_columns(self, count: int) -> None:
427
+ while len(self._df.columns) < int(count):
428
+ name = f"Column {len(self._df.columns) + 1}"
429
+ while name in self._df.columns:
430
+ name = f"{name} (2)"
431
+ self.insert_column(name, pd.Series(np.nan, index=self._df.index, dtype=float))
432
+
433
+ def set_cells(self, updates: Iterable[tuple[Any, str, Any]], parse: bool = True) -> None:
434
+ changed = False
435
+ for row_id, column, value in updates:
436
+ if row_id not in self._df.index or column not in self._df.columns:
437
+ continue
438
+ spec = self.specs.get(column)
439
+ if spec is not None and spec.formula:
440
+ continue
441
+ if parse and isinstance(value, str):
442
+ series = self._df[column]
443
+ text = value.strip()
444
+ if text == "":
445
+ value = np.nan if ptypes.is_numeric_dtype(series.dtype) else None
446
+ elif ptypes.is_numeric_dtype(series.dtype):
447
+ try:
448
+ value = float(text)
449
+ except ValueError:
450
+ value = np.nan
451
+ elif ptypes.is_datetime64_any_dtype(series.dtype):
452
+ value = pd.to_datetime(text, errors="coerce")
453
+ if ptypes.is_integer_dtype(self._df[column].dtype):
454
+ if isinstance(value, float) and not math.isnan(value) and value.is_integer():
455
+ value = int(value)
456
+ elif isinstance(value, float):
457
+ self._df[column] = self._df[column].astype(float)
458
+ self._df.at[row_id, column] = value
459
+ changed = True
460
+ if changed:
461
+ self.recompute_formulas()
462
+ self.modified = True
463
+
464
+ def replace_column(self, name: str, values: pd.Series | Sequence[Any]) -> None:
465
+ if name not in self._df.columns:
466
+ raise KeyError(name)
467
+ if isinstance(values, pd.Series):
468
+ if len(values) != len(self._df):
469
+ raise ValueError(
470
+ f"Column '{name}' replacement has {len(values)} values but the table has {len(self._df)} rows."
471
+ )
472
+ if values.index.equals(self._df.index):
473
+ series = values
474
+ else:
475
+ series = pd.Series(values.to_numpy(), index=self._df.index)
476
+ else:
477
+ items = list(values)
478
+ if len(items) != len(self._df):
479
+ raise ValueError(
480
+ f"Column '{name}' replacement has {len(items)} values but the table has {len(self._df)} rows."
481
+ )
482
+ series = pd.Series(items, index=self._df.index)
483
+ self._df[name] = series
484
+ self.specs[name].data_type = _infer_data_type(self._df[name])
485
+ self.specs[name].modeling_type = _infer_modeling_type(self._df[name])
486
+ self.modified = True
487
+
488
+ def drop_columns(self, columns: Iterable[str]) -> None:
489
+ from statstudio.core.formulas import formula_references_column
490
+
491
+ columns = [c for c in columns if c in self._df.columns]
492
+ self._df = self._df.drop(columns=columns)
493
+ for column in columns:
494
+ self.specs.pop(column, None)
495
+ self.hidden_columns.discard(column)
496
+ for name, spec in self.specs.items():
497
+ if spec.formula and any(formula_references_column(spec.formula, column) for column in columns):
498
+ spec.formula = None
499
+ self.formula_errors.pop(name, None)
500
+ if self.row_filter and any(formula_references_column(self.row_filter, column) for column in columns):
501
+ self.row_filter = None
502
+ self.modified = True
503
+
504
+ def rename_column(self, old: str, new: str) -> None:
505
+ if old not in self._df.columns:
506
+ raise KeyError(old)
507
+ new = str(new).strip()
508
+ if not new:
509
+ raise ValueError("Column name cannot be empty.")
510
+ if new in self._df.columns and new != old:
511
+ raise ValueError(f"Column {new!r} already exists.")
512
+ from statstudio.core.formulas import rename_column_in_formula
513
+
514
+ self._df = self._df.rename(columns={old: new})
515
+ spec = self.specs.pop(old)
516
+ spec.name = new
517
+ self.specs[new] = spec
518
+ for column_spec in self.specs.values():
519
+ if column_spec.formula:
520
+ column_spec.formula = rename_column_in_formula(column_spec.formula, old, new)
521
+ if self.row_filter:
522
+ self.row_filter = rename_column_in_formula(self.row_filter, old, new)
523
+ if old in self.hidden_columns:
524
+ self.hidden_columns.discard(old)
525
+ self.hidden_columns.add(new)
526
+ self.modified = True
527
+
528
+ def set_excluded(self, row_ids: Iterable[Any], excluded: bool = True) -> None:
529
+ ids = set(row_ids)
530
+ if excluded:
531
+ self.excluded_rows.update(ids)
532
+ else:
533
+ self.excluded_rows.difference_update(ids)
534
+ self.modified = True
535
+
536
+ def clear_exclusions(self) -> None:
537
+ self.excluded_rows.clear()
538
+ self.modified = True
539
+
540
+ # ---------------------------------------------------------- row states
541
+ def set_hidden(self, row_ids: Iterable[Any], hidden: bool = True) -> None:
542
+ ids = set(row_ids)
543
+ if hidden:
544
+ self.hidden_rows.update(ids)
545
+ else:
546
+ self.hidden_rows.difference_update(ids)
547
+ self.modified = True
548
+
549
+ def set_labels(self, row_ids: Iterable[Any], label: str) -> None:
550
+ for row_id in row_ids:
551
+ if label:
552
+ self.row_labels[row_id] = str(label)
553
+ else:
554
+ self.row_labels.pop(row_id, None)
555
+ self.modified = True
556
+
557
+ def set_colors(self, row_ids: Iterable[Any], color: str) -> None:
558
+ for row_id in row_ids:
559
+ if color:
560
+ self.row_colors[row_id] = str(color)
561
+ else:
562
+ self.row_colors.pop(row_id, None)
563
+ self.modified = True
564
+
565
+ def set_markers(self, row_ids: Iterable[Any], marker: str) -> None:
566
+ for row_id in row_ids:
567
+ if marker:
568
+ self.row_markers[row_id] = str(marker)
569
+ else:
570
+ self.row_markers.pop(row_id, None)
571
+ self.modified = True
572
+
573
+ def clear_row_states(self) -> None:
574
+ self.excluded_rows.clear()
575
+ self.hidden_rows.clear()
576
+ self.row_labels.clear()
577
+ self.row_colors.clear()
578
+ self.row_markers.clear()
579
+ self.modified = True
580
+
581
+ def row_state(self, row_id: Any) -> dict[str, Any]:
582
+ return {
583
+ "hidden": row_id in self.hidden_rows,
584
+ "excluded": row_id in self.excluded_rows,
585
+ "label": self.row_labels.get(row_id, ""),
586
+ "color": self.row_colors.get(row_id, ""),
587
+ "marker": self.row_markers.get(row_id, ""),
588
+ }
589
+
590
+ def prune_row_states(self) -> None:
591
+ """Drop row-state entries whose rows no longer exist."""
592
+ valid = set(self._df.index)
593
+ self.excluded_rows.intersection_update(valid)
594
+ self.hidden_rows.intersection_update(valid)
595
+ for mapping in (self.row_labels, self.row_colors, self.row_markers):
596
+ for key in [k for k in mapping if k not in valid]:
597
+ del mapping[key]
598
+
599
+ # ------------------------------------------------------------- formulas
600
+ def recompute_formulas(self) -> bool:
601
+ """Recalculate formula columns in dependency order. Returns True if anything changed."""
602
+ from statstudio.core.formulas import FormulaError, find_formula_cycles, formula_evaluation_order, formula_to_series
603
+
604
+ formula_columns = {c: s for c, s in self.specs.items() if s.formula and c in self._df.columns}
605
+ if not formula_columns:
606
+ return False
607
+ changed = False
608
+ cyclic: set[str] = set()
609
+ for cycle in find_formula_cycles(formula_columns):
610
+ message = "Circular formula reference: " + " -> ".join([*cycle, cycle[0]])
611
+ for column in cycle:
612
+ cyclic.add(column)
613
+ self.formula_errors[column] = message
614
+ if not self._df[column].isna().all():
615
+ self._df[column] = np.nan
616
+ changed = True
617
+ for column in formula_evaluation_order(formula_columns):
618
+ if column in cyclic:
619
+ continue
620
+ expression = self.specs[column].formula
621
+ if not expression:
622
+ continue
623
+ try:
624
+ series = formula_to_series(self._source_frame(), expression, name=column)
625
+ except FormulaError as exc:
626
+ self.formula_errors[column] = str(exc)
627
+ if not self._df[column].isna().all():
628
+ self._df[column] = np.nan
629
+ changed = True
630
+ continue
631
+ else:
632
+ self.formula_errors.pop(column, None)
633
+ series = series.reindex(self._df.index)
634
+ if not self._df[column].equals(series):
635
+ self._df[column] = series
636
+ changed = True
637
+ if changed:
638
+ self.modified = True
639
+ return changed
640
+
641
+ def copy_rows(self, name: str | None = None) -> "DataTable":
642
+ return self.copy(name=name)
643
+
644
+ def copy(self, name: str | None = None) -> "DataTable":
645
+ return DataTable(
646
+ self._df.copy(),
647
+ name=name or self.name,
648
+ source=self.source,
649
+ specs={k: ColumnSpec.from_dict(v.to_dict()) for k, v in self.specs.items()},
650
+ metadata=dict(self.metadata),
651
+ row_filter=self.row_filter,
652
+ sort_spec=list(self.sort_spec),
653
+ excluded_rows=set(self.excluded_rows),
654
+ hidden_columns=set(self.hidden_columns),
655
+ hidden_rows=set(self.hidden_rows),
656
+ row_labels=dict(self.row_labels),
657
+ row_colors=dict(self.row_colors),
658
+ row_markers=dict(self.row_markers),
659
+ scripts=list(self.scripts),
660
+ formula_errors=dict(self.formula_errors),
661
+ )
662
+
663
+ def subset(self, rows: pd.Series | np.ndarray | None = None, columns: Sequence[str] | None = None, name: str | None = None) -> "DataTable":
664
+ frame = self.analysis_df(include_excluded=True)
665
+ if rows is not None:
666
+ frame = frame.loc[rows]
667
+ if columns is not None:
668
+ frame = frame.loc[:, list(columns)]
669
+ result = DataTable(
670
+ frame.reset_index(drop=True),
671
+ name=name or f"{self.name} Subset",
672
+ source=f"Subset of {self.name}",
673
+ metadata=dict(self.metadata),
674
+ )
675
+ return result
676
+
677
+ def to_payload(self, data_file: str | None = None) -> dict[str, Any]:
678
+ return {
679
+ "name": self.name,
680
+ "source": self.source,
681
+ "data_file": data_file,
682
+ "specs": {k: v.to_dict() for k, v in self.specs.items()},
683
+ "metadata": self.metadata,
684
+ "row_filter": self.row_filter,
685
+ "sort_spec": self.sort_spec,
686
+ "excluded_rows": list(self.excluded_rows),
687
+ "hidden_columns": sorted(self.hidden_columns),
688
+ "hidden_rows": list(self.hidden_rows),
689
+ "row_labels": {str(k): v for k, v in self.row_labels.items()},
690
+ "row_colors": {str(k): v for k, v in self.row_colors.items()},
691
+ "row_markers": {str(k): v for k, v in self.row_markers.items()},
692
+ "scripts": [script.to_dict() for script in self.scripts],
693
+ "formula_errors": self.formula_errors,
694
+ }
695
+
696
+ @classmethod
697
+ def from_payload(cls, df: pd.DataFrame, payload: dict[str, Any]) -> "DataTable":
698
+ specs = {k: ColumnSpec.from_dict(v) for k, v in payload.get("specs", {}).items()}
699
+ index_map = {str(row_id): row_id for row_id in df.index}
700
+
701
+ def restore_ids(values: Iterable[Any]) -> list[Any]:
702
+ return [index_map.get(str(v), v) for v in values or []]
703
+
704
+ def restore_map(mapping: dict[str, Any]) -> dict[Any, Any]:
705
+ return {index_map.get(str(k), k): v for k, v in (mapping or {}).items()}
706
+
707
+ return cls(
708
+ df,
709
+ name=payload.get("name", "Table"),
710
+ source=payload.get("source"),
711
+ specs=specs,
712
+ metadata=payload.get("metadata") or {},
713
+ row_filter=payload.get("row_filter"),
714
+ sort_spec=[tuple(v) for v in payload.get("sort_spec", [])],
715
+ excluded_rows=restore_ids(payload.get("excluded_rows") or []),
716
+ hidden_columns=payload.get("hidden_columns") or [],
717
+ hidden_rows=restore_ids(payload.get("hidden_rows") or []),
718
+ row_labels=restore_map(payload.get("row_labels") or {}),
719
+ row_colors=restore_map(payload.get("row_colors") or {}),
720
+ row_markers=restore_map(payload.get("row_markers") or {}),
721
+ scripts=[TableScript.from_dict(item) for item in payload.get("scripts", [])],
722
+ formula_errors=payload.get("formula_errors") or {},
723
+ )
724
+
725
+
726
+ def ensure_unique_name(name: str, existing: Iterable[str]) -> str:
727
+ existing = set(existing)
728
+ if name not in existing:
729
+ return name
730
+ index = 2
731
+ while f"{name} {index}" in existing:
732
+ index += 1
733
+ return f"{name} {index}"
734
+
735
+
736
+ def restore_table(target: "DataTable", snapshot: "DataTable") -> None:
737
+ target._df = snapshot._df.copy()
738
+ target.name = snapshot.name
739
+ target.source = snapshot.source
740
+ target.specs = {k: ColumnSpec.from_dict(v.to_dict()) for k, v in snapshot.specs.items()}
741
+ target.metadata = dict(snapshot.metadata)
742
+ target.row_filter = snapshot.row_filter
743
+ target.sort_spec = list(snapshot.sort_spec)
744
+ target.excluded_rows = set(snapshot.excluded_rows)
745
+ target.hidden_columns = set(snapshot.hidden_columns)
746
+ target.hidden_rows = set(snapshot.hidden_rows)
747
+ target.row_labels = dict(snapshot.row_labels)
748
+ target.row_colors = dict(snapshot.row_colors)
749
+ target.row_markers = dict(snapshot.row_markers)
750
+ target.scripts = [TableScript.from_dict(script.to_dict()) for script in snapshot.scripts]
751
+ target.formula_errors = dict(snapshot.formula_errors)
752
+ target.modified = snapshot.modified
753
+
754
+
755
+ def apply_modeling_types(df: pd.DataFrame, specs: dict[str, ColumnSpec]) -> pd.DataFrame:
756
+ """Coerce columns marked nominal/ordinal so analyses treat them as categorical."""
757
+ frame = df.copy()
758
+ for column, spec in specs.items():
759
+ if column not in frame.columns:
760
+ continue
761
+ if spec.modeling_type in {"nominal", "ordinal"}:
762
+ series = frame[column]
763
+ if ptypes.is_numeric_dtype(series.dtype) and not ptypes.is_bool_dtype(series.dtype):
764
+ def label(value: Any) -> Any:
765
+ if pd.isna(value):
766
+ return None
767
+ if isinstance(value, (float, np.floating)) and float(value).is_integer():
768
+ return str(int(value))
769
+ return str(value)
770
+
771
+ frame[column] = series.map(label).astype(object)
772
+ return frame
773
+
774
+
775
+ def add_rows(target: "DataTable", count: int) -> None:
776
+ if count <= 0:
777
+ return
778
+ start = len(target._df)
779
+ new_index = pd.RangeIndex(start, start + count)
780
+ if len(target._df) and new_index.intersection(target._df.index).size:
781
+ numeric_index = [int(v) for v in target._df.index if isinstance(v, (int, np.integer))]
782
+ start = max(numeric_index, default=start) + 1
783
+ new_index = pd.RangeIndex(start, start + count)
784
+ data: dict[str, pd.Series] = {}
785
+ for column_name in target._df.columns:
786
+ series = target._df[column_name]
787
+ if ptypes.is_numeric_dtype(series.dtype) and not ptypes.is_bool_dtype(series.dtype):
788
+ data[column_name] = pd.Series(np.nan, index=new_index, dtype=float)
789
+ elif ptypes.is_datetime64_any_dtype(series.dtype):
790
+ data[column_name] = pd.Series(pd.NaT, index=new_index, dtype=series.dtype)
791
+ else:
792
+ data[column_name] = pd.Series(None, index=new_index, dtype=object)
793
+ blank = pd.DataFrame(data, index=new_index)
794
+ target._df = pd.concat([target._df, blank])
795
+ target.recompute_formulas()
796
+ target.modified = True