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,72 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from statstudio.plots.common import color, frame, new_figure, numeric, rotate_labels, style_axes
|
|
5
|
+
from statstudio.stats.results import PlotSpec
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def importance(spec: PlotSpec):
|
|
9
|
+
data = frame(spec)
|
|
10
|
+
if data.empty:
|
|
11
|
+
return new_figure()
|
|
12
|
+
variable_name = spec.params.get("variable", "Variable")
|
|
13
|
+
importance_name = spec.params.get("importance", "Importance")
|
|
14
|
+
if variable_name not in data.columns or importance_name not in data.columns:
|
|
15
|
+
return new_figure()
|
|
16
|
+
data = data.sort_values(importance_name, ascending=True)
|
|
17
|
+
figure = new_figure(7, max(3.2, 0.36 * len(data) + 1.4))
|
|
18
|
+
ax = figure.add_subplot(111)
|
|
19
|
+
ax.barh(data[variable_name].astype(str), numeric(data, importance_name), color=color(0))
|
|
20
|
+
style_axes(ax, spec.title or "Variable Importance", importance_name, variable_name)
|
|
21
|
+
return figure
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def confusion(spec: PlotSpec):
|
|
25
|
+
labels = [str(v) for v in spec.params.get("labels", [])]
|
|
26
|
+
matrix = np.asarray(spec.params.get("matrix", []), dtype=float)
|
|
27
|
+
figure = new_figure(max(4.5, len(labels) * 1.1 + 2), max(4, len(labels) * 1.0 + 1.6))
|
|
28
|
+
ax = figure.add_subplot(111)
|
|
29
|
+
if matrix.size:
|
|
30
|
+
image = ax.imshow(matrix, cmap="Blues")
|
|
31
|
+
for i in range(matrix.shape[0]):
|
|
32
|
+
for j in range(matrix.shape[1]):
|
|
33
|
+
ax.text(j, i, f"{int(matrix[i, j])}", ha="center", va="center", fontsize=10, color="white" if matrix[i, j] > matrix.max() / 2 else "#20242a")
|
|
34
|
+
figure.colorbar(image, ax=ax, fraction=0.046, pad=0.04)
|
|
35
|
+
ax.set_xticks(range(len(labels)), labels, rotation=45, ha="right")
|
|
36
|
+
ax.set_yticks(range(len(labels)), labels)
|
|
37
|
+
ax.set_xlabel("Predicted")
|
|
38
|
+
ax.set_ylabel("Actual")
|
|
39
|
+
ax.set_title(spec.title or "Confusion Matrix", fontsize=11, fontweight="bold")
|
|
40
|
+
return figure
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def model_comparison(spec: PlotSpec):
|
|
44
|
+
data = frame(spec)
|
|
45
|
+
model_name = spec.params.get("model", "Model")
|
|
46
|
+
score_name = spec.params.get("score", "Score")
|
|
47
|
+
figure = new_figure()
|
|
48
|
+
ax = figure.add_subplot(111)
|
|
49
|
+
ax.bar(data[model_name].astype(str), numeric(data, score_name), color=[color(i) for i in range(len(data))])
|
|
50
|
+
rotate_labels(ax)
|
|
51
|
+
style_axes(ax, spec.title or "Model Comparison", str(model_name), str(score_name))
|
|
52
|
+
return figure
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def interaction_grouped(spec: PlotSpec):
|
|
56
|
+
data = frame(spec)
|
|
57
|
+
x_name = spec.params["x"]
|
|
58
|
+
y_name = spec.params["y"]
|
|
59
|
+
group_name = spec.params.get("group")
|
|
60
|
+
figure = new_figure()
|
|
61
|
+
ax = figure.add_subplot(111)
|
|
62
|
+
if group_name and group_name in data.columns:
|
|
63
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False, sort=True)):
|
|
64
|
+
means = numeric(chunk, y_name).groupby(chunk[x_name]).mean()
|
|
65
|
+
ax.plot([str(v) for v in means.index], means.to_numpy(), marker="o", linewidth=2, color=color(index), label=str(label))
|
|
66
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
67
|
+
else:
|
|
68
|
+
means = numeric(data, y_name).groupby(data[x_name]).mean()
|
|
69
|
+
ax.plot([str(v) for v in means.index], means.to_numpy(), marker="o", linewidth=2, color=color(0))
|
|
70
|
+
rotate_labels(ax)
|
|
71
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(x_name), f"Mean {y_name}")
|
|
72
|
+
return figure
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Callable
|
|
4
|
+
|
|
5
|
+
from matplotlib.figure import Figure
|
|
6
|
+
|
|
7
|
+
from statstudio.plots import advanced, basic, bayesian_plots, diagnostics, doe_plots, predictive_plots
|
|
8
|
+
from statstudio.plots.common import (
|
|
9
|
+
apply_axis_limits,
|
|
10
|
+
apply_axis_scales,
|
|
11
|
+
apply_data_limits,
|
|
12
|
+
apply_row_styles,
|
|
13
|
+
)
|
|
14
|
+
from statstudio.stats.results import PlotSpec
|
|
15
|
+
|
|
16
|
+
BUILDERS: dict[str, Callable[[PlotSpec], Figure]] = {
|
|
17
|
+
"histogram": basic.histogram,
|
|
18
|
+
"box": basic.box,
|
|
19
|
+
"violin": basic.violin,
|
|
20
|
+
"strip": basic.strip,
|
|
21
|
+
"variability": advanced.variability,
|
|
22
|
+
"dotplot": advanced.dotplot,
|
|
23
|
+
"bar": basic.bar,
|
|
24
|
+
"scatter": basic.scatter,
|
|
25
|
+
"bubble": advanced.bubble,
|
|
26
|
+
"scatter3d": advanced.scatter3d,
|
|
27
|
+
"line": basic.line,
|
|
28
|
+
"line3d": advanced.line3d,
|
|
29
|
+
"area": advanced.area,
|
|
30
|
+
"density": basic.density,
|
|
31
|
+
"pie": advanced.pie,
|
|
32
|
+
"correlation_heatmap": basic.correlation_heatmap,
|
|
33
|
+
"pairplot": basic.pairplot,
|
|
34
|
+
"parallel_coordinates": advanced.parallel_coordinates,
|
|
35
|
+
"heatmap": advanced.heatmap,
|
|
36
|
+
"mosaic": basic.mosaic,
|
|
37
|
+
"pareto": basic.pareto,
|
|
38
|
+
"capability": basic.capability,
|
|
39
|
+
"sixpack": basic.sixpack,
|
|
40
|
+
"control_chart": basic.control_chart,
|
|
41
|
+
"survival": basic.survival,
|
|
42
|
+
"forecast": basic.forecast,
|
|
43
|
+
"decomposition": basic.decomposition,
|
|
44
|
+
"acf_pacf": basic.acf_pacf,
|
|
45
|
+
"actual_predicted": diagnostics.actual_predicted,
|
|
46
|
+
"residual_fitted": diagnostics.residual_fitted,
|
|
47
|
+
"residual_order": diagnostics.residual_order,
|
|
48
|
+
"scale_location": diagnostics.scale_location,
|
|
49
|
+
"leverage": diagnostics.leverage,
|
|
50
|
+
"cooks_distance": diagnostics.cooks_distance,
|
|
51
|
+
"qq": diagnostics.qq,
|
|
52
|
+
"roc": diagnostics.roc,
|
|
53
|
+
"scree": diagnostics.scree,
|
|
54
|
+
"pca_biplot": diagnostics.pca_biplot,
|
|
55
|
+
"cluster_scatter": diagnostics.cluster_scatter,
|
|
56
|
+
"dendrogram": diagnostics.dendrogram_plot,
|
|
57
|
+
"doe_pareto": doe_plots.doe_pareto,
|
|
58
|
+
"main_effects": doe_plots.main_effects,
|
|
59
|
+
"interaction": doe_plots.interaction,
|
|
60
|
+
"doe_contour": doe_plots.doe_contour,
|
|
61
|
+
"doe_surface": doe_plots.doe_surface,
|
|
62
|
+
"profiler": doe_plots.profiler,
|
|
63
|
+
"contour": doe_plots.contour_generic,
|
|
64
|
+
"surface": doe_plots.surface_generic,
|
|
65
|
+
"importance": predictive_plots.importance,
|
|
66
|
+
"confusion": predictive_plots.confusion,
|
|
67
|
+
"model_comparison": predictive_plots.model_comparison,
|
|
68
|
+
"interaction_grouped": predictive_plots.interaction_grouped,
|
|
69
|
+
"weibull_plot": diagnostics.weibull_plot,
|
|
70
|
+
"bayes_trace": bayesian_plots.bayes_trace,
|
|
71
|
+
"bayes_posterior": bayesian_plots.bayes_posterior,
|
|
72
|
+
"bayes_forest": bayesian_plots.bayes_forest,
|
|
73
|
+
"bayes_ppc": bayesian_plots.bayes_ppc,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
PLOT_DEFINITIONS = {
|
|
77
|
+
"histogram": {"label": "Histogram", "roles": ["x", "group"]},
|
|
78
|
+
"density": {"label": "Density", "roles": ["x", "group"]},
|
|
79
|
+
"box": {"label": "Box Plot", "roles": ["x", "y"]},
|
|
80
|
+
"violin": {"label": "Violin Plot", "roles": ["x", "y"]},
|
|
81
|
+
"strip": {"label": "Strip Plot", "roles": ["x", "y"]},
|
|
82
|
+
"variability": {"label": "Variability Chart", "roles": ["x", "y", "group"]},
|
|
83
|
+
"dotplot": {"label": "Dot Plot", "roles": ["x", "y", "group"]},
|
|
84
|
+
"scatter": {"label": "Scatter Plot", "roles": ["x", "y", "y2", "group", "shape", "facet"]},
|
|
85
|
+
"bubble": {"label": "Bubble Plot", "roles": ["x", "y", "size", "group", "shape", "facet"]},
|
|
86
|
+
"scatter3d": {"label": "3D Scatter Plot", "roles": ["x", "y", "z", "group", "size", "facet"]},
|
|
87
|
+
"line": {"label": "Line Chart", "roles": ["x", "y", "y2", "facet"]},
|
|
88
|
+
"line3d": {"label": "3D Line Plot", "roles": ["x", "y", "z", "group", "facet"]},
|
|
89
|
+
"area": {"label": "Area Chart", "roles": ["x", "y", "group", "facet"]},
|
|
90
|
+
"pie": {"label": "Pie Chart", "roles": ["category", "count", "facet"]},
|
|
91
|
+
"bar": {"label": "Bar Chart", "roles": ["x", "y", "y2", "group", "error_column", "facet"]},
|
|
92
|
+
"correlation_heatmap": {"label": "Correlation Heatmap", "roles": ["columns"]},
|
|
93
|
+
"pairplot": {"label": "Scatterplot Matrix", "roles": ["columns"]},
|
|
94
|
+
"parallel_coordinates": {"label": "Parallel Coordinates", "roles": ["columns", "group"]},
|
|
95
|
+
"heatmap": {"label": "Heatmap", "roles": ["x", "y", "z"]},
|
|
96
|
+
"mosaic": {"label": "Mosaic Plot", "roles": ["row", "column"]},
|
|
97
|
+
"pareto": {"label": "Pareto Chart", "roles": ["category", "count"]},
|
|
98
|
+
"contour": {"label": "Contour Plot", "roles": ["x", "y", "z"]},
|
|
99
|
+
"surface": {"label": "Surface Plot", "roles": ["x", "y", "z"]},
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
_OPTION_AWARE = {
|
|
104
|
+
"histogram",
|
|
105
|
+
"box",
|
|
106
|
+
"bar",
|
|
107
|
+
"scatter",
|
|
108
|
+
"line",
|
|
109
|
+
"violin",
|
|
110
|
+
"strip",
|
|
111
|
+
"bubble",
|
|
112
|
+
"area",
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
_LEGEND_LOCATIONS = {
|
|
116
|
+
"Best": "best",
|
|
117
|
+
"Upper right": "upper right",
|
|
118
|
+
"Upper left": "upper left",
|
|
119
|
+
"Lower right": "lower right",
|
|
120
|
+
"Lower left": "lower left",
|
|
121
|
+
"Outside right": "center left",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _label_size(value):
|
|
126
|
+
try:
|
|
127
|
+
size = float(value)
|
|
128
|
+
except (TypeError, ValueError):
|
|
129
|
+
return None
|
|
130
|
+
return size if size > 0 else None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _apply_labels_and_legend(figure: Figure, spec: PlotSpec) -> None:
|
|
134
|
+
params = spec.params
|
|
135
|
+
x_label = params.get("x_label")
|
|
136
|
+
y_label = params.get("y_label")
|
|
137
|
+
legend_position = params.get("legend_position")
|
|
138
|
+
axes = list(figure.axes)
|
|
139
|
+
if not axes:
|
|
140
|
+
return
|
|
141
|
+
primary = axes[0]
|
|
142
|
+
if x_label:
|
|
143
|
+
primary.set_xlabel(str(x_label))
|
|
144
|
+
if y_label:
|
|
145
|
+
primary.set_ylabel(str(y_label))
|
|
146
|
+
x_size = _label_size(params.get("x_label_size"))
|
|
147
|
+
y_size = _label_size(params.get("y_label_size"))
|
|
148
|
+
if x_size is not None:
|
|
149
|
+
primary.xaxis.label.set_fontsize(x_size)
|
|
150
|
+
if y_size is not None:
|
|
151
|
+
for axis in axes:
|
|
152
|
+
axis.yaxis.label.set_fontsize(y_size)
|
|
153
|
+
if legend_position and primary.get_legend() is not None:
|
|
154
|
+
location = _LEGEND_LOCATIONS.get(str(legend_position), "best")
|
|
155
|
+
title = primary.get_legend().get_title().get_text()
|
|
156
|
+
handles: list = []
|
|
157
|
+
labels: list[str] = []
|
|
158
|
+
for axis in axes:
|
|
159
|
+
axis_handles, axis_labels = axis.get_legend_handles_labels()
|
|
160
|
+
handles.extend(axis_handles)
|
|
161
|
+
labels.extend(axis_labels)
|
|
162
|
+
if handles:
|
|
163
|
+
bbox = (1.02, 0.5) if str(legend_position) == "Outside right" else None
|
|
164
|
+
primary.legend(
|
|
165
|
+
handles,
|
|
166
|
+
labels,
|
|
167
|
+
loc=location,
|
|
168
|
+
title=title or None,
|
|
169
|
+
frameon=False,
|
|
170
|
+
fontsize=8,
|
|
171
|
+
bbox_to_anchor=bbox,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _apply_scale_and_references(figure: Figure, spec: PlotSpec) -> None:
|
|
176
|
+
params = spec.params
|
|
177
|
+
for ax in figure.axes[:1]:
|
|
178
|
+
x_scale = params.get("x_scale") or ("log" if params.get("log_x") else None)
|
|
179
|
+
y_scale = params.get("y_scale") or ("log" if params.get("log_y") else None)
|
|
180
|
+
if x_scale in {"log", "linear"}:
|
|
181
|
+
try:
|
|
182
|
+
ax.set_xscale(x_scale)
|
|
183
|
+
except Exception:
|
|
184
|
+
pass
|
|
185
|
+
if y_scale in {"log", "linear"}:
|
|
186
|
+
try:
|
|
187
|
+
ax.set_yscale(y_scale)
|
|
188
|
+
except Exception:
|
|
189
|
+
pass
|
|
190
|
+
for value in params.get("ref_lines") or []:
|
|
191
|
+
try:
|
|
192
|
+
line = ax.axhline(float(value), color="#666666", linestyle="--", linewidth=1)
|
|
193
|
+
line._statstudio_reference = True
|
|
194
|
+
except (TypeError, ValueError):
|
|
195
|
+
continue
|
|
196
|
+
for value in params.get("ref_lines_x") or []:
|
|
197
|
+
try:
|
|
198
|
+
line = ax.axvline(float(value), color="#666666", linestyle=":", linewidth=1)
|
|
199
|
+
line._statstudio_reference = True
|
|
200
|
+
except (TypeError, ValueError):
|
|
201
|
+
continue
|
|
202
|
+
for annotation in params.get("annotations") or []:
|
|
203
|
+
if not isinstance(annotation, dict):
|
|
204
|
+
continue
|
|
205
|
+
try:
|
|
206
|
+
ax.annotate(
|
|
207
|
+
str(annotation.get("text", "")),
|
|
208
|
+
xy=(float(annotation.get("x")), float(annotation.get("y"))),
|
|
209
|
+
xytext=(5, 5),
|
|
210
|
+
textcoords="offset points",
|
|
211
|
+
fontsize=8,
|
|
212
|
+
color="#333333",
|
|
213
|
+
)
|
|
214
|
+
except (TypeError, ValueError):
|
|
215
|
+
continue
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def build_figure(spec: PlotSpec) -> Figure:
|
|
219
|
+
builder = BUILDERS.get(spec.kind)
|
|
220
|
+
if builder is None:
|
|
221
|
+
from statstudio import plugins
|
|
222
|
+
|
|
223
|
+
plugin = plugins.registry.plots.get(spec.kind)
|
|
224
|
+
if plugin is None:
|
|
225
|
+
raise ValueError(f"Unknown plot type: {spec.kind}")
|
|
226
|
+
figure = plugin.build(spec)
|
|
227
|
+
else:
|
|
228
|
+
figure = builder(spec)
|
|
229
|
+
apply_row_styles(figure, spec)
|
|
230
|
+
if spec.kind in _OPTION_AWARE:
|
|
231
|
+
_apply_labels_and_legend(figure, spec)
|
|
232
|
+
else:
|
|
233
|
+
_apply_scale_and_references(figure, spec)
|
|
234
|
+
_apply_labels_and_legend(figure, spec)
|
|
235
|
+
apply_axis_scales(figure, spec)
|
|
236
|
+
apply_data_limits(figure, spec)
|
|
237
|
+
apply_axis_limits(figure, spec)
|
|
238
|
+
return figure
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def save_figure(spec: PlotSpec, path: str) -> None:
|
|
242
|
+
figure = build_figure(spec)
|
|
243
|
+
try:
|
|
244
|
+
figure.savefig(path, dpi=150, bbox_inches="tight")
|
|
245
|
+
finally:
|
|
246
|
+
try:
|
|
247
|
+
import matplotlib.pyplot as plt
|
|
248
|
+
|
|
249
|
+
plt.close(figure)
|
|
250
|
+
except Exception:
|
|
251
|
+
pass
|
statstudio/plugins.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, Callable, Literal
|
|
6
|
+
|
|
7
|
+
from statstudio.stats.results import AnalysisResult, PlotSpec
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class ParamSpec:
|
|
12
|
+
name: str
|
|
13
|
+
kind: Literal["column", "columns", "int", "float", "bool", "choice", "text"]
|
|
14
|
+
label: str = ""
|
|
15
|
+
default: Any = None
|
|
16
|
+
choices: tuple[str, ...] = ()
|
|
17
|
+
required: bool = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class AnalysisContext:
|
|
22
|
+
table: Any
|
|
23
|
+
frame: Any
|
|
24
|
+
params: dict[str, Any]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class AnalysisPlugin:
|
|
29
|
+
id: str
|
|
30
|
+
label: str
|
|
31
|
+
run: Callable[[AnalysisContext], AnalysisResult]
|
|
32
|
+
category: str = "Plugins"
|
|
33
|
+
params: tuple[ParamSpec, ...] = ()
|
|
34
|
+
primary_plots: tuple[str, ...] = ()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class PlotPlugin:
|
|
39
|
+
kind: str
|
|
40
|
+
label: str
|
|
41
|
+
build: Callable[[PlotSpec], Any]
|
|
42
|
+
roles: tuple[str, ...] = ("x", "y", "group", "facet")
|
|
43
|
+
build_plotly: Callable[[PlotSpec], Any] | None = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PluginRegistry:
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
self.analyses: dict[str, AnalysisPlugin] = {}
|
|
49
|
+
self.plots: dict[str, PlotPlugin] = {}
|
|
50
|
+
self.errors: list[str] = []
|
|
51
|
+
self.discovered = False
|
|
52
|
+
|
|
53
|
+
def register_analysis(self, plugin: AnalysisPlugin) -> AnalysisPlugin:
|
|
54
|
+
if plugin.id in self.analyses:
|
|
55
|
+
raise ValueError(f"Duplicate analysis plugin: {plugin.id}")
|
|
56
|
+
self.analyses[plugin.id] = plugin
|
|
57
|
+
return plugin
|
|
58
|
+
|
|
59
|
+
def register_plot(self, plugin: PlotPlugin) -> PlotPlugin:
|
|
60
|
+
if plugin.kind in self.plots:
|
|
61
|
+
raise ValueError(f"Duplicate plot plugin: {plugin.kind}")
|
|
62
|
+
self.plots[plugin.kind] = plugin
|
|
63
|
+
return plugin
|
|
64
|
+
|
|
65
|
+
def discover(self) -> None:
|
|
66
|
+
if self.discovered:
|
|
67
|
+
return
|
|
68
|
+
self.discovered = True
|
|
69
|
+
for group, register in (
|
|
70
|
+
("statstudio.analyses", self.register_analysis),
|
|
71
|
+
("statstudio.plots", self.register_plot),
|
|
72
|
+
):
|
|
73
|
+
try:
|
|
74
|
+
entry_points = importlib.metadata.entry_points(group=group)
|
|
75
|
+
except Exception as exc: # pragma: no cover - metadata backend failures
|
|
76
|
+
self.errors.append(f"{group}: {exc}")
|
|
77
|
+
continue
|
|
78
|
+
for entry_point in entry_points:
|
|
79
|
+
try:
|
|
80
|
+
register(entry_point.load())
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
self.errors.append(f"{entry_point.name}: {exc}")
|
|
83
|
+
|
|
84
|
+
def plot_definitions(self) -> dict[str, dict[str, Any]]:
|
|
85
|
+
return {kind: {"label": plugin.label, "roles": list(plugin.roles)} for kind, plugin in self.plots.items()}
|
|
86
|
+
|
|
87
|
+
def run_analysis(self, plugin_id: str, table, params: dict[str, Any] | None = None) -> AnalysisResult:
|
|
88
|
+
plugin = self.analyses.get(plugin_id)
|
|
89
|
+
if plugin is None:
|
|
90
|
+
raise KeyError(f"Unknown analysis plugin: {plugin_id}")
|
|
91
|
+
context = AnalysisContext(table=table, frame=table.analysis_df(honor_modeling=True), params=dict(params or {}))
|
|
92
|
+
return plugin.run(context)
|
|
93
|
+
|
|
94
|
+
def build_plot(self, spec: PlotSpec):
|
|
95
|
+
plugin = self.plots.get(spec.kind)
|
|
96
|
+
if plugin is None:
|
|
97
|
+
raise KeyError(f"Unknown plot plugin: {spec.kind}")
|
|
98
|
+
return plugin.build(spec)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
registry = PluginRegistry()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def run_analysis(plugin_id: str, table, params: dict[str, Any] | None = None) -> AnalysisResult:
|
|
105
|
+
registry.discover()
|
|
106
|
+
return registry.run_analysis(plugin_id, table, params)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def build_plot(spec: PlotSpec):
|
|
110
|
+
registry.discover()
|
|
111
|
+
return registry.build_plot(spec)
|