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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publication-quality metrics visualization for LandmarkDiff.
|
| 2 |
+
|
| 3 |
+
Generates figures suitable for MICCAI/medical imaging papers:
|
| 4 |
+
- Bar charts comparing procedures and methods
|
| 5 |
+
- Radar plots for multi-metric comparison
|
| 6 |
+
- Box plots for per-sample distributions
|
| 7 |
+
- Heatmaps for Fitzpatrick equity analysis
|
| 8 |
+
- Table formatters for LaTeX
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
from landmarkdiff.metrics_viz import MetricsVisualizer
|
| 12 |
+
|
| 13 |
+
viz = MetricsVisualizer(output_dir="paper/figures")
|
| 14 |
+
|
| 15 |
+
# Bar chart comparing procedures
|
| 16 |
+
viz.procedure_comparison(metrics_by_procedure)
|
| 17 |
+
|
| 18 |
+
# Radar plot for ablation study
|
| 19 |
+
viz.radar_plot(experiments)
|
| 20 |
+
|
| 21 |
+
# Equity heatmap
|
| 22 |
+
viz.fitzpatrick_heatmap(metrics_by_type)
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MetricsVisualizer:
|
| 35 |
+
"""Generate publication-quality figures from evaluation metrics.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
output_dir: Directory to save generated figures.
|
| 39 |
+
dpi: Resolution for saved figures.
|
| 40 |
+
style: Matplotlib style preset.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
# Color palette (colorblind-safe, MICCAI-friendly)
|
| 44 |
+
COLORS = {
|
| 45 |
+
"rhinoplasty": "#4C72B0",
|
| 46 |
+
"blepharoplasty": "#55A868",
|
| 47 |
+
"rhytidectomy": "#C44E52",
|
| 48 |
+
"orthognathic": "#8172B2",
|
| 49 |
+
"baseline": "#CCB974",
|
| 50 |
+
"ours": "#4C72B0",
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
METRIC_LABELS = {
|
| 54 |
+
"ssim": "SSIM",
|
| 55 |
+
"lpips": "LPIPS",
|
| 56 |
+
"fid": "FID",
|
| 57 |
+
"nme": "NME",
|
| 58 |
+
"identity_sim": "ID Sim.",
|
| 59 |
+
"psnr": "PSNR (dB)",
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
METRIC_HIGHER_BETTER = {
|
| 63 |
+
"ssim": True,
|
| 64 |
+
"lpips": False,
|
| 65 |
+
"fid": False,
|
| 66 |
+
"nme": False,
|
| 67 |
+
"identity_sim": True,
|
| 68 |
+
"psnr": True,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
output_dir: str | Path = "figures",
|
| 74 |
+
dpi: int = 300,
|
| 75 |
+
style: str = "seaborn-v0_8-whitegrid",
|
| 76 |
+
) -> None:
|
| 77 |
+
self.output_dir = Path(output_dir)
|
| 78 |
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
self.dpi = dpi
|
| 80 |
+
self.style = style
|
| 81 |
+
|
| 82 |
+
def _get_plt(self):
|
| 83 |
+
"""Import matplotlib with configuration."""
|
| 84 |
+
import matplotlib
|
| 85 |
+
matplotlib.use("Agg")
|
| 86 |
+
import matplotlib.pyplot as plt
|
| 87 |
+
try:
|
| 88 |
+
plt.style.use(self.style)
|
| 89 |
+
except OSError:
|
| 90 |
+
plt.style.use("seaborn-v0_8")
|
| 91 |
+
# Publication font sizes
|
| 92 |
+
plt.rcParams.update({
|
| 93 |
+
"font.size": 10,
|
| 94 |
+
"axes.titlesize": 12,
|
| 95 |
+
"axes.labelsize": 11,
|
| 96 |
+
"xtick.labelsize": 9,
|
| 97 |
+
"ytick.labelsize": 9,
|
| 98 |
+
"legend.fontsize": 9,
|
| 99 |
+
"figure.titlesize": 13,
|
| 100 |
+
})
|
| 101 |
+
return plt
|
| 102 |
+
|
| 103 |
+
# ------------------------------------------------------------------
|
| 104 |
+
# Procedure comparison bar chart
|
| 105 |
+
# ------------------------------------------------------------------
|
| 106 |
+
|
| 107 |
+
def procedure_comparison(
|
| 108 |
+
self,
|
| 109 |
+
metrics_by_procedure: dict[str, dict[str, float]],
|
| 110 |
+
metrics: list[str] | None = None,
|
| 111 |
+
title: str = "Per-Procedure Performance",
|
| 112 |
+
filename: str = "procedure_comparison.pdf",
|
| 113 |
+
) -> Path:
|
| 114 |
+
"""Generate grouped bar chart comparing procedures.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
metrics_by_procedure: {procedure: {metric: value}}.
|
| 118 |
+
metrics: Which metrics to show. None = auto-detect.
|
| 119 |
+
title: Figure title.
|
| 120 |
+
filename: Output filename.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
Path to saved figure.
|
| 124 |
+
"""
|
| 125 |
+
plt = self._get_plt()
|
| 126 |
+
|
| 127 |
+
if metrics is None:
|
| 128 |
+
all_metrics: set[str] = set()
|
| 129 |
+
for m in metrics_by_procedure.values():
|
| 130 |
+
all_metrics.update(m.keys())
|
| 131 |
+
metrics = sorted(all_metrics & set(self.METRIC_LABELS.keys()))
|
| 132 |
+
|
| 133 |
+
procedures = list(metrics_by_procedure.keys())
|
| 134 |
+
n_procs = len(procedures)
|
| 135 |
+
n_metrics = len(metrics)
|
| 136 |
+
|
| 137 |
+
fig, axes = plt.subplots(1, n_metrics, figsize=(3 * n_metrics, 4))
|
| 138 |
+
if n_metrics == 1:
|
| 139 |
+
axes = [axes]
|
| 140 |
+
|
| 141 |
+
for ax, metric in zip(axes, metrics):
|
| 142 |
+
values = [metrics_by_procedure[p].get(metric, 0) for p in procedures]
|
| 143 |
+
colors = [self.COLORS.get(p, "#999999") for p in procedures]
|
| 144 |
+
|
| 145 |
+
bars = ax.bar(range(n_procs), values, color=colors, width=0.6, edgecolor="white")
|
| 146 |
+
ax.set_xticks(range(n_procs))
|
| 147 |
+
ax.set_xticklabels(
|
| 148 |
+
[p[:5].title() for p in procedures],
|
| 149 |
+
rotation=30, ha="right",
|
| 150 |
+
)
|
| 151 |
+
ax.set_ylabel(self.METRIC_LABELS.get(metric, metric))
|
| 152 |
+
ax.set_title(self.METRIC_LABELS.get(metric, metric))
|
| 153 |
+
|
| 154 |
+
# Add value labels on bars
|
| 155 |
+
for bar, val in zip(bars, values):
|
| 156 |
+
ax.text(
|
| 157 |
+
bar.get_x() + bar.get_width() / 2, bar.get_height(),
|
| 158 |
+
f"{val:.3f}", ha="center", va="bottom", fontsize=8,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
fig.suptitle(title, fontweight="bold")
|
| 162 |
+
fig.tight_layout()
|
| 163 |
+
|
| 164 |
+
out_path = self.output_dir / filename
|
| 165 |
+
fig.savefig(out_path, dpi=self.dpi, bbox_inches="tight")
|
| 166 |
+
plt.close(fig)
|
| 167 |
+
return out_path
|
| 168 |
+
|
| 169 |
+
# ------------------------------------------------------------------
|
| 170 |
+
# Radar plot for multi-metric comparison
|
| 171 |
+
# ------------------------------------------------------------------
|
| 172 |
+
|
| 173 |
+
def radar_plot(
|
| 174 |
+
self,
|
| 175 |
+
experiments: dict[str, dict[str, float]],
|
| 176 |
+
metrics: list[str] | None = None,
|
| 177 |
+
title: str = "Multi-Metric Comparison",
|
| 178 |
+
filename: str = "radar_plot.pdf",
|
| 179 |
+
) -> Path:
|
| 180 |
+
"""Generate radar/spider plot for comparing experiments.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
experiments: {experiment_name: {metric: value}}.
|
| 184 |
+
metrics: Which metrics to show.
|
| 185 |
+
title: Figure title.
|
| 186 |
+
filename: Output filename.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
Path to saved figure.
|
| 190 |
+
"""
|
| 191 |
+
plt = self._get_plt()
|
| 192 |
+
|
| 193 |
+
if metrics is None:
|
| 194 |
+
metrics = sorted(
|
| 195 |
+
set.intersection(
|
| 196 |
+
*(set(v.keys()) for v in experiments.values())
|
| 197 |
+
) & set(self.METRIC_LABELS.keys())
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
n_metrics = len(metrics)
|
| 201 |
+
angles = np.linspace(0, 2 * np.pi, n_metrics, endpoint=False).tolist()
|
| 202 |
+
angles += angles[:1] # Close the polygon
|
| 203 |
+
|
| 204 |
+
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={"polar": True})
|
| 205 |
+
|
| 206 |
+
colors = list(self.COLORS.values())
|
| 207 |
+
for i, (name, values_dict) in enumerate(experiments.items()):
|
| 208 |
+
raw_values = []
|
| 209 |
+
for m in metrics:
|
| 210 |
+
val = values_dict.get(m, 0)
|
| 211 |
+
# Normalize: for "lower is better" metrics, invert
|
| 212 |
+
if not self.METRIC_HIGHER_BETTER.get(m, True):
|
| 213 |
+
val = 1 - min(val, 1) # Invert so higher = better on plot
|
| 214 |
+
raw_values.append(val)
|
| 215 |
+
|
| 216 |
+
# Normalize to [0, 1] range
|
| 217 |
+
vals = np.array(raw_values)
|
| 218 |
+
vals = vals / max(vals.max(), 1e-10)
|
| 219 |
+
vals = vals.tolist() + vals[:1].tolist()
|
| 220 |
+
|
| 221 |
+
color = colors[i % len(colors)]
|
| 222 |
+
ax.plot(angles, vals, "o-", linewidth=2, label=name, color=color)
|
| 223 |
+
ax.fill(angles, vals, alpha=0.15, color=color)
|
| 224 |
+
|
| 225 |
+
ax.set_xticks(angles[:-1])
|
| 226 |
+
ax.set_xticklabels([self.METRIC_LABELS.get(m, m) for m in metrics])
|
| 227 |
+
ax.set_ylim(0, 1.1)
|
| 228 |
+
ax.legend(loc="upper right", bbox_to_anchor=(1.3, 1.0))
|
| 229 |
+
ax.set_title(title, fontweight="bold", pad=20)
|
| 230 |
+
|
| 231 |
+
out_path = self.output_dir / filename
|
| 232 |
+
fig.savefig(out_path, dpi=self.dpi, bbox_inches="tight")
|
| 233 |
+
plt.close(fig)
|
| 234 |
+
return out_path
|
| 235 |
+
|
| 236 |
+
# ------------------------------------------------------------------
|
| 237 |
+
# Fitzpatrick equity heatmap
|
| 238 |
+
# ------------------------------------------------------------------
|
| 239 |
+
|
| 240 |
+
def fitzpatrick_heatmap(
|
| 241 |
+
self,
|
| 242 |
+
metrics_by_type: dict[str, dict[str, float]],
|
| 243 |
+
metric: str = "ssim",
|
| 244 |
+
title: str | None = None,
|
| 245 |
+
filename: str = "fitzpatrick_equity.pdf",
|
| 246 |
+
) -> Path:
|
| 247 |
+
"""Generate heatmap showing metric values across Fitzpatrick types and procedures.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
metrics_by_type: {fitzpatrick_type: {procedure: value}}.
|
| 251 |
+
metric: Which metric to visualize.
|
| 252 |
+
title: Figure title.
|
| 253 |
+
filename: Output filename.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
Path to saved figure.
|
| 257 |
+
"""
|
| 258 |
+
plt = self._get_plt()
|
| 259 |
+
|
| 260 |
+
fitz_types = sorted(metrics_by_type.keys())
|
| 261 |
+
procedures = sorted(
|
| 262 |
+
set.union(*(set(v.keys()) for v in metrics_by_type.values()))
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# Build matrix
|
| 266 |
+
matrix = np.zeros((len(fitz_types), len(procedures)))
|
| 267 |
+
for i, ft in enumerate(fitz_types):
|
| 268 |
+
for j, proc in enumerate(procedures):
|
| 269 |
+
matrix[i, j] = metrics_by_type[ft].get(proc, 0)
|
| 270 |
+
|
| 271 |
+
fig, ax = plt.subplots(figsize=(max(6, len(procedures) * 1.5), max(4, len(fitz_types) * 0.8)))
|
| 272 |
+
|
| 273 |
+
cmap = "RdYlGn" if self.METRIC_HIGHER_BETTER.get(metric, True) else "RdYlGn_r"
|
| 274 |
+
im = ax.imshow(matrix, cmap=cmap, aspect="auto")
|
| 275 |
+
|
| 276 |
+
ax.set_xticks(range(len(procedures)))
|
| 277 |
+
ax.set_xticklabels([p.title() for p in procedures], rotation=30, ha="right")
|
| 278 |
+
ax.set_yticks(range(len(fitz_types)))
|
| 279 |
+
ax.set_yticklabels(fitz_types)
|
| 280 |
+
ax.set_ylabel("Fitzpatrick Type")
|
| 281 |
+
|
| 282 |
+
# Annotate cells
|
| 283 |
+
for i in range(len(fitz_types)):
|
| 284 |
+
for j in range(len(procedures)):
|
| 285 |
+
ax.text(j, i, f"{matrix[i, j]:.3f}",
|
| 286 |
+
ha="center", va="center", fontsize=9,
|
| 287 |
+
color="white" if matrix[i, j] < np.median(matrix) else "black")
|
| 288 |
+
|
| 289 |
+
fig.colorbar(im, ax=ax, label=self.METRIC_LABELS.get(metric, metric))
|
| 290 |
+
|
| 291 |
+
if title is None:
|
| 292 |
+
title = f"{self.METRIC_LABELS.get(metric, metric)} by Fitzpatrick Type"
|
| 293 |
+
ax.set_title(title, fontweight="bold")
|
| 294 |
+
fig.tight_layout()
|
| 295 |
+
|
| 296 |
+
out_path = self.output_dir / filename
|
| 297 |
+
fig.savefig(out_path, dpi=self.dpi, bbox_inches="tight")
|
| 298 |
+
plt.close(fig)
|
| 299 |
+
return out_path
|
| 300 |
+
|
| 301 |
+
# ------------------------------------------------------------------
|
| 302 |
+
# Box plots for per-sample distribution
|
| 303 |
+
# ------------------------------------------------------------------
|
| 304 |
+
|
| 305 |
+
def distribution_boxplot(
|
| 306 |
+
self,
|
| 307 |
+
samples_by_group: dict[str, list[float]],
|
| 308 |
+
metric: str = "ssim",
|
| 309 |
+
title: str | None = None,
|
| 310 |
+
filename: str = "distribution.pdf",
|
| 311 |
+
) -> Path:
|
| 312 |
+
"""Generate box plot showing per-sample metric distributions.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
samples_by_group: {group_name: [sample_values]}.
|
| 316 |
+
metric: Metric being plotted.
|
| 317 |
+
title: Figure title.
|
| 318 |
+
filename: Output filename.
|
| 319 |
+
|
| 320 |
+
Returns:
|
| 321 |
+
Path to saved figure.
|
| 322 |
+
"""
|
| 323 |
+
plt = self._get_plt()
|
| 324 |
+
|
| 325 |
+
groups = list(samples_by_group.keys())
|
| 326 |
+
data = [samples_by_group[g] for g in groups]
|
| 327 |
+
|
| 328 |
+
fig, ax = plt.subplots(figsize=(max(6, len(groups) * 1.2), 5))
|
| 329 |
+
|
| 330 |
+
bp = ax.boxplot(
|
| 331 |
+
data, patch_artist=True, widths=0.6,
|
| 332 |
+
medianprops={"color": "black", "linewidth": 1.5},
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
colors = [self.COLORS.get(g, "#4C72B0") for g in groups]
|
| 336 |
+
for patch, color in zip(bp["boxes"], colors):
|
| 337 |
+
patch.set_facecolor(color)
|
| 338 |
+
patch.set_alpha(0.7)
|
| 339 |
+
|
| 340 |
+
ax.set_xticklabels(
|
| 341 |
+
[g.title() for g in groups],
|
| 342 |
+
rotation=30, ha="right",
|
| 343 |
+
)
|
| 344 |
+
ax.set_ylabel(self.METRIC_LABELS.get(metric, metric))
|
| 345 |
+
|
| 346 |
+
if title is None:
|
| 347 |
+
title = f"{self.METRIC_LABELS.get(metric, metric)} Distribution"
|
| 348 |
+
ax.set_title(title, fontweight="bold")
|
| 349 |
+
|
| 350 |
+
# Add sample count annotations
|
| 351 |
+
for i, (g, vals) in enumerate(zip(groups, data)):
|
| 352 |
+
ax.text(i + 1, ax.get_ylim()[0], f"n={len(vals)}",
|
| 353 |
+
ha="center", va="bottom", fontsize=8, color="gray")
|
| 354 |
+
|
| 355 |
+
fig.tight_layout()
|
| 356 |
+
out_path = self.output_dir / filename
|
| 357 |
+
fig.savefig(out_path, dpi=self.dpi, bbox_inches="tight")
|
| 358 |
+
plt.close(fig)
|
| 359 |
+
return out_path
|
| 360 |
+
|
| 361 |
+
# ------------------------------------------------------------------
|
| 362 |
+
# LaTeX table formatter
|
| 363 |
+
# ------------------------------------------------------------------
|
| 364 |
+
|
| 365 |
+
@staticmethod
|
| 366 |
+
def to_latex_table(
|
| 367 |
+
rows: list[dict[str, Any]],
|
| 368 |
+
metrics: list[str],
|
| 369 |
+
caption: str = "Quantitative results",
|
| 370 |
+
label: str = "tab:results",
|
| 371 |
+
highlight_best: bool = True,
|
| 372 |
+
) -> str:
|
| 373 |
+
"""Format metrics as a LaTeX table.
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
rows: List of dicts with 'name' and metric values.
|
| 377 |
+
metrics: List of metric names to include.
|
| 378 |
+
caption: Table caption.
|
| 379 |
+
label: LaTeX label.
|
| 380 |
+
highlight_best: Bold the best value per column.
|
| 381 |
+
|
| 382 |
+
Returns:
|
| 383 |
+
LaTeX table string.
|
| 384 |
+
"""
|
| 385 |
+
metric_labels = MetricsVisualizer.METRIC_LABELS
|
| 386 |
+
higher_better = MetricsVisualizer.METRIC_HIGHER_BETTER
|
| 387 |
+
|
| 388 |
+
# Find best values
|
| 389 |
+
best: dict[str, float] = {}
|
| 390 |
+
if highlight_best:
|
| 391 |
+
for m in metrics:
|
| 392 |
+
vals = [r.get(m) for r in rows if r.get(m) is not None]
|
| 393 |
+
if vals:
|
| 394 |
+
if higher_better.get(m, True):
|
| 395 |
+
best[m] = max(vals)
|
| 396 |
+
else:
|
| 397 |
+
best[m] = min(vals)
|
| 398 |
+
|
| 399 |
+
cols = "l" + "c" * len(metrics)
|
| 400 |
+
lines = [
|
| 401 |
+
"\\begin{table}[t]",
|
| 402 |
+
"\\centering",
|
| 403 |
+
f"\\caption{{{caption}}}",
|
| 404 |
+
f"\\label{{{label}}}",
|
| 405 |
+
f"\\begin{{tabular}}{{{cols}}}",
|
| 406 |
+
"\\toprule",
|
| 407 |
+
]
|
| 408 |
+
|
| 409 |
+
# Header
|
| 410 |
+
header = ["Method"]
|
| 411 |
+
for m in metrics:
|
| 412 |
+
name = metric_labels.get(m, m)
|
| 413 |
+
arrow = "$\\uparrow$" if higher_better.get(m, True) else "$\\downarrow$"
|
| 414 |
+
header.append(f"{name} {arrow}")
|
| 415 |
+
lines.append(" & ".join(header) + " \\\\")
|
| 416 |
+
lines.append("\\midrule")
|
| 417 |
+
|
| 418 |
+
# Data rows
|
| 419 |
+
for row in rows:
|
| 420 |
+
parts = [row.get("name", "").replace("_", "\\_")]
|
| 421 |
+
for m in metrics:
|
| 422 |
+
val = row.get(m)
|
| 423 |
+
if val is None:
|
| 424 |
+
parts.append("--")
|
| 425 |
+
else:
|
| 426 |
+
fmt = ".4f" if abs(val) < 10 else ".1f"
|
| 427 |
+
val_str = f"{val:{fmt}}"
|
| 428 |
+
if highlight_best and val == best.get(m):
|
| 429 |
+
val_str = f"\\textbf{{{val_str}}}"
|
| 430 |
+
parts.append(val_str)
|
| 431 |
+
lines.append(" & ".join(parts) + " \\\\")
|
| 432 |
+
|
| 433 |
+
lines.extend([
|
| 434 |
+
"\\bottomrule",
|
| 435 |
+
"\\end{tabular}",
|
| 436 |
+
"\\end{table}",
|
| 437 |
+
])
|
| 438 |
+
|
| 439 |
+
return "\n".join(lines)
|