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,594 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import inspect
5
+ import math
6
+ from dataclasses import dataclass
7
+ from datetime import date, datetime
8
+ from typing import Any, Sequence
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class AnalysisSpec:
16
+ module: str
17
+ function: str
18
+ data: str = "df"
19
+ exclude: tuple[str, ...] = ()
20
+
21
+
22
+ ANALYSIS_SPECS: dict[str, AnalysisSpec] = {
23
+ "descriptive": AnalysisSpec("descriptive", "describe"),
24
+ "frequency": AnalysisSpec("descriptive", "frequency_table"),
25
+ "grouped_summary": AnalysisSpec("descriptive", "grouped_summary"),
26
+ "t_test_one": AnalysisSpec("hypothesis", "one_sample_t_test"),
27
+ "t_test_two": AnalysisSpec("hypothesis", "two_sample_t_test"),
28
+ "t_test_paired": AnalysisSpec("hypothesis", "paired_t_test"),
29
+ "anova": AnalysisSpec("hypothesis", "anova_oneway"),
30
+ "kruskal": AnalysisSpec("hypothesis", "kruskal_test"),
31
+ "mann_whitney": AnalysisSpec("hypothesis", "mann_whitney_test"),
32
+ "wilcoxon": AnalysisSpec("hypothesis", "wilcoxon_test"),
33
+ "chi_square": AnalysisSpec("hypothesis", "chi_square_test"),
34
+ "proportion": AnalysisSpec("hypothesis", "proportion_test"),
35
+ "normality": AnalysisSpec("hypothesis", "normality_test"),
36
+ "levene": AnalysisSpec("hypothesis", "levene_test"),
37
+ "fit_y_by_x": AnalysisSpec("hypothesis", "fit_y_by_x"),
38
+ "two_way_anova": AnalysisSpec("hypothesis", "two_way_anova"),
39
+ "repeated_measures_anova": AnalysisSpec("hypothesis", "repeated_measures_anova"),
40
+ "contingency": AnalysisSpec("hypothesis", "contingency_table"),
41
+ "posthoc": AnalysisSpec("hypothesis", "posthoc_test"),
42
+ "sign_test": AnalysisSpec("hypothesis", "sign_test"),
43
+ "one_sample_wilcoxon": AnalysisSpec("hypothesis", "one_sample_wilcoxon"),
44
+ "mood_median": AnalysisSpec("hypothesis", "mood_median_test"),
45
+ "friedman": AnalysisSpec("hypothesis", "friedman_test"),
46
+ "runs_test": AnalysisSpec("hypothesis", "runs_test"),
47
+ "equivalence": AnalysisSpec("hypothesis", "equivalence_test"),
48
+ "linear_regression": AnalysisSpec("regression", "linear_regression", exclude=("formula",)),
49
+ "polynomial_regression": AnalysisSpec("regression", "polynomial_regression"),
50
+ "logistic_regression": AnalysisSpec("regression", "logistic_regression"),
51
+ "glm": AnalysisSpec("regression", "glm_regression"),
52
+ "mixed_model": AnalysisSpec("regression", "mixed_model"),
53
+ "stepwise_regression": AnalysisSpec("regression", "stepwise_regression"),
54
+ "gee": AnalysisSpec("regression", "gee_regression"),
55
+ "cart": AnalysisSpec("predictive", "cart"),
56
+ "random_forest": AnalysisSpec("predictive", "random_forest"),
57
+ "neural": AnalysisSpec("predictive", "neural_network"),
58
+ "xgboost": AnalysisSpec("predictive", "xgboost_model"),
59
+ "svm": AnalysisSpec("predictive", "svm_model"),
60
+ "naive_bayes": AnalysisSpec("predictive", "naive_bayes"),
61
+ "automl": AnalysisSpec("predictive", "automl"),
62
+ "control_chart": AnalysisSpec("quality", "spc_chart"),
63
+ "capability": AnalysisSpec("quality", "capability"),
64
+ "process_screening": AnalysisSpec("quality", "process_screening"),
65
+ "gage_rr": AnalysisSpec("quality", "gage_rr"),
66
+ "attribute_agreement": AnalysisSpec("quality", "attribute_agreement"),
67
+ "pareto": AnalysisSpec("quality", "pareto_chart"),
68
+ "kaplan_meier": AnalysisSpec("survival", "kaplan_meier"),
69
+ "logrank": AnalysisSpec("survival", "logrank_test"),
70
+ "cox": AnalysisSpec("survival", "cox_regression"),
71
+ "cox_regression": AnalysisSpec("survival", "cox_regression"),
72
+ "cumulative_incidence": AnalysisSpec("survival", "cumulative_incidence"),
73
+ "weibull_aft": AnalysisSpec("survival", "weibull_aft"),
74
+ "interval_censored_weibull": AnalysisSpec("survival", "interval_censored_weibull"),
75
+ "reliability_zero_failures": AnalysisSpec("survival", "reliability_zero_failures", data="none"),
76
+ "ts_summary": AnalysisSpec("timeseries", "time_series_summary"),
77
+ "acf_pacf": AnalysisSpec("timeseries", "acf_pacf"),
78
+ "stationarity": AnalysisSpec("timeseries", "stationarity_tests"),
79
+ "decomposition": AnalysisSpec("timeseries", "decomposition"),
80
+ "stl": AnalysisSpec("timeseries", "stl_decomposition"),
81
+ "arima": AnalysisSpec("timeseries", "arima_forecast"),
82
+ "exponential_smoothing": AnalysisSpec("timeseries", "exponential_smoothing"),
83
+ "forecast": AnalysisSpec("timeseries", "forecast"),
84
+ "correlation": AnalysisSpec("correlation", "correlation_matrix"),
85
+ "covariance": AnalysisSpec("correlation", "covariance_matrix"),
86
+ "pca": AnalysisSpec("multivariate", "pca"),
87
+ "kmeans": AnalysisSpec("multivariate", "kmeans_clustering"),
88
+ "hierarchical_clustering": AnalysisSpec("multivariate", "hierarchical_clustering"),
89
+ "discriminant": AnalysisSpec("multivariate", "discriminant_analysis"),
90
+ "canonical_correlation": AnalysisSpec("multivariate", "canonical_correlation"),
91
+ "factor_analysis": AnalysisSpec("multivariate", "factor_analysis"),
92
+ "manova": AnalysisSpec("multivariate", "manova"),
93
+ "distribution_fit": AnalysisSpec("distributions", "fit_distribution"),
94
+ "distribution_id": AnalysisSpec("distributions", "distribution_id"),
95
+ "distribution_summary": AnalysisSpec("distributions", "distribution_summary"),
96
+ "tolerance_interval": AnalysisSpec("tolerance", "tolerance_interval"),
97
+ "tolerance_sample_size": AnalysisSpec("tolerance", "sample_size_tolerance", data="none"),
98
+ "power_t": AnalysisSpec("power", "power_t_test", data="none"),
99
+ "power_t_sample_size": AnalysisSpec("power", "sample_size_t_test", data="none"),
100
+ "power_proportion": AnalysisSpec("power", "sample_size_proportion", data="none"),
101
+ "power_anova": AnalysisSpec("power", "sample_size_anova", data="none"),
102
+ "power_paired_t": AnalysisSpec("power", "sample_size_paired_t", data="none"),
103
+ "power_equivalence": AnalysisSpec("power", "sample_size_equivalence", data="none"),
104
+ "power_variance": AnalysisSpec("power", "sample_size_variance", data="none"),
105
+ "power_curve": AnalysisSpec("power", "power_curve", data="none"),
106
+ "doe_analysis": AnalysisSpec("doe", "analyze_design", data="table"),
107
+ "custom_doe_analysis": AnalysisSpec("custom_doe", "analyze_custom_design", data="table"),
108
+ "custom_prediction_profiler": AnalysisSpec("custom_doe", "prediction_profiler", data="table"),
109
+ "custom_response_simulation": AnalysisSpec("custom_doe", "simulate_response", data="table"),
110
+ "prediction_profiler": AnalysisSpec("doe", "prediction_profiler", data="table"),
111
+ "regression_prediction_profiler": AnalysisSpec("regression", "prediction_profiler"),
112
+ "regression_multi_response_optimization": AnalysisSpec("regression", "multi_response_optimize"),
113
+ "doe_diagnostics": AnalysisSpec("doe", "design_diagnostics", data="table"),
114
+ "response_simulation": AnalysisSpec("simulator", "simulate_response", data="table"),
115
+ "mixture_analysis": AnalysisSpec("optimal_doe", "analyze_mixture", data="table"),
116
+ "bayesian_linear_regression": AnalysisSpec("bayesian", "bayesian_linear_regression"),
117
+ "bayesian_logistic_regression": AnalysisSpec("bayesian", "bayesian_logistic_regression"),
118
+ "bayesian_two_sample": AnalysisSpec("bayesian", "bayesian_two_sample"),
119
+ "bayesian_anova": AnalysisSpec("bayesian", "bayesian_oneway_anova"),
120
+ "bayesian_optimization": AnalysisSpec("bayesian_optimization", "bayesian_optimize"),
121
+ }
122
+
123
+
124
+ def literal(value: Any) -> str:
125
+ if value is pd.NA:
126
+ return "pd.NA"
127
+ if isinstance(value, np.generic):
128
+ value = value.item()
129
+ if isinstance(value, float) and not math.isfinite(value):
130
+ return "float('nan')" if math.isnan(value) else ("float('inf')" if value > 0 else "float('-inf')")
131
+ if isinstance(value, dict):
132
+ return "{" + ", ".join(f"{literal(key)}: {literal(item)}" for key, item in value.items()) + "}"
133
+ if isinstance(value, (list, tuple, set)):
134
+ items = ", ".join(literal(item) for item in value)
135
+ if isinstance(value, tuple):
136
+ return f"({items}{',' if len(value) == 1 else ''})"
137
+ if isinstance(value, set):
138
+ return "{" + items + "}"
139
+ return "[" + items + "]"
140
+ if isinstance(value, (datetime, date, pd.Timestamp)):
141
+ return f"pd.Timestamp({value.isoformat()!r})"
142
+ return repr(value)
143
+
144
+
145
+ def _function_spec(spec: AnalysisSpec):
146
+ module = importlib.import_module(f"statstudio.stats.{spec.module}")
147
+ function = getattr(module, spec.function)
148
+ return function, inspect.signature(function)
149
+
150
+
151
+ def _call_params(spec: AnalysisSpec, params: dict[str, Any]) -> dict[str, Any]:
152
+ function, signature = _function_spec(spec)
153
+ del function
154
+ parameters = list(signature.parameters.values())
155
+ data_parameters = 0 if spec.data == "none" else 1
156
+ allowed = {parameter.name for parameter in parameters[data_parameters:] if parameter.kind in (parameter.POSITIONAL_OR_KEYWORD, parameter.KEYWORD_ONLY)}
157
+ return {
158
+ key: value
159
+ for key, value in (params or {}).items()
160
+ if key in allowed and key not in spec.exclude
161
+ }
162
+
163
+
164
+ def analysis_code(result, table_expression: str = "table") -> str:
165
+ analysis_type = getattr(result, "analysis_type", "")
166
+ params = dict(getattr(result, "params", {}) or {})
167
+ if analysis_type == "plot":
168
+ kind = params.pop("kind", "histogram")
169
+ title = params.pop("title", "")
170
+ return (
171
+ f"_plot_data = {table_expression}.plot_df()\n"
172
+ f"figure = plots.build_figure(PlotSpec(kind={literal(kind)}, "
173
+ f"params={literal(params)}, title={literal(title)}, "
174
+ f"data=_plot_data, row_ids=list(_plot_data.index)))"
175
+ )
176
+ if analysis_type == "multi_response_optimization":
177
+ responses = list(params.get("responses") or [])
178
+ goals = params.get("goals") or {}
179
+ order = int(params.get("order", 2))
180
+ starts = int(params.get("starts", 20))
181
+ seed = int(params.get("seed", 42))
182
+ label = str(params.get("response") or ", ".join(responses))
183
+ return (
184
+ "from statstudio.stats import desirability, doe\n"
185
+ f"_mr_order = {order}\n"
186
+ f"_mr_models = {{}}\n"
187
+ f"_mr_goals = {literal(goals)}\n"
188
+ f"_mr_factors = []\n"
189
+ f"for _mr_response in {literal(responses)}:\n"
190
+ f" _mr_model, _mr_factors, _ = doe.fit_design_model({table_expression}, _mr_response, _mr_order)\n"
191
+ f" _mr_models[_mr_response] = _mr_model\n"
192
+ f"result = desirability.multi_response_optimize("
193
+ f"_mr_models, _mr_factors, _mr_goals, {literal(label)}, {starts}, {seed}, order=_mr_order)"
194
+ )
195
+ spec = ANALYSIS_SPECS.get(analysis_type)
196
+ if spec is None:
197
+ return f"# No replay code is available for analysis type {analysis_type!r}."
198
+ if spec.data != "none" and str(table_expression).strip() in {"", "None"}:
199
+ return "# No source table is available for this replay."
200
+ try:
201
+ kwargs = _call_params(spec, params)
202
+ except Exception as exc:
203
+ return f"# Could not generate replay code: {exc}"
204
+ args: list[str] = []
205
+ if spec.data == "df":
206
+ args.append(f"df={table_expression}.analysis_df(honor_modeling=True)")
207
+ elif spec.data == "table":
208
+ args.append(f"table={table_expression}")
209
+ args.extend(f"{key}={literal(value)}" for key, value in kwargs.items())
210
+ call = f"stats.{spec.module}.{spec.function}(" + ", ".join(args) + ")"
211
+ return f"result = {call}"
212
+
213
+
214
+ def _table(name: str) -> str:
215
+ return f"_tables[{literal(name)}]"
216
+
217
+
218
+
219
+
220
+ def operation_code(
221
+ operation: str,
222
+ params: dict[str, Any],
223
+ sources: Sequence[str],
224
+ result_table: str,
225
+ *,
226
+ source_expression: str | None = None,
227
+ target_expression: str | None = None,
228
+ ) -> str:
229
+ params = dict(params or {})
230
+ sources = list(sources or [])
231
+ target = target_expression if target_expression is not None else _table(result_table)
232
+ source = source_expression if source_expression is not None else (_table(sources[0]) if sources else target)
233
+ if operation == "new_table":
234
+ return f'{target} = DataTable(pd.DataFrame(), {literal(result_table)})'
235
+ if operation == "sample":
236
+ name = params.get("sample", result_table)
237
+ return f'{target} = load_sample({literal(name)}); {target}.name = {literal(result_table)}'
238
+ if operation == "custom_design":
239
+ spec = params.get("spec", {})
240
+ return (
241
+ "from statstudio.stats import custom_doe\n"
242
+ f"{target} = custom_doe.build_custom_design(custom_doe.CustomDesignSpec.from_dict({literal(spec)}))\n"
243
+ f"{target}.name = {literal(result_table)}"
244
+ )
245
+ if operation == "doe_design":
246
+ spec = params.get("spec", {})
247
+ factors = spec.get("factors") or []
248
+ replicates = int(spec.get("replicates", 1))
249
+ centers = int(spec.get("centers", 0))
250
+ randomize = bool(spec.get("randomize", True))
251
+ seed = int(spec.get("seed", 42))
252
+ resolution = spec.get("resolution", "IV")
253
+ levels = int(spec.get("levels", 3))
254
+ runs = int(spec.get("runs", 16))
255
+ alpha = spec.get("alpha")
256
+ optimal_runs = int(spec.get("optimal_runs", 12))
257
+ criterion = str(spec.get("criterion", "D")).upper()
258
+ return (
259
+ "from statstudio.stats import doe, optimal_doe\n"
260
+ f"_doe_factor_specs = {literal(factors)}\n"
261
+ "_doe_factors = [\n"
262
+ " doe.Factor(\n"
263
+ " name=item['name'],\n"
264
+ " low=float(item.get('low', -1.0)),\n"
265
+ " high=float(item.get('high', 1.0)),\n"
266
+ " units=str(item.get('units', '')),\n"
267
+ " )\n"
268
+ " for item in _doe_factor_specs\n"
269
+ "]\n"
270
+ f"_doe_names = [item['name'] for item in {literal(factors)}]\n"
271
+ f"_doe_type = {literal(spec.get('design_type'))}\n"
272
+ "if _doe_type == 'Full Factorial':\n"
273
+ f" {target} = doe.full_factorial(_doe_factors, {replicates}, {centers}, {randomize}, {seed})\n"
274
+ "elif _doe_type == '3-Level Factorial':\n"
275
+ f" {target} = doe.factorial_levels(_doe_factors, {levels}, {replicates}, {randomize}, {seed})\n"
276
+ "elif _doe_type == 'Fractional Factorial':\n"
277
+ f" {target} = doe.fractional_factorial(_doe_factors, {literal(resolution)}, {replicates}, {centers}, {randomize}, {seed})\n"
278
+ "elif _doe_type == 'Plackett-Burman Screening':\n"
279
+ f" {target} = doe.screening_design(_doe_factors, {runs}, {centers}, {randomize}, {seed})\n"
280
+ "elif _doe_type == 'Central Composite':\n"
281
+ f" {target} = doe.central_composite(_doe_factors, {literal(alpha)}, max(1, {centers}), {replicates}, {randomize}, {seed})\n"
282
+ "elif _doe_type == 'Box-Behnken':\n"
283
+ f" {target} = doe.box_behnken(_doe_factors, max(1, {centers}), {replicates}, {randomize}, {seed})\n"
284
+ "elif _doe_type == 'D-Optimal':\n"
285
+ f" {target} = optimal_doe.optimal_design(_doe_factors, {optimal_runs}, {literal(criterion)}, 20, {seed})\n"
286
+ "elif _doe_type == 'Mixture':\n"
287
+ f" {target} = optimal_doe.mixture_design(_doe_names, {levels}, 1.0, {seed})\n"
288
+ "else:\n"
289
+ " raise ValueError(f'Unknown DOE design type: {_doe_type}')\n"
290
+ f"{target}.name = {literal(result_table)}"
291
+ )
292
+ if operation == "import_file":
293
+ path = params.get("path", "")
294
+ sheet = params.get("sheet_name", 0)
295
+ options = params.get("options")
296
+ option_code = ""
297
+ if isinstance(options, dict) and options:
298
+ option_code = f", options=CSVOptions({', '.join(f'{key}={literal(value)}' for key, value in options.items())})"
299
+ return f'{target} = read_file({literal(path)}{option_code}, sheet_name={literal(sheet)}); {target}.name = {literal(result_table)}'
300
+ if operation == "load_table":
301
+ return f'{target} = load_table({literal(params.get("path", ""))}); {target}.name = {literal(result_table)}'
302
+ if operation == "clipboard":
303
+ text = str(params.get("text", ""))
304
+ return f'{target} = DataTable(parse_clipboard_frame({literal(text)}), {literal(result_table)})'
305
+ if operation == "odbc":
306
+ profile = params.get("profile") or {}
307
+ query = str(params.get("query", ""))
308
+ name = str(params.get("name") or result_table)
309
+ return (
310
+ f'_odbc_profile = OdbcProfile.from_dict({literal(profile)})\n'
311
+ f'{target} = import_query(_odbc_profile, {literal(query)}, {literal(name)})\n'
312
+ f'{target}.name = {literal(result_table)}'
313
+ )
314
+ if operation == "join":
315
+ right = _table(sources[1]) if len(sources) > 1 else target
316
+ on = params.get("on")
317
+ if on:
318
+ keys = f"on={literal(on)}"
319
+ else:
320
+ keys = f"left_on={literal(params.get('left_on'))}, right_on={literal(params.get('right_on'))}"
321
+ return (
322
+ f'{target} = merge_tables({source}, {right}, how={literal(params.get("how", "inner"))}, '
323
+ f'{keys}, name={literal(result_table)})'
324
+ )
325
+ if operation == "append":
326
+ tables = ", ".join(_table(name) for name in sources)
327
+ return f'{target} = append_tables([{tables}], name={literal(result_table)})'
328
+ if operation == "split":
329
+ index = int(params.get("index", 0))
330
+ return (
331
+ f'_split = transform.split_table({source}, {literal(params.get("column", ""))}); '
332
+ f'{target} = _split[{index}]; {target}.name = {literal(result_table)}'
333
+ )
334
+ if operation == "stack":
335
+ return (
336
+ f'{target} = transform.stack_table({source}, id_columns={literal(params.get("id_columns", []))}, '
337
+ f'value_columns={literal(params.get("value_columns", []))}, variable_name={literal(params.get("variable_name", "Variable"))}, '
338
+ f'value_name={literal(params.get("value_name", "Value"))}, name={literal(result_table)})'
339
+ )
340
+ if operation == "unstack":
341
+ return (
342
+ f'{target} = transform.unstack_table({source}, index_columns={literal(params.get("index_columns", []))}, '
343
+ f'column_column={literal(params.get("column_column", ""))}, value_column={literal(params.get("value_column", ""))}, '
344
+ f'aggregate={literal(params.get("aggregate", "mean"))}, name={literal(result_table)})'
345
+ )
346
+ if operation == "transpose":
347
+ return f'{target} = transform.transpose_table({source}, name={literal(result_table)})'
348
+ if operation == "subset":
349
+ return f'{target} = transform.subset_columns({source}, {literal(params.get("columns", []))}, name={literal(result_table)})'
350
+ if operation == "subset_rows":
351
+ return f'{target} = {source}.subset(rows={literal(params.get("rows", []))}, name={literal(result_table)})'
352
+ if operation == "recode":
353
+ return (
354
+ f'{target} = transform.recode_column({source}, {literal(params.get("column", ""))}, '
355
+ f'{literal(params.get("mapping", {}))}, default={literal(params.get("default"))}, '
356
+ f'new_name={literal(params.get("new_name"))}, keep_unmapped={literal(params.get("keep_unmapped", True))}); '
357
+ f'{target}.name = {literal(result_table)}'
358
+ )
359
+ if operation == "replace_missing":
360
+ return (
361
+ f'{target} = transform.replace_missing({source}, {literal(params.get("column", ""))}, '
362
+ f'value={literal(params.get("value"))}, new_name={literal(params.get("new_name"))}); '
363
+ f'{target}.name = {literal(result_table)}'
364
+ )
365
+ if operation == "boxcox":
366
+ return f'{target}, _lambda = transform.boxcox_column({source}, {literal(params.get("column", ""))}, new_name={literal(params.get("new_name"))}, shift={literal(params.get("shift"))}); {target}.name = {literal(result_table)}'
367
+ if operation == "rank":
368
+ return f'{target} = transform.rank_column({source}, {literal(params.get("column", ""))}, new_name={literal(params.get("new_name"))}, method={literal(params.get("method", "average"))}); {target}.name = {literal(result_table)}'
369
+ if operation == "bin":
370
+ return f'{target} = transform.bin_column({source}, {literal(params.get("column", ""))}, {literal(params.get("bins", 5))}, labels={literal(params.get("labels"))}, new_name={literal(params.get("new_name"))}); {target}.name = {literal(result_table)}'
371
+ if operation == "text_to_columns":
372
+ return f'{target} = transform.text_to_columns({source}, {literal(params.get("column", ""))}, {literal(params.get("separator", ","))}, new_names={literal(params.get("new_names"))}); {target}.name = {literal(result_table)}'
373
+ if operation == "add_rows":
374
+ return f'add_rows({source}, {literal(params.get("count", 1))})'
375
+ if operation == "add_column":
376
+ return f'transform.add_empty_column({source}, {literal(params.get("name", ""))}, {literal(params.get("data_type", "numeric"))}, {literal(params.get("default"))})'
377
+ if operation == "formula":
378
+ return f'transform.add_formula_column({source}, {literal(params.get("name", ""))}, {literal(params.get("formula", ""))})'
379
+ if operation == "set_formula":
380
+ return f'{source}.set_formula({literal(params.get("column", ""))}, {literal(params.get("formula"))})'
381
+ if operation == "standardize":
382
+ return f'transform.standardize_columns({source}, {literal(params.get("columns", []))}, suffix={literal(params.get("suffix", "_z"))})'
383
+ if operation == "filter":
384
+ return f'{source}.set_filter({literal(params.get("expression"))})'
385
+ if operation == "clear_filter":
386
+ return f'{source}.set_filter(None)'
387
+ if operation in {"exclude_rows", "include_rows"}:
388
+ return f'{source}.set_excluded({literal(params.get("rows", []))}, {operation == "exclude_rows"})'
389
+ if operation in {"hide_rows", "unhide_rows"}:
390
+ return f'{source}.set_hidden({literal(params.get("rows", []))}, {operation == "hide_rows"})'
391
+ if operation == "clear_exclusions":
392
+ return f'{source}.clear_exclusions()'
393
+ if operation == "delete_rows":
394
+ return f'transform.delete_rows({source}, {literal(params.get("rows", []))})'
395
+ if operation == "duplicate_rows":
396
+ return f'transform.duplicate_rows({source}, {literal(params.get("rows", []))})'
397
+ if operation == "move_column":
398
+ return f'transform.move_column({source}, {literal(params.get("column", ""))}, {literal(params.get("offset", 0))})'
399
+ if operation == "find_replace":
400
+ return (
401
+ f'transform.find_replace({source}, {literal(params.get("columns", []))}, {literal(params.get("find", ""))}, '
402
+ f'{literal(params.get("replace", ""))}, regex={literal(params.get("regex", False))}, '
403
+ f'match_case={literal(params.get("match_case", True))}, whole_cell={literal(params.get("whole_cell", False))})'
404
+ )
405
+ if operation == "rename_column":
406
+ return f'{source}.rename_column({literal(params.get("old", ""))}, {literal(params.get("new", ""))})'
407
+ if operation == "delete_column":
408
+ return f'{source}.drop_columns({literal(params.get("columns", []))})'
409
+ if operation == "hide_column":
410
+ return f'{source}.hidden_columns.add({literal(params.get("column", ""))})'
411
+ if operation == "rename_table":
412
+ old = params.get("old", "")
413
+ return f'if {literal(old)} in _tables:\n {target} = _tables.pop({literal(old)}); {target}.name = {literal(result_table)}'
414
+ if operation == "duplicate_table":
415
+ return f'{target} = {source}.copy({literal(result_table)})'
416
+ if operation == "delete_table":
417
+ return f'_tables.pop({literal(params.get("name", result_table))}, None)'
418
+ if operation == "cell_edit":
419
+ return (
420
+ f'{source}.set_cells([({literal(params.get("row"))}, {literal(params.get("column"))}, '
421
+ f'{literal(params.get("value"))})])'
422
+ )
423
+ if operation == "sort":
424
+ spec = [[str(column), bool(ascending)] for column, ascending in params.get("spec", [])]
425
+ return f'{source}.sort_by({literal(spec)})'
426
+ return f"# No replay code is available for operation {operation!r}."
427
+
428
+
429
+ CREATION_OPERATIONS = {
430
+ "new_table",
431
+ "sample",
432
+ "custom_design",
433
+ "doe_design",
434
+ "import_file",
435
+ "load_table",
436
+ "clipboard",
437
+ "odbc",
438
+ "join",
439
+ "append",
440
+ "split",
441
+ "stack",
442
+ "unstack",
443
+ "transpose",
444
+ "subset",
445
+ "subset_rows",
446
+ "recode",
447
+ "replace_missing",
448
+ "boxcox",
449
+ "rank",
450
+ "bin",
451
+ "text_to_columns",
452
+ "duplicate_table",
453
+ }
454
+
455
+ INPLACE_OPERATIONS = {
456
+ "add_rows",
457
+ "add_column",
458
+ "formula",
459
+ "set_formula",
460
+ "standardize",
461
+ "filter",
462
+ "clear_filter",
463
+ "exclude_rows",
464
+ "include_rows",
465
+ "hide_rows",
466
+ "unhide_rows",
467
+ "clear_exclusions",
468
+ "delete_rows",
469
+ "duplicate_rows",
470
+ "move_column",
471
+ "find_replace",
472
+ "rename_column",
473
+ "delete_column",
474
+ "hide_column",
475
+ "cell_edit",
476
+ "sort",
477
+ }
478
+
479
+
480
+ def import_prelude() -> str:
481
+ return "\n".join(
482
+ [
483
+ "import pandas as pd",
484
+ "from statstudio import plots, stats",
485
+ "from statstudio.core.table import DataTable, add_rows",
486
+ "from statstudio.core import transform",
487
+ "from statstudio.core.joins import merge_tables, append_tables",
488
+ "from statstudio.io.file_import import CSVOptions, parse_clipboard_frame, read_file",
489
+ "from statstudio.io.sample_data import load_sample",
490
+ "from statstudio.io.odbc import OdbcProfile, import_query",
491
+ "from statstudio.io.table_io import load_table",
492
+ "from statstudio.stats.results import PlotSpec",
493
+ ]
494
+ )
495
+
496
+
497
+ def script_prelude(project_path: str | None, initial: list[str]) -> str:
498
+ lines = [import_prelude()]
499
+ if project_path:
500
+ lines.extend(
501
+ [
502
+ "from statstudio.core.project import Project as _Project",
503
+ f"_project = _Project.load({literal(project_path)})",
504
+ "_tables = {name: _project.get_table(name).copy() for name in " + literal(initial) + " if _project.find_table(name)}",
505
+ ]
506
+ )
507
+ else:
508
+ lines.extend(
509
+ [
510
+ "try:",
511
+ " sdk",
512
+ "except NameError as exc:",
513
+ " raise RuntimeError('Save the project or provide a project path to export a standalone script.') from exc",
514
+ "_tables = {name: sdk.dataset(name).copy() for name in " + literal(initial) + "}",
515
+ ]
516
+ )
517
+ return "\n".join(lines)
518
+
519
+
520
+ def cumulative_script(project, project_path: str | None = None) -> str:
521
+ journal = list(project.journal)
522
+ created = {
523
+ entry.result_table
524
+ for entry in journal
525
+ if entry.kind == "data_prep" and entry.result_table and entry.operation in CREATION_OPERATIONS
526
+ }
527
+ for entry in journal:
528
+ if entry.operation == "rename_table" and entry.result_table:
529
+ params = entry.params or {}
530
+ if params.get("old") in created:
531
+ created.add(entry.result_table)
532
+ seeded = {table.name for table in project.tables if table.name not in created}
533
+ initial = [table.name for table in project.tables if table.name in seeded]
534
+ rename_aliases: dict[str, str] = {}
535
+ for entry in journal:
536
+ if entry.operation == "rename_table" and entry.result_table in seeded:
537
+ old_name = (entry.params or {}).get("old")
538
+ if old_name and old_name not in seeded:
539
+ rename_aliases[str(old_name)] = entry.result_table
540
+ alias_lines = [
541
+ f"_tables[{literal(old_name)}] = _tables[{literal(new_name)}]"
542
+ for old_name, new_name in rename_aliases.items()
543
+ ]
544
+ lines = [
545
+ "# Generated by StatStudio. Run in the StatStudio Python console or with `statstudio run`.",
546
+ script_prelude(project_path, initial),
547
+ "",
548
+ *alias_lines,
549
+ "# Tables without a recorded creation step are seeded from their current state.",
550
+ "",
551
+ ]
552
+ for entry in journal:
553
+ if getattr(entry, "undone", False):
554
+ lines.append(f"# [{entry.sequence}] {entry.title or entry.operation} (undone)")
555
+ lines.append("")
556
+ continue
557
+ if (
558
+ entry.kind == "data_prep"
559
+ and entry.operation in INPLACE_OPERATIONS
560
+ and entry.result_table in seeded
561
+ ):
562
+ lines.append(
563
+ f"# [{entry.sequence}] {entry.title or entry.operation} "
564
+ "(already reflected in the seeded table snapshot)"
565
+ )
566
+ lines.append("")
567
+ continue
568
+ lines.append(f"# [{entry.sequence}] {entry.title or entry.operation}")
569
+ code_text = entry.code or "# no code recorded"
570
+ lines.extend(code_text.splitlines())
571
+ if entry.kind == "analysis":
572
+ if "figure = " in code_text:
573
+ lines.append("print('Rendered graph:', figure)")
574
+ elif "result = " in code_text:
575
+ lines.append("print(getattr(result, 'summary', '') or getattr(result, 'title', 'Analysis complete'))")
576
+ lines.append("")
577
+ if project_path:
578
+ lines.insert(1, f"# Project: {project_path}")
579
+ return "\n".join(lines).rstrip() + "\n"
580
+
581
+
582
+ def linked_script_body(script) -> str:
583
+ return (script.code or "").strip() + "\n"
584
+
585
+
586
+ def standalone_linked_script(script, table_path: str) -> str:
587
+ lines = [
588
+ "# Generated by StatStudio. Requires the table file next to this script.",
589
+ import_prelude(),
590
+ f"table = load_table({literal(table_path)})",
591
+ "",
592
+ linked_script_body(script),
593
+ ]
594
+ return "\n".join(lines)