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,94 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy import stats
|
|
5
|
+
|
|
6
|
+
from statstudio.plots.common import color, frame, new_figure, numeric, style_axes
|
|
7
|
+
from statstudio.stats.results import PlotSpec
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _selected_parameters(data, requested) -> list[str]:
|
|
11
|
+
available = list(dict.fromkeys(data["Parameter"].astype(str).tolist()))
|
|
12
|
+
if requested:
|
|
13
|
+
selected = [str(name) for name in requested if str(name) in available]
|
|
14
|
+
if selected:
|
|
15
|
+
return selected
|
|
16
|
+
return available
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def bayes_trace(spec: PlotSpec):
|
|
20
|
+
data = frame(spec)
|
|
21
|
+
parameters = _selected_parameters(data, spec.params.get("parameters"))
|
|
22
|
+
if not parameters:
|
|
23
|
+
raise ValueError("No posterior parameters to plot.")
|
|
24
|
+
parameters = parameters[:6]
|
|
25
|
+
figure = new_figure(7.5, max(2.4, 1.8 * len(parameters)))
|
|
26
|
+
for index, parameter in enumerate(parameters, start=1):
|
|
27
|
+
ax = figure.add_subplot(len(parameters), 1, index)
|
|
28
|
+
subset = data[data["Parameter"].astype(str) == parameter]
|
|
29
|
+
for chain_index, (_, chain) in enumerate(subset.groupby("Chain", sort=True)):
|
|
30
|
+
ax.plot(chain["Draw"], numeric(chain, "Value"), color=color(chain_index), linewidth=0.7, alpha=0.85)
|
|
31
|
+
style_axes(ax, parameter, "Draw" if index == len(parameters) else "", "Value")
|
|
32
|
+
return figure
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def bayes_posterior(spec: PlotSpec):
|
|
36
|
+
data = frame(spec)
|
|
37
|
+
parameters = _selected_parameters(data, spec.params.get("parameters"))
|
|
38
|
+
if not parameters:
|
|
39
|
+
raise ValueError("No posterior parameters to plot.")
|
|
40
|
+
parameters = parameters[:6]
|
|
41
|
+
figure = new_figure(7.5, max(2.4, 2.0 * ((len(parameters) + 1) // 2)))
|
|
42
|
+
columns = 2 if len(parameters) > 1 else 1
|
|
43
|
+
rows = int(np.ceil(len(parameters) / columns))
|
|
44
|
+
for index, parameter in enumerate(parameters, start=1):
|
|
45
|
+
ax = figure.add_subplot(rows, columns, index)
|
|
46
|
+
values = numeric(data[data["Parameter"].astype(str) == parameter], "Value").dropna().to_numpy(dtype=float)
|
|
47
|
+
if len(values) > 2 and np.unique(values).size > 2:
|
|
48
|
+
grid = np.linspace(float(values.min()), float(values.max()), 300)
|
|
49
|
+
density = stats.gaussian_kde(values)(grid)
|
|
50
|
+
ax.plot(grid, density, color=color(0), linewidth=1.8)
|
|
51
|
+
ax.fill_between(grid, density, color=color(0), alpha=0.18)
|
|
52
|
+
else:
|
|
53
|
+
ax.hist(values, bins=spec.params.get("bins", "auto"), color=color(0), edgecolor="white", alpha=0.85)
|
|
54
|
+
style_axes(ax, parameter, parameter, "Density")
|
|
55
|
+
return figure
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def bayes_forest(spec: PlotSpec):
|
|
59
|
+
data = frame(spec)
|
|
60
|
+
required = {"Term", "Mean", "HDI Low", "HDI High"}
|
|
61
|
+
if data.empty or not required.issubset(data.columns):
|
|
62
|
+
return new_figure()
|
|
63
|
+
terms = data["Term"].astype(str).tolist()
|
|
64
|
+
means = numeric(data, "Mean").to_numpy(dtype=float)
|
|
65
|
+
lows = numeric(data, "HDI Low").to_numpy(dtype=float)
|
|
66
|
+
highs = numeric(data, "HDI High").to_numpy(dtype=float)
|
|
67
|
+
figure = new_figure(7.0, max(2.5, 0.55 * len(terms) + 1.5))
|
|
68
|
+
ax = figure.add_subplot(111)
|
|
69
|
+
positions = np.arange(len(terms))
|
|
70
|
+
errors = np.vstack([means - lows, highs - means])
|
|
71
|
+
ax.errorbar(means, positions, xerr=errors, fmt="o", color=color(0), ecolor=color(0), capsize=4, markersize=6)
|
|
72
|
+
ax.axvline(float(spec.params.get("reference", 0.0)), color="#777777", linestyle="--", linewidth=1)
|
|
73
|
+
ax.set_yticks(positions)
|
|
74
|
+
ax.set_yticklabels(terms)
|
|
75
|
+
ax.invert_yaxis()
|
|
76
|
+
style_axes(ax, spec.title or "Posterior Intervals", "Estimate", "")
|
|
77
|
+
return figure
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def bayes_ppc(spec: PlotSpec):
|
|
81
|
+
data = frame(spec)
|
|
82
|
+
index = numeric(data, "Index")
|
|
83
|
+
observed = numeric(data, "Observed")
|
|
84
|
+
predicted = numeric(data, "Predicted")
|
|
85
|
+
lower = numeric(data, "Lower")
|
|
86
|
+
upper = numeric(data, "Upper")
|
|
87
|
+
figure = new_figure()
|
|
88
|
+
ax = figure.add_subplot(111)
|
|
89
|
+
ax.fill_between(index, lower, upper, color=color(0), alpha=0.18, label="Posterior interval")
|
|
90
|
+
ax.plot(index, predicted, color=color(0), linewidth=1.8, label="Predicted")
|
|
91
|
+
ax.scatter(index, observed, color=color(1), s=22, alpha=0.85, label="Observed")
|
|
92
|
+
ax.legend(frameon=False, fontsize=8)
|
|
93
|
+
style_axes(ax, spec.title or "Posterior Predictive Check", "Observation", "Value")
|
|
94
|
+
return figure
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import numpy as np
|
|
5
|
+
from matplotlib import dates as mdates
|
|
6
|
+
from matplotlib.colors import to_rgba
|
|
7
|
+
from matplotlib.figure import Figure
|
|
8
|
+
|
|
9
|
+
from statstudio.stats.results import PlotSpec
|
|
10
|
+
|
|
11
|
+
COLORS = [
|
|
12
|
+
"#3c78b4",
|
|
13
|
+
"#d95f02",
|
|
14
|
+
"#1b9e77",
|
|
15
|
+
"#7570b3",
|
|
16
|
+
"#e7298a",
|
|
17
|
+
"#66a61e",
|
|
18
|
+
"#e6ab02",
|
|
19
|
+
"#a6761d",
|
|
20
|
+
"#1f78b4",
|
|
21
|
+
"#fb9a99",
|
|
22
|
+
"#33a02c",
|
|
23
|
+
"#cab2d6",
|
|
24
|
+
"#ff7f00",
|
|
25
|
+
"#6a3d9a",
|
|
26
|
+
"#b15928",
|
|
27
|
+
"#8dd3c7",
|
|
28
|
+
"#bebada",
|
|
29
|
+
"#80b1d3",
|
|
30
|
+
"#fdb462",
|
|
31
|
+
"#b3de69",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def new_figure(width: float = 7.0, height: float = 4.5) -> Figure:
|
|
36
|
+
figure = Figure(figsize=(width, height), constrained_layout=True, dpi=100)
|
|
37
|
+
figure.patch.set_facecolor("white")
|
|
38
|
+
return figure
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def frame(spec: PlotSpec) -> pd.DataFrame:
|
|
42
|
+
if spec.data is None:
|
|
43
|
+
raise ValueError("This plot has no data.")
|
|
44
|
+
return spec.data
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def column(frame: pd.DataFrame, name: str) -> pd.Series:
|
|
48
|
+
if name not in frame.columns:
|
|
49
|
+
raise KeyError(name)
|
|
50
|
+
return frame[name]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def numeric(frame: pd.DataFrame, name: str) -> pd.Series:
|
|
54
|
+
return pd.to_numeric(frame[name], errors="coerce")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def error_column_name(params: dict, frame: pd.DataFrame) -> str | None:
|
|
58
|
+
for key in ("error_column", "error"):
|
|
59
|
+
name = params.get(key)
|
|
60
|
+
if isinstance(name, str) and name in frame.columns:
|
|
61
|
+
return name
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def color(index: int) -> str:
|
|
66
|
+
return COLORS[index % len(COLORS)]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def style_axes(ax, title: str = "", xlabel: str = "", ylabel: str = "") -> None:
|
|
70
|
+
if title:
|
|
71
|
+
ax.set_title(title, fontsize=11, fontweight="bold")
|
|
72
|
+
if xlabel:
|
|
73
|
+
ax.set_xlabel(xlabel)
|
|
74
|
+
if ylabel:
|
|
75
|
+
ax.set_ylabel(ylabel)
|
|
76
|
+
ax.grid(True, color="#e4e8ee", linewidth=0.7, alpha=0.8)
|
|
77
|
+
ax.set_axisbelow(True)
|
|
78
|
+
for spine in ("top", "right"):
|
|
79
|
+
ax.spines[spine].set_visible(False)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def rotate_labels(ax, rotation: int = 45, horizontalalignment: str | None = None) -> None:
|
|
83
|
+
alignment = horizontalalignment or ("right" if rotation else "center")
|
|
84
|
+
for label in ax.get_xticklabels():
|
|
85
|
+
label.set_rotation(rotation)
|
|
86
|
+
label.set_horizontalalignment(alignment)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def row_ids_for(spec: PlotSpec, index) -> list:
|
|
90
|
+
"""Row identifiers aligned with a plot's point order."""
|
|
91
|
+
if spec.row_ids is not None and len(spec.row_ids) == len(index):
|
|
92
|
+
return list(spec.row_ids)
|
|
93
|
+
return list(index)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def attach_row_ids(artist, row_ids) -> None:
|
|
97
|
+
"""Record the source row identifiers on a Matplotlib artist."""
|
|
98
|
+
try:
|
|
99
|
+
artist._statstudio_row_ids = list(row_ids)
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def artist_row_ids(artist) -> list | None:
|
|
105
|
+
ids = getattr(artist, "_statstudio_row_ids", None)
|
|
106
|
+
return ids if ids is not None else None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def apply_row_styles(figure: Figure, spec: PlotSpec) -> None:
|
|
110
|
+
"""Apply per-row colors from the data table to collections that carry row IDs."""
|
|
111
|
+
styles = spec.row_styles or {}
|
|
112
|
+
if not styles:
|
|
113
|
+
return
|
|
114
|
+
for ax in figure.axes:
|
|
115
|
+
for collection in ax.collections:
|
|
116
|
+
ids = artist_row_ids(collection)
|
|
117
|
+
if not ids:
|
|
118
|
+
continue
|
|
119
|
+
try:
|
|
120
|
+
base = np.asarray(collection.get_facecolor())
|
|
121
|
+
except Exception:
|
|
122
|
+
continue
|
|
123
|
+
if base.size == 0:
|
|
124
|
+
continue
|
|
125
|
+
colors = np.array([base[i % len(base)] for i in range(len(ids))])
|
|
126
|
+
changed = False
|
|
127
|
+
for position, row_id in enumerate(ids):
|
|
128
|
+
state = styles.get(row_id)
|
|
129
|
+
if not state:
|
|
130
|
+
continue
|
|
131
|
+
value = state.get("color")
|
|
132
|
+
if not value:
|
|
133
|
+
continue
|
|
134
|
+
try:
|
|
135
|
+
colors[position] = to_rgba(value)
|
|
136
|
+
changed = True
|
|
137
|
+
except Exception:
|
|
138
|
+
continue
|
|
139
|
+
if changed:
|
|
140
|
+
try:
|
|
141
|
+
collection.set_facecolor(colors)
|
|
142
|
+
except Exception:
|
|
143
|
+
pass
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _numeric_array(values):
|
|
147
|
+
try:
|
|
148
|
+
array = np.asarray(values)
|
|
149
|
+
except Exception:
|
|
150
|
+
return None
|
|
151
|
+
if array.dtype.kind == "M":
|
|
152
|
+
try:
|
|
153
|
+
array = mdates.date2num(array.astype("datetime64[ms]").astype(object))
|
|
154
|
+
except Exception:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
array = np.asarray(array, dtype=float).ravel()
|
|
158
|
+
except (TypeError, ValueError):
|
|
159
|
+
return None
|
|
160
|
+
array = array[np.isfinite(array)]
|
|
161
|
+
if array.size == 0:
|
|
162
|
+
return None
|
|
163
|
+
return array
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _is_twin_axis(ax, primary) -> bool:
|
|
167
|
+
if ax is primary:
|
|
168
|
+
return False
|
|
169
|
+
try:
|
|
170
|
+
return ax.get_shared_x_axes().joined(ax, primary)
|
|
171
|
+
except Exception:
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _collect_extents(ax, drop_zero_base: bool):
|
|
176
|
+
xs: list = []
|
|
177
|
+
ys: list = []
|
|
178
|
+
for line in ax.lines:
|
|
179
|
+
if getattr(line, "_statstudio_reference", False):
|
|
180
|
+
continue
|
|
181
|
+
try:
|
|
182
|
+
x_values, y_values = line.get_data()
|
|
183
|
+
except Exception:
|
|
184
|
+
continue
|
|
185
|
+
xs.append(x_values)
|
|
186
|
+
ys.append(y_values)
|
|
187
|
+
for collection in ax.collections:
|
|
188
|
+
try:
|
|
189
|
+
offsets = collection.get_offsets()
|
|
190
|
+
except Exception:
|
|
191
|
+
offsets = None
|
|
192
|
+
if offsets is None:
|
|
193
|
+
continue
|
|
194
|
+
array = _numeric_array(offsets)
|
|
195
|
+
if array is None:
|
|
196
|
+
continue
|
|
197
|
+
if np.asarray(offsets).ndim == 2 and np.asarray(offsets).shape[1] >= 2:
|
|
198
|
+
matrix = np.asarray(offsets, dtype=float)
|
|
199
|
+
matrix = matrix[np.isfinite(matrix).all(axis=1)]
|
|
200
|
+
if matrix.size:
|
|
201
|
+
xs.append(matrix[:, 0])
|
|
202
|
+
ys.append(matrix[:, 1])
|
|
203
|
+
for patch in ax.patches:
|
|
204
|
+
try:
|
|
205
|
+
y0 = float(patch.get_y())
|
|
206
|
+
height = float(patch.get_height())
|
|
207
|
+
x0 = float(patch.get_x())
|
|
208
|
+
width = float(patch.get_width())
|
|
209
|
+
except Exception:
|
|
210
|
+
continue
|
|
211
|
+
xs.append([x0, x0 + width])
|
|
212
|
+
if drop_zero_base and y0 == 0.0:
|
|
213
|
+
ys.append([height])
|
|
214
|
+
else:
|
|
215
|
+
ys.append([y0, y0 + height])
|
|
216
|
+
for image in getattr(ax, "images", []):
|
|
217
|
+
try:
|
|
218
|
+
extent = image.get_extent()
|
|
219
|
+
except Exception:
|
|
220
|
+
continue
|
|
221
|
+
xs.append([extent[0], extent[1]])
|
|
222
|
+
ys.append([extent[2], extent[3]])
|
|
223
|
+
return xs, ys
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _padded(values, log_scale: bool):
|
|
227
|
+
array = _numeric_array(values)
|
|
228
|
+
if array is None:
|
|
229
|
+
return None
|
|
230
|
+
low = float(array.min())
|
|
231
|
+
high = float(array.max())
|
|
232
|
+
if log_scale:
|
|
233
|
+
positive = array[array > 0]
|
|
234
|
+
if positive.size == 0:
|
|
235
|
+
return None
|
|
236
|
+
low = float(positive.min()) / 1.05
|
|
237
|
+
high = float(positive.max()) * 1.05
|
|
238
|
+
return low, high
|
|
239
|
+
if not (np.isfinite(low) and np.isfinite(high)):
|
|
240
|
+
return None
|
|
241
|
+
if high <= low:
|
|
242
|
+
pad = abs(low) * 0.05 or 1.0
|
|
243
|
+
else:
|
|
244
|
+
pad = (high - low) * 0.05
|
|
245
|
+
return low - pad, high + pad
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def apply_axis_scales(figure: Figure, spec: PlotSpec) -> None:
|
|
249
|
+
"""Apply axis scale settings (linear/log) from the plot parameters."""
|
|
250
|
+
params = spec.params or {}
|
|
251
|
+
axes = list(figure.axes)
|
|
252
|
+
if not axes:
|
|
253
|
+
return
|
|
254
|
+
x_scale = params.get("x_scale") or ("log" if params.get("log_x") else None)
|
|
255
|
+
y_scale = params.get("y_scale") or ("log" if params.get("log_y") else None)
|
|
256
|
+
for ax in axes[:1]:
|
|
257
|
+
if x_scale in {"log", "linear"}:
|
|
258
|
+
try:
|
|
259
|
+
ax.set_xscale(x_scale)
|
|
260
|
+
except Exception:
|
|
261
|
+
pass
|
|
262
|
+
if y_scale in {"log", "linear"}:
|
|
263
|
+
try:
|
|
264
|
+
ax.set_yscale(y_scale)
|
|
265
|
+
except Exception:
|
|
266
|
+
pass
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def apply_data_limits(figure: Figure, spec: PlotSpec | None = None) -> None:
|
|
270
|
+
"""Set axis limits from the actual plotted data instead of sticky zero baselines."""
|
|
271
|
+
kind = getattr(spec, "kind", "") if spec is not None else ""
|
|
272
|
+
if kind == "mosaic":
|
|
273
|
+
return
|
|
274
|
+
axes = list(figure.axes)
|
|
275
|
+
if not axes:
|
|
276
|
+
return
|
|
277
|
+
primary = axes[0]
|
|
278
|
+
for ax in axes:
|
|
279
|
+
if getattr(ax, "name", "") == "3d":
|
|
280
|
+
continue
|
|
281
|
+
try:
|
|
282
|
+
if ax.get_label() == "<colorbar>":
|
|
283
|
+
continue
|
|
284
|
+
except Exception:
|
|
285
|
+
pass
|
|
286
|
+
drop_zero_base = kind != "box"
|
|
287
|
+
xs, ys = _collect_extents(ax, drop_zero_base=drop_zero_base)
|
|
288
|
+
if xs:
|
|
289
|
+
x_limits = _padded(np.concatenate([_numeric_array(x) for x in xs if _numeric_array(x) is not None] or [np.array([])]), ax.get_xscale() == "log")
|
|
290
|
+
else:
|
|
291
|
+
x_limits = None
|
|
292
|
+
if ys:
|
|
293
|
+
y_limits = _padded(np.concatenate([_numeric_array(y) for y in ys if _numeric_array(y) is not None] or [np.array([])]), ax.get_yscale() == "log")
|
|
294
|
+
else:
|
|
295
|
+
y_limits = None
|
|
296
|
+
try:
|
|
297
|
+
if x_limits is not None and not _is_twin_axis(ax, primary):
|
|
298
|
+
ax.set_xlim(*x_limits, auto=False)
|
|
299
|
+
if y_limits is not None:
|
|
300
|
+
ax.set_ylim(*y_limits, auto=False)
|
|
301
|
+
except Exception:
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def apply_axis_limits(figure: Figure, spec: PlotSpec) -> None:
|
|
306
|
+
"""Apply user-entered axis minimums/maximums; these win over auto limits."""
|
|
307
|
+
params = spec.params or {}
|
|
308
|
+
axes = list(figure.axes)
|
|
309
|
+
if not axes:
|
|
310
|
+
return
|
|
311
|
+
primary = axes[0]
|
|
312
|
+
for key, setter, side in (
|
|
313
|
+
("x_min", primary.set_xlim, "left"),
|
|
314
|
+
("x_max", primary.set_xlim, "right"),
|
|
315
|
+
("y_min", primary.set_ylim, "bottom"),
|
|
316
|
+
("y_max", primary.set_ylim, "top"),
|
|
317
|
+
):
|
|
318
|
+
value = params.get(key)
|
|
319
|
+
if value is None or value == "":
|
|
320
|
+
continue
|
|
321
|
+
try:
|
|
322
|
+
numeric = float(value)
|
|
323
|
+
except (TypeError, ValueError):
|
|
324
|
+
continue
|
|
325
|
+
if not np.isfinite(numeric):
|
|
326
|
+
continue
|
|
327
|
+
if key.startswith("x") and primary.get_xscale() == "log" and numeric <= 0:
|
|
328
|
+
continue
|
|
329
|
+
if key.startswith("y") and primary.get_yscale() == "log" and numeric <= 0:
|
|
330
|
+
continue
|
|
331
|
+
try:
|
|
332
|
+
setter(**{side: numeric})
|
|
333
|
+
except Exception:
|
|
334
|
+
continue
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from scipy import stats
|
|
6
|
+
from scipy.cluster.hierarchy import dendrogram
|
|
7
|
+
|
|
8
|
+
from statstudio.plots.common import color, frame, new_figure, numeric, style_axes
|
|
9
|
+
from statstudio.stats.results import PlotSpec
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def actual_predicted(spec: PlotSpec):
|
|
13
|
+
data = frame(spec)
|
|
14
|
+
actual = numeric(data, spec.params["actual"])
|
|
15
|
+
predicted = numeric(data, spec.params["predicted"])
|
|
16
|
+
figure = new_figure()
|
|
17
|
+
ax = figure.add_subplot(111)
|
|
18
|
+
ax.scatter(predicted, actual, s=30, alpha=0.8, color=color(0))
|
|
19
|
+
if spec.params.get("identity", True):
|
|
20
|
+
values = pd.concat([actual, predicted]).dropna()
|
|
21
|
+
if not values.empty:
|
|
22
|
+
low, high = values.min(), values.max()
|
|
23
|
+
ax.plot([low, high], [low, high], linestyle="--", color="#666666")
|
|
24
|
+
style_axes(ax, spec.title or "Actual vs Predicted", "Predicted", "Actual")
|
|
25
|
+
return figure
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def residual_fitted(spec: PlotSpec):
|
|
29
|
+
data = frame(spec)
|
|
30
|
+
fitted = numeric(data, spec.params["fitted"])
|
|
31
|
+
residual = numeric(data, spec.params["residual"])
|
|
32
|
+
figure = new_figure()
|
|
33
|
+
ax = figure.add_subplot(111)
|
|
34
|
+
ax.scatter(fitted, residual, s=30, alpha=0.8, color=color(0))
|
|
35
|
+
if spec.params.get("zero", True):
|
|
36
|
+
ax.axhline(0, color="#333333", linestyle="--", linewidth=1)
|
|
37
|
+
style_axes(ax, spec.title or "Residuals vs Fitted", "Fitted", "Residual")
|
|
38
|
+
return figure
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def qq(spec: PlotSpec):
|
|
42
|
+
data = frame(spec)
|
|
43
|
+
values = numeric(data, spec.params["column"]).dropna()
|
|
44
|
+
figure = new_figure()
|
|
45
|
+
ax = figure.add_subplot(111)
|
|
46
|
+
if len(values) < 2:
|
|
47
|
+
ax.text(0.5, 0.5, "Not enough data for a Q-Q plot", ha="center", va="center", transform=ax.transAxes, fontsize=10, color="#888888")
|
|
48
|
+
style_axes(ax, spec.title or "Normal Q-Q Plot", "Theoretical Quantiles", "Sample Quantiles")
|
|
49
|
+
return figure
|
|
50
|
+
(osm, osr), (slope, intercept, r) = stats.probplot(values, dist="norm")
|
|
51
|
+
ax.scatter(osm, osr, s=26, alpha=0.8, color=color(0))
|
|
52
|
+
ax.plot(osm, slope * osm + intercept, color=color(1), linewidth=1.6)
|
|
53
|
+
style_axes(ax, spec.title or "Normal Q-Q Plot", "Theoretical Quantiles", "Sample Quantiles")
|
|
54
|
+
return figure
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def roc(spec: PlotSpec):
|
|
58
|
+
fpr = spec.params["fpr"]
|
|
59
|
+
tpr = spec.params["tpr"]
|
|
60
|
+
auc = spec.params.get("auc")
|
|
61
|
+
figure = new_figure(5.5, 5)
|
|
62
|
+
ax = figure.add_subplot(111)
|
|
63
|
+
ax.plot(fpr, tpr, color=color(0), linewidth=2, label=f"AUC = {auc:.3f}" if auc is not None else None)
|
|
64
|
+
ax.plot([0, 1], [0, 1], linestyle="--", color="#777777", linewidth=1)
|
|
65
|
+
if auc is not None:
|
|
66
|
+
ax.legend(frameon=False)
|
|
67
|
+
style_axes(ax, spec.title or "ROC Curve", "False Positive Rate", "True Positive Rate")
|
|
68
|
+
return figure
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def scree(spec: PlotSpec):
|
|
72
|
+
eigenvalues = spec.params["eigenvalues"]
|
|
73
|
+
figure = new_figure()
|
|
74
|
+
ax = figure.add_subplot(111)
|
|
75
|
+
x = np.arange(1, len(eigenvalues) + 1)
|
|
76
|
+
ax.plot(x, eigenvalues, marker="o", color=color(0), linewidth=2)
|
|
77
|
+
ax.bar(x, eigenvalues, color=color(0), alpha=0.18)
|
|
78
|
+
style_axes(ax, spec.title or "Scree Plot", "Component", "Eigenvalue")
|
|
79
|
+
return figure
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def pca_biplot(spec: PlotSpec):
|
|
83
|
+
data = frame(spec)
|
|
84
|
+
figure = new_figure()
|
|
85
|
+
ax = figure.add_subplot(111)
|
|
86
|
+
if "PC1" in data.columns and "PC2" in data.columns:
|
|
87
|
+
ax.scatter(data["PC1"], data["PC2"], s=28, alpha=0.7, color=color(0))
|
|
88
|
+
loadings = spec.params.get("loadings") or []
|
|
89
|
+
if loadings:
|
|
90
|
+
scale = max(abs(data["PC1"]).max() if "PC1" in data.columns else 1, abs(data["PC2"]).max() if "PC2" in data.columns else 1) * 0.8
|
|
91
|
+
for item in loadings:
|
|
92
|
+
if "PC1" in item and "PC2" in item:
|
|
93
|
+
x, y = item["PC1"], item["PC2"]
|
|
94
|
+
ax.arrow(0, 0, x * scale, y * scale, color=color(1), width=0.002, head_width=0.04, alpha=0.8)
|
|
95
|
+
ax.text(x * scale * 1.08, y * scale * 1.08, str(item.get("Variable", "")), color=color(1), fontsize=8)
|
|
96
|
+
style_axes(ax, spec.title or "PCA Biplot", "PC1", "PC2")
|
|
97
|
+
return figure
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def cluster_scatter(spec: PlotSpec):
|
|
101
|
+
data = frame(spec)
|
|
102
|
+
x_name = spec.params["x"]
|
|
103
|
+
y_name = spec.params["y"]
|
|
104
|
+
group_name = spec.params.get("group")
|
|
105
|
+
figure = new_figure()
|
|
106
|
+
ax = figure.add_subplot(111)
|
|
107
|
+
if group_name and group_name in data.columns:
|
|
108
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False)):
|
|
109
|
+
ax.scatter(numeric(chunk, x_name), numeric(chunk, y_name), s=30, alpha=0.8, color=color(index), label=f"Cluster {label}")
|
|
110
|
+
ax.legend(frameon=False, fontsize=8)
|
|
111
|
+
else:
|
|
112
|
+
ax.scatter(numeric(data, x_name), numeric(data, y_name), s=30, color=color(0))
|
|
113
|
+
style_axes(ax, spec.title or "Cluster Scatter", str(x_name), str(y_name))
|
|
114
|
+
return figure
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def dendrogram_plot(spec: PlotSpec):
|
|
118
|
+
linkage_matrix = np.asarray(spec.params["linkage"], dtype=float)
|
|
119
|
+
figure = new_figure(8, 4.5)
|
|
120
|
+
ax = figure.add_subplot(111)
|
|
121
|
+
dendrogram(linkage_matrix, ax=ax, no_labels=True, color_threshold=0)
|
|
122
|
+
style_axes(ax, spec.title or "Dendrogram", "Observations", "Distance")
|
|
123
|
+
return figure
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def weibull_plot(spec: PlotSpec):
|
|
127
|
+
import numpy as np
|
|
128
|
+
|
|
129
|
+
times = np.asarray(spec.params.get("time", []), dtype=float)
|
|
130
|
+
censored = np.asarray(spec.params.get("censored", []), dtype=bool)
|
|
131
|
+
shape = float(spec.params.get("shape", 1.0))
|
|
132
|
+
scale = float(spec.params.get("scale", 1.0))
|
|
133
|
+
figure = new_figure()
|
|
134
|
+
ax = figure.add_subplot(111)
|
|
135
|
+
if len(times):
|
|
136
|
+
order = np.argsort(times)
|
|
137
|
+
times = times[order]
|
|
138
|
+
if censored.size != times.size:
|
|
139
|
+
raise ValueError("The censoring vector must match the number of survival times.")
|
|
140
|
+
censored = censored[order]
|
|
141
|
+
survival = 1.0
|
|
142
|
+
xs, ys = [], []
|
|
143
|
+
n = len(times)
|
|
144
|
+
for index, (value, censor) in enumerate(zip(times, censored)):
|
|
145
|
+
at_risk = n - index
|
|
146
|
+
if not censor and at_risk > 0:
|
|
147
|
+
survival *= (1 - 1 / at_risk)
|
|
148
|
+
if 0 < survival < 1 and value > 0:
|
|
149
|
+
xs.append(np.log(value))
|
|
150
|
+
ys.append(np.log(-np.log(survival)))
|
|
151
|
+
ax.scatter(xs, ys, s=22, color=color(0), alpha=0.8, label="Empirical")
|
|
152
|
+
if len(xs) and scale > 0 and shape > 0:
|
|
153
|
+
lo, hi = min(xs), max(xs)
|
|
154
|
+
grid = np.linspace(lo, hi, 100)
|
|
155
|
+
ax.plot(grid, shape * grid - shape * np.log(scale), color=color(1), linewidth=2, label="Weibull fit")
|
|
156
|
+
ax.legend(frameon=False, fontsize=8)
|
|
157
|
+
style_axes(ax, spec.title or "Weibull Probability Plot", "ln(Time)", "ln(-ln S)")
|
|
158
|
+
return figure
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def residual_order(spec: PlotSpec):
|
|
162
|
+
data = frame(spec)
|
|
163
|
+
figure = new_figure()
|
|
164
|
+
ax = figure.add_subplot(111)
|
|
165
|
+
ax.plot(numeric(data, "Observation"), numeric(data, "Residual"), marker="o", markersize=3, linewidth=1.0, color=color(0))
|
|
166
|
+
ax.axhline(0, color="#333333", linestyle="--", linewidth=1)
|
|
167
|
+
style_axes(ax, spec.title or "Residuals vs Observation Order", "Observation", "Residual")
|
|
168
|
+
return figure
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def scale_location(spec: PlotSpec):
|
|
172
|
+
data = frame(spec)
|
|
173
|
+
figure = new_figure()
|
|
174
|
+
ax = figure.add_subplot(111)
|
|
175
|
+
ax.scatter(numeric(data, "Fitted"), numeric(data, "SqrtAbsStdResidual"), s=28, alpha=0.8, color=color(0))
|
|
176
|
+
style_axes(ax, spec.title or "Scale-Location", "Fitted", "sqrt(|Standardized Residual|)")
|
|
177
|
+
return figure
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def leverage(spec: PlotSpec):
|
|
181
|
+
import numpy as np
|
|
182
|
+
|
|
183
|
+
data = frame(spec)
|
|
184
|
+
figure = new_figure()
|
|
185
|
+
ax = figure.add_subplot(111)
|
|
186
|
+
leverage_values = numeric(data, "Leverage")
|
|
187
|
+
residual = numeric(data, "StdResidual")
|
|
188
|
+
cooks = numeric(data, "Cooks")
|
|
189
|
+
finite = np.isfinite(leverage_values) & np.isfinite(residual) & np.isfinite(cooks)
|
|
190
|
+
threshold = spec.params.get("cook_threshold", 4 / max(1, int(finite.sum())))
|
|
191
|
+
maximum = float(np.nanmax(cooks[finite])) if finite.any() else 1.0
|
|
192
|
+
sizes = 24 + 240 * np.clip(cooks[finite] / (maximum or 1), 0, 1)
|
|
193
|
+
colors = [color(4) if value > threshold else color(0) for value in cooks[finite]]
|
|
194
|
+
ax.scatter(leverage_values[finite], residual[finite], s=sizes, alpha=0.8, color=colors)
|
|
195
|
+
ax.axhline(0, color="#333333", linestyle="--", linewidth=1)
|
|
196
|
+
if finite.any():
|
|
197
|
+
ax.axvline(2 * float(leverage_values[finite].mean()), color="#888888", linestyle=":", linewidth=1)
|
|
198
|
+
style_axes(ax, spec.title or "Leverage vs Standardized Residuals", "Leverage", "Standardized Residual")
|
|
199
|
+
return figure
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cooks_distance(spec: PlotSpec):
|
|
203
|
+
data = frame(spec)
|
|
204
|
+
figure = new_figure()
|
|
205
|
+
ax = figure.add_subplot(111)
|
|
206
|
+
observations = numeric(data, "Observation")
|
|
207
|
+
cooks = numeric(data, "Cooks")
|
|
208
|
+
finite = np.isfinite(observations) & np.isfinite(cooks)
|
|
209
|
+
threshold = spec.params.get("cook_threshold", 4 / max(1, int(finite.sum())))
|
|
210
|
+
ax.vlines(observations[finite], 0, cooks[finite], color=color(0), linewidth=1.6)
|
|
211
|
+
ax.axhline(threshold, color=color(4), linestyle="--", linewidth=1, label="4/n threshold")
|
|
212
|
+
ax.legend(frameon=False, fontsize=8)
|
|
213
|
+
style_axes(ax, spec.title or "Cook's Distance", "Observation", "Cook's D")
|
|
214
|
+
return figure
|