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,605 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import operator
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Callable, Iterable
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FormulaError(ValueError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _series_or_scalar(value: Any, index: pd.Index) -> Any:
|
|
17
|
+
if isinstance(value, pd.Series):
|
|
18
|
+
return value
|
|
19
|
+
if isinstance(value, np.ndarray):
|
|
20
|
+
if value.ndim == 1 and len(value) == len(index):
|
|
21
|
+
return pd.Series(value, index=index)
|
|
22
|
+
return value
|
|
23
|
+
if isinstance(value, pd.Index):
|
|
24
|
+
return pd.Series(value, index=index)
|
|
25
|
+
return value
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_series(value: Any) -> bool:
|
|
29
|
+
return isinstance(value, pd.Series)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _logical_and(left: Any, right: Any) -> Any:
|
|
33
|
+
if _is_series(left) or _is_series(right):
|
|
34
|
+
return left & right
|
|
35
|
+
return bool(left) and bool(right)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _logical_or(left: Any, right: Any) -> Any:
|
|
39
|
+
if _is_series(left) or _is_series(right):
|
|
40
|
+
return left | right
|
|
41
|
+
return bool(left) or bool(right)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _logical_not(value: Any) -> Any:
|
|
45
|
+
if _is_series(value):
|
|
46
|
+
if pd.api.types.is_bool_dtype(value.dtype) or pd.api.types.is_numeric_dtype(value.dtype):
|
|
47
|
+
return value.map(lambda item: np.nan if pd.isna(item) else not bool(item))
|
|
48
|
+
try:
|
|
49
|
+
return value.map(lambda item: np.nan if pd.isna(item) else not bool(item))
|
|
50
|
+
except (TypeError, ValueError) as exc:
|
|
51
|
+
raise FormulaError("Cannot apply 'not' to this column.") from exc
|
|
52
|
+
if pd.isna(value):
|
|
53
|
+
return np.nan
|
|
54
|
+
return not bool(value)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _safe_binop(function: Callable[[Any, Any], Any], left: Any, right: Any) -> Any:
|
|
58
|
+
series = _is_series(left) or _is_series(right)
|
|
59
|
+
try:
|
|
60
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
61
|
+
result = function(left, right)
|
|
62
|
+
except ZeroDivisionError:
|
|
63
|
+
if series:
|
|
64
|
+
index = left.index if _is_series(left) else right.index
|
|
65
|
+
return pd.Series(np.nan, index=index, dtype=float)
|
|
66
|
+
return np.nan
|
|
67
|
+
except (TypeError, ValueError) as exc:
|
|
68
|
+
raise FormulaError(f"Invalid arithmetic: {exc}") from exc
|
|
69
|
+
if series and isinstance(result, pd.Series):
|
|
70
|
+
return result.replace([np.inf, -np.inf], np.nan)
|
|
71
|
+
if isinstance(result, (float, np.floating)) and np.isinf(result):
|
|
72
|
+
return np.nan
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _where(condition: Any, when_true: Any, when_false: Any) -> Any:
|
|
77
|
+
if _is_series(condition):
|
|
78
|
+
if not _is_series(when_true):
|
|
79
|
+
when_true = pd.Series(when_true, index=condition.index)
|
|
80
|
+
if not _is_series(when_false):
|
|
81
|
+
when_false = pd.Series(when_false, index=condition.index)
|
|
82
|
+
return when_true.where(condition, when_false)
|
|
83
|
+
return when_true if condition else when_false
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _safe_round(value: Any, decimals: int = 0) -> Any:
|
|
87
|
+
return np.round(value, decimals)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _zscore(value: Any) -> Any:
|
|
91
|
+
if _is_series(value):
|
|
92
|
+
std = value.std(ddof=1)
|
|
93
|
+
if not std or pd.isna(std):
|
|
94
|
+
return pd.Series(np.nan, index=value.index)
|
|
95
|
+
return (value - value.mean()) / std
|
|
96
|
+
return 0.0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _normalize(value: Any) -> Any:
|
|
100
|
+
if _is_series(value):
|
|
101
|
+
minimum, maximum = value.min(), value.max()
|
|
102
|
+
if maximum == minimum:
|
|
103
|
+
return pd.Series(np.nan, index=value.index)
|
|
104
|
+
return (value - minimum) / (maximum - minimum)
|
|
105
|
+
return 0.0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _rank(value: Any) -> Any:
|
|
109
|
+
if _is_series(value):
|
|
110
|
+
return value.rank(method="average")
|
|
111
|
+
return 1.0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _is_missing_scalar(value: Any) -> bool:
|
|
115
|
+
try:
|
|
116
|
+
result = pd.isna(value)
|
|
117
|
+
except (TypeError, ValueError):
|
|
118
|
+
return False
|
|
119
|
+
return bool(result) if np.isscalar(result) else False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _concat(*values: Any) -> Any:
|
|
123
|
+
index = next((v.index for v in values if _is_series(v)), None)
|
|
124
|
+
if index is None:
|
|
125
|
+
if any(_is_missing_scalar(value) for value in values):
|
|
126
|
+
return np.nan
|
|
127
|
+
return "".join(str(value) for value in values)
|
|
128
|
+
frames: list[pd.Series] = []
|
|
129
|
+
for value in values:
|
|
130
|
+
if _is_series(value):
|
|
131
|
+
frames.append(value.reindex(index).astype("string"))
|
|
132
|
+
elif _is_missing_scalar(value):
|
|
133
|
+
frames.append(pd.Series([pd.NA] * len(index), index=index, dtype="string"))
|
|
134
|
+
else:
|
|
135
|
+
frames.append(pd.Series([str(value)] * len(index), index=index, dtype="string"))
|
|
136
|
+
result = frames[0]
|
|
137
|
+
for frame in frames[1:]:
|
|
138
|
+
result = result + frame
|
|
139
|
+
return result
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _contains(value: Any, pattern: str, case: bool = True, regex: bool = False) -> Any:
|
|
143
|
+
if _is_series(value):
|
|
144
|
+
return value.astype("string").str.contains(str(pattern), case=case, regex=regex, na=False)
|
|
145
|
+
if _is_missing_scalar(value):
|
|
146
|
+
return False
|
|
147
|
+
text = str(value)
|
|
148
|
+
needle = str(pattern)
|
|
149
|
+
if regex:
|
|
150
|
+
return re.search(needle, text, 0 if case else re.IGNORECASE) is not None
|
|
151
|
+
if case:
|
|
152
|
+
return needle in text
|
|
153
|
+
return needle.lower() in text.lower()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _starts_with(value: Any, prefix: str, case: bool = True) -> Any:
|
|
157
|
+
if _is_series(value):
|
|
158
|
+
return value.astype("string").str.contains(rf"^{re.escape(str(prefix))}", case=case, regex=True, na=False)
|
|
159
|
+
if _is_missing_scalar(value):
|
|
160
|
+
return False
|
|
161
|
+
text, needle = str(value), str(prefix)
|
|
162
|
+
if case:
|
|
163
|
+
return text.startswith(needle)
|
|
164
|
+
return text.lower().startswith(needle.lower())
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _ends_with(value: Any, suffix: str, case: bool = True) -> Any:
|
|
168
|
+
if _is_series(value):
|
|
169
|
+
return value.astype("string").str.contains(rf"{re.escape(str(suffix))}$", case=case, regex=True, na=False)
|
|
170
|
+
if _is_missing_scalar(value):
|
|
171
|
+
return False
|
|
172
|
+
text, needle = str(value), str(suffix)
|
|
173
|
+
if case:
|
|
174
|
+
return text.endswith(needle)
|
|
175
|
+
return text.lower().endswith(needle.lower())
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _lower(value: Any) -> Any:
|
|
179
|
+
if _is_series(value):
|
|
180
|
+
return value.astype("string").str.lower()
|
|
181
|
+
return np.nan if _is_missing_scalar(value) else str(value).lower()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _upper(value: Any) -> Any:
|
|
185
|
+
if _is_series(value):
|
|
186
|
+
return value.astype("string").str.upper()
|
|
187
|
+
return np.nan if _is_missing_scalar(value) else str(value).upper()
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _strip(value: Any) -> Any:
|
|
191
|
+
if _is_series(value):
|
|
192
|
+
return value.astype("string").str.strip()
|
|
193
|
+
return np.nan if _is_missing_scalar(value) else str(value).strip()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _replace(value: Any, old: str, new: str) -> Any:
|
|
197
|
+
if _is_series(value):
|
|
198
|
+
return value.astype("string").str.replace(str(old), str(new), regex=False)
|
|
199
|
+
return np.nan if _is_missing_scalar(value) else str(value).replace(str(old), str(new))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _if_missing(value: Any, replacement: Any) -> Any:
|
|
203
|
+
if _is_series(value):
|
|
204
|
+
return value.fillna(replacement)
|
|
205
|
+
return replacement if pd.isna(value) else value
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _functions() -> dict[str, Callable[..., Any]]:
|
|
209
|
+
return {
|
|
210
|
+
"col": lambda name: None,
|
|
211
|
+
"Q": lambda name: None,
|
|
212
|
+
"where": _where,
|
|
213
|
+
"ifelse": _where,
|
|
214
|
+
"if_missing": _if_missing,
|
|
215
|
+
"is_missing": pd.isna,
|
|
216
|
+
"isnull": pd.isna,
|
|
217
|
+
"isna": pd.isna,
|
|
218
|
+
"notnull": pd.notna,
|
|
219
|
+
"notmissing": pd.notna,
|
|
220
|
+
"abs": np.abs,
|
|
221
|
+
"sqrt": np.sqrt,
|
|
222
|
+
"log": np.log,
|
|
223
|
+
"ln": np.log,
|
|
224
|
+
"log10": np.log10,
|
|
225
|
+
"log2": np.log2,
|
|
226
|
+
"pow": np.power,
|
|
227
|
+
"exp": np.exp,
|
|
228
|
+
"sin": np.sin,
|
|
229
|
+
"cos": np.cos,
|
|
230
|
+
"tan": np.tan,
|
|
231
|
+
"floor": np.floor,
|
|
232
|
+
"ceil": np.ceil,
|
|
233
|
+
"round": _safe_round,
|
|
234
|
+
"minimum": np.minimum,
|
|
235
|
+
"maximum": np.maximum,
|
|
236
|
+
"min": np.minimum,
|
|
237
|
+
"max": np.maximum,
|
|
238
|
+
"mean": lambda v: v.mean() if _is_series(v) else v,
|
|
239
|
+
"median": lambda v: v.median() if _is_series(v) else v,
|
|
240
|
+
"std": lambda v: v.std() if _is_series(v) else 0.0,
|
|
241
|
+
"var": lambda v: v.var() if _is_series(v) else 0.0,
|
|
242
|
+
"sum": lambda v: v.sum() if _is_series(v) else v,
|
|
243
|
+
"count": lambda v: v.count() if _is_series(v) else int(not pd.isna(v)),
|
|
244
|
+
"quantile": lambda v, q: v.quantile(q) if _is_series(v) else v,
|
|
245
|
+
"zscore": _zscore,
|
|
246
|
+
"normalize": _normalize,
|
|
247
|
+
"rank": _rank,
|
|
248
|
+
"concat": _concat,
|
|
249
|
+
"lower": _lower,
|
|
250
|
+
"upper": _upper,
|
|
251
|
+
"strip": _strip,
|
|
252
|
+
"contains": _contains,
|
|
253
|
+
"startswith": _starts_with,
|
|
254
|
+
"endswith": _ends_with,
|
|
255
|
+
"replace": _replace,
|
|
256
|
+
"year": lambda v: pd.to_datetime(v).dt.year if _is_series(v) else pd.to_datetime(v).year,
|
|
257
|
+
"month": lambda v: pd.to_datetime(v).dt.month if _is_series(v) else pd.to_datetime(v).month,
|
|
258
|
+
"day": lambda v: pd.to_datetime(v).dt.day if _is_series(v) else pd.to_datetime(v).day,
|
|
259
|
+
"today": pd.Timestamp.today,
|
|
260
|
+
"row": lambda: None,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
_BINOPS = {
|
|
265
|
+
ast.Add: operator.add,
|
|
266
|
+
ast.Sub: operator.sub,
|
|
267
|
+
ast.Mult: operator.mul,
|
|
268
|
+
ast.Div: operator.truediv,
|
|
269
|
+
ast.FloorDiv: operator.floordiv,
|
|
270
|
+
ast.Mod: operator.mod,
|
|
271
|
+
ast.Pow: operator.pow,
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
_ALLOWED_KEYWORDS = {
|
|
275
|
+
"contains": {"case", "regex"},
|
|
276
|
+
"startswith": {"case"},
|
|
277
|
+
"endswith": {"case"},
|
|
278
|
+
"round": {"decimals"},
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
_CMPOPS = {
|
|
282
|
+
ast.Eq: operator.eq,
|
|
283
|
+
ast.NotEq: operator.ne,
|
|
284
|
+
ast.Lt: operator.lt,
|
|
285
|
+
ast.LtE: operator.le,
|
|
286
|
+
ast.Gt: operator.gt,
|
|
287
|
+
ast.GtE: operator.ge,
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class _Evaluator:
|
|
292
|
+
def __init__(self, df: pd.DataFrame) -> None:
|
|
293
|
+
self.df = df
|
|
294
|
+
self.functions = _functions()
|
|
295
|
+
self.functions["col"] = self._column
|
|
296
|
+
self.functions["Q"] = self._column
|
|
297
|
+
self.functions["row"] = lambda: pd.Series(np.arange(1, len(self.df) + 1), index=self.df.index)
|
|
298
|
+
|
|
299
|
+
def _column(self, name: str) -> pd.Series:
|
|
300
|
+
if name not in self.df.columns:
|
|
301
|
+
raise FormulaError(f"Unknown column: {name!r}")
|
|
302
|
+
return self.df[name]
|
|
303
|
+
|
|
304
|
+
def evaluate(self, expression: str) -> Any:
|
|
305
|
+
try:
|
|
306
|
+
tree = ast.parse(expression, mode="eval")
|
|
307
|
+
except SyntaxError as exc:
|
|
308
|
+
raise FormulaError(f"Invalid formula: {exc.msg}") from exc
|
|
309
|
+
return self.visit(tree.body)
|
|
310
|
+
|
|
311
|
+
def visit(self, node: ast.AST) -> Any:
|
|
312
|
+
method = getattr(self, f"visit_{type(node).__name__}", None)
|
|
313
|
+
if method is None:
|
|
314
|
+
raise FormulaError(f"Unsupported syntax: {type(node).__name__}")
|
|
315
|
+
return method(node) # type: ignore[no-any-return]
|
|
316
|
+
|
|
317
|
+
def visit_Constant(self, node: ast.Constant) -> Any:
|
|
318
|
+
return node.value
|
|
319
|
+
|
|
320
|
+
def visit_Name(self, node: ast.Name) -> Any:
|
|
321
|
+
if node.id in {"True", "False", "None"}:
|
|
322
|
+
return {"True": True, "False": False, "None": None}[node.id]
|
|
323
|
+
if node.id in self.df.columns:
|
|
324
|
+
return self.df[node.id]
|
|
325
|
+
if node.id in self.functions:
|
|
326
|
+
return self.functions[node.id]
|
|
327
|
+
raise FormulaError(
|
|
328
|
+
f"Unknown name {node.id!r}. Use col(\"name\") for columns that are not valid identifiers."
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def visit_BinOp(self, node: ast.BinOp) -> Any:
|
|
332
|
+
op = _BINOPS.get(type(node.op))
|
|
333
|
+
if op is None:
|
|
334
|
+
raise FormulaError("Unsupported operator.")
|
|
335
|
+
return _safe_binop(op, self.visit(node.left), self.visit(node.right))
|
|
336
|
+
|
|
337
|
+
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
|
|
338
|
+
value = self.visit(node.operand)
|
|
339
|
+
if isinstance(node.op, ast.USub):
|
|
340
|
+
return -value
|
|
341
|
+
if isinstance(node.op, ast.UAdd):
|
|
342
|
+
return value
|
|
343
|
+
if isinstance(node.op, ast.Not):
|
|
344
|
+
return _logical_not(value)
|
|
345
|
+
raise FormulaError("Unsupported unary operator.")
|
|
346
|
+
|
|
347
|
+
def visit_BoolOp(self, node: ast.BoolOp) -> Any:
|
|
348
|
+
result = self.visit(node.values[0])
|
|
349
|
+
for operand in node.values[1:]:
|
|
350
|
+
if not _is_series(result):
|
|
351
|
+
if isinstance(node.op, ast.And) and not bool(result):
|
|
352
|
+
return False
|
|
353
|
+
if isinstance(node.op, ast.Or) and bool(result):
|
|
354
|
+
return True
|
|
355
|
+
value = self.visit(operand)
|
|
356
|
+
if isinstance(node.op, ast.And):
|
|
357
|
+
result = _logical_and(result, value)
|
|
358
|
+
elif isinstance(node.op, ast.Or):
|
|
359
|
+
result = _logical_or(result, value)
|
|
360
|
+
else:
|
|
361
|
+
raise FormulaError("Unsupported boolean operator.")
|
|
362
|
+
return result
|
|
363
|
+
|
|
364
|
+
def visit_Compare(self, node: ast.Compare) -> Any:
|
|
365
|
+
left = self.visit(node.left)
|
|
366
|
+
result: Any = True
|
|
367
|
+
for op_node, comparator_node in zip(node.ops, node.comparators):
|
|
368
|
+
right = self.visit(comparator_node)
|
|
369
|
+
if isinstance(op_node, ast.In):
|
|
370
|
+
if _is_series(left):
|
|
371
|
+
piece = left.isin(list(right))
|
|
372
|
+
elif _is_series(right):
|
|
373
|
+
piece = right.isin([left])
|
|
374
|
+
else:
|
|
375
|
+
piece = left in right
|
|
376
|
+
elif isinstance(op_node, ast.NotIn):
|
|
377
|
+
if _is_series(left):
|
|
378
|
+
piece = ~left.isin(list(right))
|
|
379
|
+
elif _is_series(right):
|
|
380
|
+
piece = ~right.isin([left])
|
|
381
|
+
else:
|
|
382
|
+
piece = left not in right
|
|
383
|
+
elif isinstance(op_node, (ast.Is, ast.IsNot)):
|
|
384
|
+
if right is None:
|
|
385
|
+
piece = pd.isna(left)
|
|
386
|
+
elif left is None:
|
|
387
|
+
piece = pd.isna(right)
|
|
388
|
+
else:
|
|
389
|
+
piece = (left is right)
|
|
390
|
+
if isinstance(op_node, ast.IsNot):
|
|
391
|
+
piece = _logical_not(piece) if not _is_series(piece) else ~piece
|
|
392
|
+
else:
|
|
393
|
+
op = _CMPOPS.get(type(op_node))
|
|
394
|
+
if op is None:
|
|
395
|
+
raise FormulaError("Unsupported comparison.")
|
|
396
|
+
piece = op(left, right)
|
|
397
|
+
result = _logical_and(result, piece)
|
|
398
|
+
left = right
|
|
399
|
+
return result
|
|
400
|
+
|
|
401
|
+
def visit_IfExp(self, node: ast.IfExp) -> Any:
|
|
402
|
+
return _where(self.visit(node.test), self.visit(node.body), self.visit(node.orelse))
|
|
403
|
+
|
|
404
|
+
def visit_Call(self, node: ast.Call) -> Any:
|
|
405
|
+
if not isinstance(node.func, ast.Name):
|
|
406
|
+
raise FormulaError("Only named functions are allowed.")
|
|
407
|
+
function = self.functions.get(node.func.id)
|
|
408
|
+
if function is None:
|
|
409
|
+
raise FormulaError(f"Unknown function: {node.func.id!r}")
|
|
410
|
+
allowed = _ALLOWED_KEYWORDS.get(node.func.id, set())
|
|
411
|
+
keywords: dict[str, Any] = {}
|
|
412
|
+
for keyword in node.keywords:
|
|
413
|
+
if keyword.arg is None or keyword.arg not in allowed:
|
|
414
|
+
name = keyword.arg or "**"
|
|
415
|
+
raise FormulaError(f"Keyword argument {name!r} is not supported for {node.func.id}.")
|
|
416
|
+
keywords[keyword.arg] = self.visit(keyword.value)
|
|
417
|
+
args = [self.visit(arg) for arg in node.args]
|
|
418
|
+
try:
|
|
419
|
+
result = function(*args, **keywords)
|
|
420
|
+
except FormulaError:
|
|
421
|
+
raise
|
|
422
|
+
except Exception as exc:
|
|
423
|
+
raise FormulaError(f"Error calling {node.func.id}: {exc}") from exc
|
|
424
|
+
return _series_or_scalar(result, self.df.index)
|
|
425
|
+
|
|
426
|
+
def visit_Attribute(self, node: ast.Attribute) -> Any:
|
|
427
|
+
raise FormulaError("Attribute access is not allowed in formulas.")
|
|
428
|
+
|
|
429
|
+
def visit_Subscript(self, node: ast.Subscript) -> Any:
|
|
430
|
+
raise FormulaError("Subscript access is not allowed in formulas.")
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def evaluate_formula(df: pd.DataFrame, expression: str) -> Any:
|
|
434
|
+
if not expression or not expression.strip():
|
|
435
|
+
raise FormulaError("Formula is empty.")
|
|
436
|
+
evaluator = _Evaluator(df)
|
|
437
|
+
result = evaluator.evaluate(expression)
|
|
438
|
+
result = _series_or_scalar(result, df.index)
|
|
439
|
+
if isinstance(result, np.ndarray) and result.ndim != 1:
|
|
440
|
+
raise FormulaError("Formula must produce a single column.")
|
|
441
|
+
return result
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def formula_to_series(df: pd.DataFrame, expression: str, name: str | None = None) -> pd.Series:
|
|
445
|
+
result = evaluate_formula(df, expression)
|
|
446
|
+
if isinstance(result, pd.Series):
|
|
447
|
+
series = result
|
|
448
|
+
else:
|
|
449
|
+
series = pd.Series([result] * len(df), index=df.index)
|
|
450
|
+
if name:
|
|
451
|
+
series = series.copy()
|
|
452
|
+
series.name = name
|
|
453
|
+
return series
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def rename_column_in_formula(expression: str, old: str, new: str) -> str:
|
|
457
|
+
"""Rewrite references to a renamed column in a formula, preserving other text."""
|
|
458
|
+
try:
|
|
459
|
+
tree = ast.parse(expression, mode="eval")
|
|
460
|
+
except SyntaxError:
|
|
461
|
+
return expression
|
|
462
|
+
|
|
463
|
+
class _Renamer(ast.NodeTransformer):
|
|
464
|
+
def visit_Name(self, node: ast.Name) -> ast.AST:
|
|
465
|
+
if node.id == old:
|
|
466
|
+
return ast.copy_location(ast.Name(id=new, ctx=node.ctx), node)
|
|
467
|
+
return node
|
|
468
|
+
|
|
469
|
+
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
470
|
+
node.args = [self.visit(argument) for argument in node.args]
|
|
471
|
+
node.keywords = [self.visit(keyword) for keyword in node.keywords]
|
|
472
|
+
if isinstance(node.func, ast.Name) and node.func.id in {"col", "Q"} and node.args:
|
|
473
|
+
argument = node.args[0]
|
|
474
|
+
if isinstance(argument, ast.Constant) and argument.value == old:
|
|
475
|
+
node.args[0] = ast.copy_location(ast.Constant(value=new), argument)
|
|
476
|
+
elif not isinstance(node.func, ast.Name):
|
|
477
|
+
node.func = self.visit(node.func)
|
|
478
|
+
return node
|
|
479
|
+
|
|
480
|
+
try:
|
|
481
|
+
renamed = _Renamer().visit(tree)
|
|
482
|
+
ast.fix_missing_locations(renamed)
|
|
483
|
+
return ast.unparse(renamed.body)
|
|
484
|
+
except Exception:
|
|
485
|
+
return expression
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def formula_references_column(expression: str, column: str) -> bool:
|
|
489
|
+
try:
|
|
490
|
+
tree = ast.parse(expression, mode="eval")
|
|
491
|
+
except SyntaxError:
|
|
492
|
+
return column in expression
|
|
493
|
+
for node in ast.walk(tree):
|
|
494
|
+
if isinstance(node, ast.Name) and node.id == column:
|
|
495
|
+
return True
|
|
496
|
+
if (
|
|
497
|
+
isinstance(node, ast.Call)
|
|
498
|
+
and isinstance(node.func, ast.Name)
|
|
499
|
+
and node.func.id in {"col", "Q"}
|
|
500
|
+
and node.args
|
|
501
|
+
and isinstance(node.args[0], ast.Constant)
|
|
502
|
+
and node.args[0].value == column
|
|
503
|
+
):
|
|
504
|
+
return True
|
|
505
|
+
return False
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def validate_formula(df: pd.DataFrame, expression: str) -> tuple[bool, str]:
|
|
509
|
+
try:
|
|
510
|
+
result = evaluate_formula(df, expression)
|
|
511
|
+
if isinstance(result, pd.Series):
|
|
512
|
+
return True, f"Valid: {len(result)} rows, {int(result.isna().sum())} missing"
|
|
513
|
+
return True, f"Valid: scalar value {result!r}"
|
|
514
|
+
except Exception as exc:
|
|
515
|
+
return False, str(exc)
|
|
516
|
+
|
|
517
|
+
def formula_dependencies(expression: str, columns: Iterable[str]) -> set[str]:
|
|
518
|
+
"""Return column names referenced by a formula."""
|
|
519
|
+
names = {str(column) for column in columns}
|
|
520
|
+
try:
|
|
521
|
+
tree = ast.parse(expression, mode="eval")
|
|
522
|
+
except SyntaxError:
|
|
523
|
+
return {name for name in names if name in expression}
|
|
524
|
+
call_names: set[str] = set()
|
|
525
|
+
for node in ast.walk(tree):
|
|
526
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
|
527
|
+
call_names.add(node.func.id)
|
|
528
|
+
dependencies: set[str] = set()
|
|
529
|
+
for node in ast.walk(tree):
|
|
530
|
+
if isinstance(node, ast.Name) and node.id in names and node.id not in call_names:
|
|
531
|
+
dependencies.add(node.id)
|
|
532
|
+
elif (
|
|
533
|
+
isinstance(node, ast.Call)
|
|
534
|
+
and isinstance(node.func, ast.Name)
|
|
535
|
+
and node.func.id in {"col", "Q"}
|
|
536
|
+
and node.args
|
|
537
|
+
and isinstance(node.args[0], ast.Constant)
|
|
538
|
+
and str(node.args[0].value) in names
|
|
539
|
+
):
|
|
540
|
+
dependencies.add(str(node.args[0].value))
|
|
541
|
+
return dependencies
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def formula_evaluation_order(specs: dict[str, Any]) -> list[str]:
|
|
545
|
+
"""Topological order for formula columns; cycles are omitted."""
|
|
546
|
+
formula_columns = {name for name, spec in specs.items() if getattr(spec, "formula", None)}
|
|
547
|
+
dependencies = {
|
|
548
|
+
name: formula_dependencies(specs[name].formula, formula_columns) & formula_columns
|
|
549
|
+
for name in formula_columns
|
|
550
|
+
}
|
|
551
|
+
ordered: list[str] = []
|
|
552
|
+
remaining = dict(dependencies)
|
|
553
|
+
while remaining:
|
|
554
|
+
ready = sorted(name for name, deps in remaining.items() if not (deps - set(ordered)))
|
|
555
|
+
if not ready:
|
|
556
|
+
break
|
|
557
|
+
for name in ready:
|
|
558
|
+
ordered.append(name)
|
|
559
|
+
remaining.pop(name, None)
|
|
560
|
+
return ordered
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def find_formula_cycles(specs: dict[str, Any]) -> list[list[str]]:
|
|
564
|
+
"""Return strongly connected components that contain a cycle."""
|
|
565
|
+
formula_columns = {name for name, spec in specs.items() if getattr(spec, "formula", None)}
|
|
566
|
+
dependencies = {
|
|
567
|
+
name: formula_dependencies(specs[name].formula, formula_columns) & formula_columns
|
|
568
|
+
for name in formula_columns
|
|
569
|
+
}
|
|
570
|
+
index = 0
|
|
571
|
+
indices: dict[str, int] = {}
|
|
572
|
+
lowlinks: dict[str, int] = {}
|
|
573
|
+
stack: list[str] = []
|
|
574
|
+
on_stack: set[str] = set()
|
|
575
|
+
cycles: list[list[str]] = []
|
|
576
|
+
|
|
577
|
+
def visit(node: str) -> None:
|
|
578
|
+
nonlocal index
|
|
579
|
+
indices[node] = index
|
|
580
|
+
lowlinks[node] = index
|
|
581
|
+
index += 1
|
|
582
|
+
stack.append(node)
|
|
583
|
+
on_stack.add(node)
|
|
584
|
+
for dependency in sorted(dependencies.get(node, set())):
|
|
585
|
+
if dependency not in indices:
|
|
586
|
+
visit(dependency)
|
|
587
|
+
lowlinks[node] = min(lowlinks[node], lowlinks[dependency])
|
|
588
|
+
elif dependency in on_stack:
|
|
589
|
+
lowlinks[node] = min(lowlinks[node], indices[dependency])
|
|
590
|
+
if lowlinks[node] == indices[node]:
|
|
591
|
+
component: list[str] = []
|
|
592
|
+
while True:
|
|
593
|
+
member = stack.pop()
|
|
594
|
+
on_stack.discard(member)
|
|
595
|
+
component.append(member)
|
|
596
|
+
if member == node:
|
|
597
|
+
break
|
|
598
|
+
if len(component) > 1 or (len(component) == 1 and node in dependencies.get(node, set())):
|
|
599
|
+
cycles.append(sorted(component))
|
|
600
|
+
|
|
601
|
+
for node in sorted(formula_columns):
|
|
602
|
+
if node not in indices:
|
|
603
|
+
visit(node)
|
|
604
|
+
return cycles
|
|
605
|
+
|