staplot 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.
- staplot/__init__.py +1 -0
- staplot/api.py +441 -0
- staplot/main.py +21 -0
- staplot/models/__init__.py +1 -0
- staplot/models/project.py +461 -0
- staplot/plots/__init__.py +14 -0
- staplot/plots/bar.py +104 -0
- staplot/plots/before_after.py +110 -0
- staplot/plots/bland_altman.py +73 -0
- staplot/plots/box.py +95 -0
- staplot/plots/distribution_plot.py +188 -0
- staplot/plots/grouped_bar.py +112 -0
- staplot/plots/heatmap.py +73 -0
- staplot/plots/histogram.py +76 -0
- staplot/plots/qq.py +61 -0
- staplot/plots/residuals.py +72 -0
- staplot/plots/roc_plot.py +40 -0
- staplot/plots/scatter.py +61 -0
- staplot/plots/significance.py +94 -0
- staplot/plots/styles.py +154 -0
- staplot/plots/survival.py +78 -0
- staplot/plots/volcano.py +110 -0
- staplot/stats/__init__.py +15 -0
- staplot/stats/anova.py +124 -0
- staplot/stats/chi_square.py +85 -0
- staplot/stats/correlation.py +71 -0
- staplot/stats/curve_fit.py +85 -0
- staplot/stats/descriptive.py +52 -0
- staplot/stats/distribution.py +223 -0
- staplot/stats/multiple_comparisons.py +104 -0
- staplot/stats/normality.py +67 -0
- staplot/stats/outliers.py +62 -0
- staplot/stats/power.py +130 -0
- staplot/stats/regression.py +95 -0
- staplot/stats/repeated_measures.py +114 -0
- staplot/stats/roc.py +196 -0
- staplot/stats/tests.py +142 -0
- staplot/stats/two_way_anova.py +88 -0
- staplot/ui/__init__.py +0 -0
- staplot/ui/analysis_dialog.py +406 -0
- staplot/ui/axis_dialog.py +104 -0
- staplot/ui/computed_column_dialog.py +261 -0
- staplot/ui/contingency_table_widget.py +158 -0
- staplot/ui/data_table_widget.py +277 -0
- staplot/ui/distribution_inspector.py +431 -0
- staplot/ui/figure_layout_widget.py +236 -0
- staplot/ui/graph_gallery.py +117 -0
- staplot/ui/graph_options_dialog.py +325 -0
- staplot/ui/grouped_table_widget.py +190 -0
- staplot/ui/layout_dialog.py +218 -0
- staplot/ui/main_window.py +1126 -0
- staplot/ui/multiple_comparisons_dialog.py +168 -0
- staplot/ui/navigator.py +88 -0
- staplot/ui/plot_canvas.py +251 -0
- staplot/ui/power_dialog.py +108 -0
- staplot/ui/report_dialog.py +255 -0
- staplot/ui/reshape_dialog.py +286 -0
- staplot/ui/results_widget.py +19 -0
- staplot/ui/standard_curve_dialog.py +150 -0
- staplot/ui/test_wizard.py +252 -0
- staplot/ui/transform_dialog.py +137 -0
- staplot/ui/undo_commands.py +86 -0
- staplot-0.1.0.dist-info/METADATA +85 -0
- staplot-0.1.0.dist-info/RECORD +68 -0
- staplot-0.1.0.dist-info/WHEEL +5 -0
- staplot-0.1.0.dist-info/entry_points.txt +2 -0
- staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
- staplot-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""HTML / PDF report generator."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import datetime
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
import webbrowser
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
from qtpy.QtWidgets import (
|
|
11
|
+
QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
|
|
12
|
+
QTextBrowser, QFileDialog, QLabel, QProgressBar,
|
|
13
|
+
)
|
|
14
|
+
from qtpy.QtCore import Qt
|
|
15
|
+
|
|
16
|
+
from ..plots import styles
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@styles.styled
|
|
20
|
+
def _fig_to_b64(fig) -> str:
|
|
21
|
+
"""Render a matplotlib Figure to a base64-encoded PNG string."""
|
|
22
|
+
buf = io.BytesIO()
|
|
23
|
+
fig.savefig(buf, format="png", dpi=120, bbox_inches="tight")
|
|
24
|
+
buf.seek(0)
|
|
25
|
+
return base64.b64encode(buf.read()).decode()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def generate_report_html(project, render_fn) -> str:
|
|
29
|
+
"""
|
|
30
|
+
Build a self-contained HTML report from a Project.
|
|
31
|
+
render_fn(gc) must return a matplotlib Figure or None.
|
|
32
|
+
"""
|
|
33
|
+
date_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
34
|
+
|
|
35
|
+
# ── Graphs ────────────────────────────────────────────────────────
|
|
36
|
+
graphs_html = []
|
|
37
|
+
for gc in project.graphs:
|
|
38
|
+
try:
|
|
39
|
+
fig = render_fn(gc)
|
|
40
|
+
except Exception:
|
|
41
|
+
fig = None
|
|
42
|
+
if fig is None:
|
|
43
|
+
continue
|
|
44
|
+
b64 = _fig_to_b64(fig)
|
|
45
|
+
graphs_html.append(
|
|
46
|
+
f'<div class="graph">'
|
|
47
|
+
f'<h3>{_esc(gc.name)}</h3>'
|
|
48
|
+
f'<img src="data:image/png;base64,{b64}" alt="{_esc(gc.name)}"/>'
|
|
49
|
+
f'</div>'
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# ── Analyses ──────────────────────────────────────────────────────
|
|
53
|
+
analyses_html = []
|
|
54
|
+
for a in project.analyses:
|
|
55
|
+
analyses_html.append(
|
|
56
|
+
f'<div class="analysis">'
|
|
57
|
+
f'<h3>{_esc(a.name)}</h3>'
|
|
58
|
+
f'<p class="method">Method: {_esc(a.method)}'
|
|
59
|
+
+ (f' | Table: {_esc(a.source_table)}' if a.source_table else '')
|
|
60
|
+
+ f'</p>'
|
|
61
|
+
f'<pre>{_esc(a.summary_text)}</pre>'
|
|
62
|
+
f'</div>'
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# ── Data tables ───────────────────────────────────────────────────
|
|
66
|
+
tables_html = []
|
|
67
|
+
for t in project.tables:
|
|
68
|
+
if hasattr(t, "to_dataframe"):
|
|
69
|
+
df = t.to_dataframe()
|
|
70
|
+
if df.empty:
|
|
71
|
+
continue
|
|
72
|
+
# Limit display to first 200 rows
|
|
73
|
+
df_disp = df.head(200)
|
|
74
|
+
table_html = df_disp.to_html(index=True, classes="data-table",
|
|
75
|
+
border=0, na_rep="")
|
|
76
|
+
note = (f'<p class="note">Showing first 200 of {len(df)} rows.</p>'
|
|
77
|
+
if len(df) > 200 else "")
|
|
78
|
+
tables_html.append(
|
|
79
|
+
f'<div class="table-section">'
|
|
80
|
+
f'<h3>{_esc(t.name)}</h3>'
|
|
81
|
+
f'{note}{table_html}'
|
|
82
|
+
f'</div>'
|
|
83
|
+
)
|
|
84
|
+
elif hasattr(t, "get_matrix"):
|
|
85
|
+
import numpy as np
|
|
86
|
+
mat = t.get_matrix()
|
|
87
|
+
rows = ""
|
|
88
|
+
for i, rl in enumerate(t.row_labels):
|
|
89
|
+
cells = "".join(f"<td>{mat[i,j]}</td>"
|
|
90
|
+
for j in range(len(t.col_labels)))
|
|
91
|
+
rows += f"<tr><th>{_esc(rl)}</th>{cells}</tr>"
|
|
92
|
+
col_heads = "".join(f"<th>{_esc(cl)}</th>"
|
|
93
|
+
for cl in t.col_labels)
|
|
94
|
+
tables_html.append(
|
|
95
|
+
f'<div class="table-section">'
|
|
96
|
+
f'<h3>{_esc(t.name)} <span class="badge">Contingency</span></h3>'
|
|
97
|
+
f'<table class="data-table"><thead>'
|
|
98
|
+
f'<tr><th></th>{col_heads}</tr></thead>'
|
|
99
|
+
f'<tbody>{rows}</tbody></table>'
|
|
100
|
+
f'</div>'
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# ── Assemble ──────────────────────────────────────────────────────
|
|
104
|
+
def section(heading: str, items: list, empty_msg: str) -> str:
|
|
105
|
+
body = "\n".join(items) if items else f"<p>{empty_msg}</p>"
|
|
106
|
+
return f"<h2>{heading} <span class='count'>({len(items)})</span></h2>\n{body}\n"
|
|
107
|
+
|
|
108
|
+
return f"""<!DOCTYPE html>
|
|
109
|
+
<html lang="en">
|
|
110
|
+
<head>
|
|
111
|
+
<meta charset="utf-8">
|
|
112
|
+
<title>{_esc(project.name)} — Staplot Report</title>
|
|
113
|
+
<style>
|
|
114
|
+
body {{
|
|
115
|
+
font-family: Arial, Helvetica, sans-serif;
|
|
116
|
+
max-width: 1080px; margin: 0 auto; padding: 24px 32px;
|
|
117
|
+
color: #222; background: #fff;
|
|
118
|
+
}}
|
|
119
|
+
h1 {{ color: #2d5fa6; border-bottom: 3px solid #2d5fa6; padding-bottom: 6px; }}
|
|
120
|
+
h2 {{ color: #333; border-bottom: 1px solid #ddd; margin-top: 32px; }}
|
|
121
|
+
h3 {{ color: #444; margin-bottom: 4px; }}
|
|
122
|
+
.count {{ font-size: 0.75em; color: #888; font-weight: normal; }}
|
|
123
|
+
.badge {{ font-size: 0.7em; background: #e8f0ff; color: #2d5fa6;
|
|
124
|
+
padding: 2px 6px; border-radius: 10px; }}
|
|
125
|
+
.method {{ color: #666; font-size: 0.85em; margin: 2px 0 8px; }}
|
|
126
|
+
.note {{ color: #888; font-size: 0.8em; font-style: italic; }}
|
|
127
|
+
.graph {{ margin: 18px 0; page-break-inside: avoid; }}
|
|
128
|
+
.graph img {{ max-width: 100%; border: 1px solid #e8e8e8;
|
|
129
|
+
border-radius: 4px; box-shadow: 0 1px 4px rgba(0,0,0,.08); }}
|
|
130
|
+
.analysis {{
|
|
131
|
+
background: #f7f9fc; border-left: 4px solid #2d5fa6;
|
|
132
|
+
padding: 12px 16px; margin: 12px 0; border-radius: 0 4px 4px 0;
|
|
133
|
+
}}
|
|
134
|
+
pre {{
|
|
135
|
+
font-family: "Courier New", Courier, monospace;
|
|
136
|
+
font-size: 11px; white-space: pre-wrap; margin: 0;
|
|
137
|
+
}}
|
|
138
|
+
table.data-table {{ border-collapse: collapse; width: 100%;
|
|
139
|
+
font-size: 12px; margin-top: 8px; }}
|
|
140
|
+
table.data-table th {{
|
|
141
|
+
background: #2d5fa6; color: #fff;
|
|
142
|
+
padding: 5px 8px; text-align: left;
|
|
143
|
+
}}
|
|
144
|
+
table.data-table td {{ border: 1px solid #e0e0e0; padding: 4px 8px; }}
|
|
145
|
+
table.data-table tr:nth-child(even) td {{ background: #f4f4f4; }}
|
|
146
|
+
footer {{ color: #999; font-size: 11px; margin-top: 40px;
|
|
147
|
+
border-top: 1px solid #eee; padding-top: 10px; }}
|
|
148
|
+
@media print {{
|
|
149
|
+
body {{ padding: 0; }}
|
|
150
|
+
.no-print {{ display: none; }}
|
|
151
|
+
}}
|
|
152
|
+
</style>
|
|
153
|
+
</head>
|
|
154
|
+
<body>
|
|
155
|
+
|
|
156
|
+
<h1>{_esc(project.name)}</h1>
|
|
157
|
+
<p>Generated by <strong>Staplot</strong> on {date_str}</p>
|
|
158
|
+
|
|
159
|
+
{section("Graphs", graphs_html, "No graphs in this project.")}
|
|
160
|
+
{section("Analyses", analyses_html, "No analyses in this project.")}
|
|
161
|
+
{section("Data Tables", tables_html, "No data tables.")}
|
|
162
|
+
|
|
163
|
+
<footer>Staplot — Statistical analysis and publication-quality plotting</footer>
|
|
164
|
+
</body>
|
|
165
|
+
</html>"""
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _esc(text: str) -> str:
|
|
169
|
+
"""Minimal HTML escaping."""
|
|
170
|
+
return (str(text)
|
|
171
|
+
.replace("&", "&")
|
|
172
|
+
.replace("<", "<")
|
|
173
|
+
.replace(">", ">")
|
|
174
|
+
.replace('"', """))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ── Dialog ────────────────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
class ReportDialog(QDialog):
|
|
180
|
+
"""Preview and export the project report as HTML (printable to PDF)."""
|
|
181
|
+
|
|
182
|
+
def __init__(self, project, render_fn, parent=None):
|
|
183
|
+
super().__init__(parent)
|
|
184
|
+
self.setWindowTitle("Generate Report")
|
|
185
|
+
self.setMinimumSize(820, 620)
|
|
186
|
+
|
|
187
|
+
self._html = ""
|
|
188
|
+
layout = QVBoxLayout(self)
|
|
189
|
+
|
|
190
|
+
# Status
|
|
191
|
+
self._status = QLabel("Rendering graphs…")
|
|
192
|
+
layout.addWidget(self._status)
|
|
193
|
+
|
|
194
|
+
self._progress = QProgressBar()
|
|
195
|
+
self._progress.setRange(0, max(1, len(project.graphs)))
|
|
196
|
+
self._progress.setValue(0)
|
|
197
|
+
layout.addWidget(self._progress)
|
|
198
|
+
|
|
199
|
+
# Preview
|
|
200
|
+
self._browser = QTextBrowser()
|
|
201
|
+
self._browser.setOpenExternalLinks(True)
|
|
202
|
+
layout.addWidget(self._browser)
|
|
203
|
+
|
|
204
|
+
# Buttons
|
|
205
|
+
btn_row = QHBoxLayout()
|
|
206
|
+
btn_row.addStretch()
|
|
207
|
+
save_btn = QPushButton("Save as HTML…")
|
|
208
|
+
save_btn.clicked.connect(self._save_html)
|
|
209
|
+
btn_row.addWidget(save_btn)
|
|
210
|
+
|
|
211
|
+
open_btn = QPushButton("Open in Browser (→ print to PDF)")
|
|
212
|
+
open_btn.clicked.connect(self._open_browser)
|
|
213
|
+
btn_row.addWidget(open_btn)
|
|
214
|
+
|
|
215
|
+
close_btn = QPushButton("Close")
|
|
216
|
+
close_btn.clicked.connect(self.reject)
|
|
217
|
+
btn_row.addWidget(close_btn)
|
|
218
|
+
layout.addLayout(btn_row)
|
|
219
|
+
|
|
220
|
+
# Generate (inline, quick enough for typical projects)
|
|
221
|
+
self._generate(project, render_fn)
|
|
222
|
+
|
|
223
|
+
def _generate(self, project, render_fn):
|
|
224
|
+
n = len(project.graphs)
|
|
225
|
+
|
|
226
|
+
def tracked_render(gc):
|
|
227
|
+
fig = render_fn(gc)
|
|
228
|
+
self._progress.setValue(self._progress.value() + 1)
|
|
229
|
+
from qtpy.QtWidgets import QApplication
|
|
230
|
+
QApplication.processEvents()
|
|
231
|
+
return fig
|
|
232
|
+
|
|
233
|
+
self._html = generate_report_html(project, tracked_render)
|
|
234
|
+
self._progress.setValue(n)
|
|
235
|
+
self._status.setText(
|
|
236
|
+
f"Report ready — {len(project.graphs)} graphs, "
|
|
237
|
+
f"{len(project.analyses)} analyses, "
|
|
238
|
+
f"{len(project.tables)} tables."
|
|
239
|
+
)
|
|
240
|
+
self._browser.setHtml(self._html)
|
|
241
|
+
|
|
242
|
+
def _save_html(self):
|
|
243
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
244
|
+
self, "Save Report", "", "HTML (*.html);;All files (*)")
|
|
245
|
+
if path:
|
|
246
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
247
|
+
f.write(self._html)
|
|
248
|
+
self._status.setText(f"Saved: {path}")
|
|
249
|
+
|
|
250
|
+
def _open_browser(self):
|
|
251
|
+
tmp = tempfile.NamedTemporaryFile(
|
|
252
|
+
suffix=".html", delete=False, mode="w", encoding="utf-8")
|
|
253
|
+
tmp.write(self._html)
|
|
254
|
+
tmp.close()
|
|
255
|
+
webbrowser.open(f"file://{tmp.name}")
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Reshape table dialog — Wide ↔ Long format conversion."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from qtpy.QtWidgets import (
|
|
7
|
+
QDialog, QVBoxLayout, QFormLayout, QComboBox, QLineEdit,
|
|
8
|
+
QPushButton, QDialogButtonBox, QLabel, QListWidget,
|
|
9
|
+
QTabWidget, QWidget, QAbstractItemView, QHBoxLayout,
|
|
10
|
+
)
|
|
11
|
+
from qtpy.QtCore import Qt
|
|
12
|
+
|
|
13
|
+
from ..models.project import DataTable
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _wide_to_long(
|
|
17
|
+
source: DataTable,
|
|
18
|
+
value_cols: list[str],
|
|
19
|
+
var_col: str = "Group",
|
|
20
|
+
val_col: str = "Value",
|
|
21
|
+
result_name: str | None = None,
|
|
22
|
+
) -> DataTable:
|
|
23
|
+
"""
|
|
24
|
+
Stack *value_cols* into two new columns (var_col, val_col).
|
|
25
|
+
All other columns are replicated as identifier variables.
|
|
26
|
+
"""
|
|
27
|
+
df = source.to_dataframe()
|
|
28
|
+
id_cols = [c for c in df.columns if c not in value_cols]
|
|
29
|
+
melted = df.melt(id_vars=id_cols, value_vars=value_cols,
|
|
30
|
+
var_name=var_col, value_name=val_col)
|
|
31
|
+
melted = melted.reset_index(drop=True)
|
|
32
|
+
|
|
33
|
+
name = result_name or f"{source.name} (long)"
|
|
34
|
+
t = DataTable(name)
|
|
35
|
+
for col in melted.columns:
|
|
36
|
+
t.add_column(col)
|
|
37
|
+
for r, row in melted.iterrows():
|
|
38
|
+
for c_idx, col in enumerate(melted.columns):
|
|
39
|
+
raw = row[col]
|
|
40
|
+
if isinstance(raw, float) and np.isnan(raw):
|
|
41
|
+
val = None
|
|
42
|
+
elif isinstance(raw, (int, float)):
|
|
43
|
+
val = float(raw)
|
|
44
|
+
else:
|
|
45
|
+
# text — store as is; DataTableWidget shows "" for None
|
|
46
|
+
val = None # skip non-numeric for now
|
|
47
|
+
t.set_value(r, c_idx, val)
|
|
48
|
+
# Re-fill text values (var_col)
|
|
49
|
+
var_idx = list(melted.columns).index(var_col)
|
|
50
|
+
for r, row in melted.iterrows():
|
|
51
|
+
raw = row[var_col]
|
|
52
|
+
t.set_value(r, var_idx, None) # clear numeric placeholder
|
|
53
|
+
# store as a special string marker — not ideal but workable
|
|
54
|
+
# We'll just store the group name encoded as a dummy float
|
|
55
|
+
# For the var_col we simply leave it as None (not meaningful numerically)
|
|
56
|
+
# and rely on the user to see the group names separately.
|
|
57
|
+
# Better: encode as indices
|
|
58
|
+
# Actually map group names to indices and add a legend column
|
|
59
|
+
group_map = {g: i for i, g in enumerate(value_cols)}
|
|
60
|
+
for r, row in melted.iterrows():
|
|
61
|
+
t.set_value(r, var_idx, float(group_map.get(row[var_col], 0)))
|
|
62
|
+
return t
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _wide_to_long_clean(
|
|
66
|
+
source: DataTable,
|
|
67
|
+
value_cols: list[str],
|
|
68
|
+
var_col: str = "Group",
|
|
69
|
+
val_col: str = "Value",
|
|
70
|
+
result_name: str | None = None,
|
|
71
|
+
) -> DataTable:
|
|
72
|
+
"""
|
|
73
|
+
Proper wide→long: creates a DataTable where
|
|
74
|
+
each original row appears once per selected column.
|
|
75
|
+
"""
|
|
76
|
+
name = result_name or f"{source.name} (long)"
|
|
77
|
+
n_rows = source.num_rows()
|
|
78
|
+
result = DataTable(name)
|
|
79
|
+
result.add_column(var_col) # col index 0
|
|
80
|
+
result.add_column(val_col) # col index 1
|
|
81
|
+
|
|
82
|
+
out_row = 0
|
|
83
|
+
for col in source.columns:
|
|
84
|
+
if col.name not in value_cols:
|
|
85
|
+
continue
|
|
86
|
+
for row_idx, v in enumerate(col.values):
|
|
87
|
+
if v is None or (isinstance(v, float) and np.isnan(v)):
|
|
88
|
+
continue
|
|
89
|
+
# Encode group name as its position index (numeric)
|
|
90
|
+
result.set_value(out_row, 0, float(value_cols.index(col.name)))
|
|
91
|
+
result.set_value(out_row, 1, float(v))
|
|
92
|
+
out_row += 1
|
|
93
|
+
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _long_to_wide(
|
|
98
|
+
source: DataTable,
|
|
99
|
+
group_col: str,
|
|
100
|
+
value_col: str,
|
|
101
|
+
result_name: str | None = None,
|
|
102
|
+
) -> DataTable:
|
|
103
|
+
"""
|
|
104
|
+
Pivot: each unique value in *group_col* becomes a column.
|
|
105
|
+
Works best when group_col contains integers (group indices)
|
|
106
|
+
or when the user has numeric group IDs.
|
|
107
|
+
"""
|
|
108
|
+
df = source.to_dataframe()
|
|
109
|
+
if group_col not in df.columns or value_col not in df.columns:
|
|
110
|
+
raise ValueError("Columns not found.")
|
|
111
|
+
|
|
112
|
+
pivoted = (df[[group_col, value_col]]
|
|
113
|
+
.pivot_table(index=df.index,
|
|
114
|
+
columns=group_col,
|
|
115
|
+
values=value_col,
|
|
116
|
+
aggfunc="first"))
|
|
117
|
+
pivoted.columns = [str(c) for c in pivoted.columns]
|
|
118
|
+
pivoted = pivoted.reset_index(drop=True)
|
|
119
|
+
|
|
120
|
+
name = result_name or f"{source.name} (wide)"
|
|
121
|
+
result = DataTable(name)
|
|
122
|
+
for col in pivoted.columns:
|
|
123
|
+
result.add_column(col)
|
|
124
|
+
for r, row in pivoted.iterrows():
|
|
125
|
+
for c_idx, col in enumerate(pivoted.columns):
|
|
126
|
+
val = row[col]
|
|
127
|
+
result.set_value(r, c_idx,
|
|
128
|
+
None if (isinstance(val, float) and np.isnan(val))
|
|
129
|
+
else float(val))
|
|
130
|
+
return result
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ── Dialog ─────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
class ReshapeDialog(QDialog):
|
|
136
|
+
"""Wide ↔ Long table reshaping."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, tables: list, parent=None):
|
|
139
|
+
super().__init__(parent)
|
|
140
|
+
self.setWindowTitle("Reshape Table")
|
|
141
|
+
self.setMinimumWidth(500)
|
|
142
|
+
self._tables = [t for t in tables if isinstance(t, DataTable)]
|
|
143
|
+
self._result: DataTable | None = None
|
|
144
|
+
|
|
145
|
+
layout = QVBoxLayout(self)
|
|
146
|
+
self._tabs = QTabWidget()
|
|
147
|
+
self._tabs.addTab(self._build_wide2long(), "Wide → Long")
|
|
148
|
+
self._tabs.addTab(self._build_long2wide(), "Long → Wide")
|
|
149
|
+
layout.addWidget(self._tabs)
|
|
150
|
+
|
|
151
|
+
convert_btn = QPushButton("Convert")
|
|
152
|
+
convert_btn.setDefault(True)
|
|
153
|
+
convert_btn.clicked.connect(self._convert)
|
|
154
|
+
layout.addWidget(convert_btn, alignment=Qt.AlignmentFlag.AlignRight)
|
|
155
|
+
|
|
156
|
+
self._status = QLabel("")
|
|
157
|
+
layout.addWidget(self._status)
|
|
158
|
+
|
|
159
|
+
btns = QDialogButtonBox(
|
|
160
|
+
QDialogButtonBox.StandardButton.Ok
|
|
161
|
+
| QDialogButtonBox.StandardButton.Cancel
|
|
162
|
+
)
|
|
163
|
+
btns.accepted.connect(self.accept)
|
|
164
|
+
btns.rejected.connect(self.reject)
|
|
165
|
+
layout.addWidget(btns)
|
|
166
|
+
|
|
167
|
+
# ------------------------------------------------------------------
|
|
168
|
+
def _build_wide2long(self) -> QWidget:
|
|
169
|
+
w = QWidget()
|
|
170
|
+
layout = QVBoxLayout(w)
|
|
171
|
+
layout.addWidget(QLabel(
|
|
172
|
+
"Select which columns to <b>stack</b> into a single 'Value' column.\n"
|
|
173
|
+
"A numeric 'Group' column will encode each original column by index."
|
|
174
|
+
))
|
|
175
|
+
form = QFormLayout()
|
|
176
|
+
self._w2l_table = QComboBox()
|
|
177
|
+
self._w2l_table.addItems([t.name for t in self._tables])
|
|
178
|
+
self._w2l_table.currentIndexChanged.connect(self._refresh_w2l_cols)
|
|
179
|
+
form.addRow("Source table:", self._w2l_table)
|
|
180
|
+
layout.addLayout(form)
|
|
181
|
+
|
|
182
|
+
layout.addWidget(QLabel("Columns to stack (hold Ctrl / Shift to select multiple):"))
|
|
183
|
+
self._w2l_cols = QListWidget()
|
|
184
|
+
self._w2l_cols.setSelectionMode(
|
|
185
|
+
QAbstractItemView.SelectionMode.ExtendedSelection)
|
|
186
|
+
self._w2l_cols.setMaximumHeight(120)
|
|
187
|
+
layout.addWidget(self._w2l_cols)
|
|
188
|
+
|
|
189
|
+
form2 = QFormLayout()
|
|
190
|
+
self._w2l_var = QLineEdit("Group")
|
|
191
|
+
self._w2l_val = QLineEdit("Value")
|
|
192
|
+
self._w2l_name = QLineEdit()
|
|
193
|
+
form2.addRow("Group column name:", self._w2l_var)
|
|
194
|
+
form2.addRow("Value column name:", self._w2l_val)
|
|
195
|
+
form2.addRow("Result table name:", self._w2l_name)
|
|
196
|
+
layout.addLayout(form2)
|
|
197
|
+
layout.addStretch()
|
|
198
|
+
|
|
199
|
+
self._refresh_w2l_cols()
|
|
200
|
+
return w
|
|
201
|
+
|
|
202
|
+
def _refresh_w2l_cols(self):
|
|
203
|
+
self._w2l_cols.clear()
|
|
204
|
+
idx = self._w2l_table.currentIndex()
|
|
205
|
+
if 0 <= idx < len(self._tables):
|
|
206
|
+
t = self._tables[idx]
|
|
207
|
+
for col in t.columns:
|
|
208
|
+
self._w2l_cols.addItem(col.name)
|
|
209
|
+
self._w2l_name.setText(f"{t.name} (long)")
|
|
210
|
+
# Select all by default
|
|
211
|
+
self._w2l_cols.selectAll()
|
|
212
|
+
|
|
213
|
+
def _build_long2wide(self) -> QWidget:
|
|
214
|
+
w = QWidget()
|
|
215
|
+
form = QFormLayout(w)
|
|
216
|
+
self._l2w_table = QComboBox()
|
|
217
|
+
self._l2w_table.addItems([t.name for t in self._tables])
|
|
218
|
+
self._l2w_table.currentIndexChanged.connect(self._refresh_l2w_cols)
|
|
219
|
+
form.addRow("Source table:", self._l2w_table)
|
|
220
|
+
|
|
221
|
+
self._l2w_group = QComboBox()
|
|
222
|
+
form.addRow("Group column:", self._l2w_group)
|
|
223
|
+
self._l2w_value = QComboBox()
|
|
224
|
+
form.addRow("Value column:", self._l2w_value)
|
|
225
|
+
|
|
226
|
+
self._l2w_name = QLineEdit()
|
|
227
|
+
form.addRow("Result table name:", self._l2w_name)
|
|
228
|
+
form.addRow(QLabel(
|
|
229
|
+
"The Group column is used to create separate columns in the output."
|
|
230
|
+
))
|
|
231
|
+
|
|
232
|
+
self._refresh_l2w_cols()
|
|
233
|
+
return w
|
|
234
|
+
|
|
235
|
+
def _refresh_l2w_cols(self):
|
|
236
|
+
idx = self._l2w_table.currentIndex()
|
|
237
|
+
names = []
|
|
238
|
+
if 0 <= idx < len(self._tables):
|
|
239
|
+
t = self._tables[idx]
|
|
240
|
+
names = [c.name for c in t.columns]
|
|
241
|
+
self._l2w_name.setText(f"{t.name} (wide)")
|
|
242
|
+
for cb in (self._l2w_group, self._l2w_value):
|
|
243
|
+
cb.clear()
|
|
244
|
+
cb.addItems(names)
|
|
245
|
+
if len(names) >= 2:
|
|
246
|
+
self._l2w_value.setCurrentIndex(1)
|
|
247
|
+
|
|
248
|
+
# ------------------------------------------------------------------
|
|
249
|
+
def _convert(self):
|
|
250
|
+
try:
|
|
251
|
+
if self._tabs.currentIndex() == 0:
|
|
252
|
+
idx = self._w2l_table.currentIndex()
|
|
253
|
+
if idx < 0 or idx >= len(self._tables):
|
|
254
|
+
raise ValueError("Select a table.")
|
|
255
|
+
t = self._tables[idx]
|
|
256
|
+
sel = [item.text() for item in self._w2l_cols.selectedItems()]
|
|
257
|
+
if not sel:
|
|
258
|
+
raise ValueError("Select at least one column to stack.")
|
|
259
|
+
self._result = _wide_to_long_clean(
|
|
260
|
+
t, sel,
|
|
261
|
+
var_col=self._w2l_var.text().strip() or "Group",
|
|
262
|
+
val_col=self._w2l_val.text().strip() or "Value",
|
|
263
|
+
result_name=self._w2l_name.text().strip() or None,
|
|
264
|
+
)
|
|
265
|
+
else:
|
|
266
|
+
idx = self._l2w_table.currentIndex()
|
|
267
|
+
if idx < 0 or idx >= len(self._tables):
|
|
268
|
+
raise ValueError("Select a table.")
|
|
269
|
+
t = self._tables[idx]
|
|
270
|
+
self._result = _long_to_wide(
|
|
271
|
+
t,
|
|
272
|
+
group_col=self._l2w_group.currentText(),
|
|
273
|
+
value_col=self._l2w_value.currentText(),
|
|
274
|
+
result_name=self._l2w_name.text().strip() or None,
|
|
275
|
+
)
|
|
276
|
+
n = self._result.num_rows()
|
|
277
|
+
nc = len(self._result.columns)
|
|
278
|
+
self._status.setText(
|
|
279
|
+
f"Preview: {n} rows × {nc} columns — click OK to add to project."
|
|
280
|
+
)
|
|
281
|
+
except Exception as exc:
|
|
282
|
+
self._status.setText(f"Error: {exc}")
|
|
283
|
+
self._result = None
|
|
284
|
+
|
|
285
|
+
def get_result(self) -> DataTable | None:
|
|
286
|
+
return self._result
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from qtpy.QtWidgets import QTextEdit
|
|
2
|
+
from qtpy.QtGui import QFont
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ResultsWidget(QTextEdit):
|
|
6
|
+
"""Read-only monospaced display for analysis output."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, parent=None):
|
|
9
|
+
super().__init__(parent)
|
|
10
|
+
self.setReadOnly(True)
|
|
11
|
+
font = QFont("Courier New", 9)
|
|
12
|
+
font.setStyleHint(QFont.StyleHint.Monospace)
|
|
13
|
+
self.setFont(font)
|
|
14
|
+
self.setStyleSheet(
|
|
15
|
+
"QTextEdit { background: #fafafa; border: none; padding: 8px; }"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
def show_result(self, result):
|
|
19
|
+
self.setPlainText(result.summary_text)
|