Download Scripts/plot_geometric_metrics.py from moiaraya/I-AsSET: direct link, hf CLI and curl.
- Browser
- Download file 50.6 kB
-
https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/plot_geometric_metrics.py
- Command line
-
hf download hf://datasets/moiaraya/I-AsSET/Scripts/plot_geometric_metrics.py
-
curl -L -o plot_geometric_metrics.py https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/plot_geometric_metrics.py
50.6 kB
#!/usr/bin/env python3
"""
Publication-ready comparison of 3DGS and TRELLIS.
Generates two separate figures:
1. Qualitative comparison:
- 3DGS and TRELLIS reconstructions
- Four representative object classes
- Native Matplotlib viridis colorbar (0.0–1.5 mm)
- Optional right-edge cropping of every input PNG
2. Quantitative comparison:
- Chamfer distance (mm)
- Hausdorff distance (mm)
- Absolute scale error (%)
- All object classes, preserving underscores in class names
Input files
-----------
/media/rtx5090/IASSET/tmp/metrics_per_class.csv
/media/rtx5090/IASSET/tmp/figures/
3DGS_C_Steel_Ball_L_dev.png
3DGS_FestoY_dev.png
3DGS_GF_Plain_Screw_M8_dev.png
3DGS_MM_Spring_dev.png
TRELLIS_C_Steel_Ball_L_dev.png
TRELLIS_FestoY_dev.png
TRELLIS_GF_Plain_Screw_M8_dev.png
TRELLIS_GF_Plain_Screw_M8_colorbar.pdf # Not required
TRELLIS_MM_Spring_dev.png
Output files
------------
qualitative_comparison.pdf
qualitative_comparison.png
quantitative_comparison.pdf
quantitative_comparison.png
Dependencies
------------
pip install numpy pandas matplotlib pillow
"""
from pathlib import Path
import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.lines import Line2D
from matplotlib.ticker import MaxNLocator, FuncFormatter
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from PIL import Image
from matplotlib.patches import Patch
from matplotlib.ticker import LogLocator, NullLocator
# ============================================================
# Configuration
# ============================================================
BASE_DIR = Path("/media/rtx5090/IASSET/tmp")
CSV_PATH = BASE_DIR / "metrics_per_class.csv"
FIGURES_DIR = BASE_DIR / "figures"
# Output paths.
OUTPUT_QUALITATIVE_PDF = BASE_DIR / "qualitative_geometry_comparison.pdf"
OUTPUT_QUALITATIVE_PNG = BASE_DIR / "qualitative_geometry_comparison.png"
OUTPUT_QUANTITATIVE_PDF = BASE_DIR / "quantitative_geometry_comparison.pdf"
OUTPUT_QUANTITATIVE_PNG = BASE_DIR / "quantitative_geometry_comparison.png"
# ------------------------------------------------------------
# Figure dimensions
# ------------------------------------------------------------
# Qualitative figure: double-column width.
QUALITATIVE_WIDTH = 7.16
QUALITATIVE_HEIGHT = 2.55
# Quantitative figure: single-column width.
QUANTITATIVE_WIDTH = 3.50
QUANTITATIVE_HEIGHT = 7.2
DPI = 600
# ------------------------------------------------------------
# Typography
# ------------------------------------------------------------
# Single parameter controlling font sizes throughout both figures.
FONT_SIZE = 8
# ------------------------------------------------------------
# Input image cropping
# ------------------------------------------------------------
# Fraction removed from the RIGHT edge of every input PNG.
#
# 0.00 = no cropping
# 0.05 = crop the rightmost 5%
# 0.10 = crop the rightmost 10%
#
# Applied to each input PNG before plotting, not to the figure.
CROP_RIGHT_FRACTION = 0.165
# ------------------------------------------------------------
# Colorbar
# ------------------------------------------------------------
COLORBAR_MIN = 0.0
COLORBAR_MAX = 1.5
COLORBAR_LABEL = "Deviation [mm]"
# Colorbar position in figure coordinates:
# [left, bottom, width, height].
#
# The colorbar is placed outside the image grid so its ticks,
# label, and pointed end do not get clipped by the image axes.
COLORBAR_AXES = [0.895, 0.14, 0.025, 0.72]
# ------------------------------------------------------------
# Methods and colors
# ------------------------------------------------------------
METHODS = ["3DGS", "TRELLIS"]
VIRIDIS = mpl.colormaps["viridis"]
METHOD_COLORS = {
"3DGS": VIRIDIS(0.25),
"TRELLIS": VIRIDIS(0.80),
}
# Output paths.
OUTPUT_COMPACT_PDF = BASE_DIR / "quantitative_geometry_compact.pdf"
OUTPUT_COMPACT_PNG = BASE_DIR / "quantitative_geometry_compact.png"
# Geometry. The figure height is derived automatically from the font
# size, the number of rows, and COMPACT_ROW_PLOT_HEIGHT, so rotated
# class labels and the legend never clip.
COMPACT_WIDTH = 7.16 # inches, double-column width
COMPACT_ROW_PLOT_HEIGHT = 1.40 # inches of plotting area per row
COMPACT_N_ROWS = 1 # 2 rows of 16 classes; 1 gives a single strip
# Single parameter controlling all text in the compact figure.
COMPACT_FONT_SIZE = 8
# Class order: None (CSV order), "alphabetical", or a metric column name
# such as "chamfer_mm" (ascending, mean over both methods).
COMPACT_SORT_BY = None
# Same exclusion as in make_quantitative_figure(). Use set() to keep all.
COMPACT_EXCLUDED_CLASSES = {"GF_Collar_S"}
# Method colors (viridis, consistent with the other figures).
COMPACT_METHOD_COLORS = METHOD_COLORS
# Marker encodes the metric, color encodes the method.
COMPACT_MM_METRICS = [
{"column": "chamfer_mm", "label": "Chamfer", "marker": "o", "size": 12},
{"column": "hd_mm", "label": "Hausdorff", "marker": "^", "size": 14},
]
COMPACT_PCT_METRIC = {
"column": "scale_err_abs", "label": "Scale error", "marker": "D", "size": 9,
}
# Horizontal slot offsets inside one class group (group pitch = 1.0).
# Left pair: [mm] axis (3DGS, TRELLIS). Right pair: [%] axis (3DGS, TRELLIS).
COMPACT_MM_OFFSETS = (-0.33, -0.13)
COMPACT_PCT_OFFSETS = (0.13, 0.33)
COMPACT_BAND_COLOR = "#EFEFEF" # alternating class background
# ------------------------------------------------------------
# Qualitative examples
# ------------------------------------------------------------
# The strings are the exact class identifiers used in the CSV
# and image filenames.
#
# GF_Collar_S is intentionally excluded.
EXAMPLES = [
"C_Steel_Ball_L",
"FestoY",
"GF_Plain_Screw_M8",
"MM_Spring",
]
# ------------------------------------------------------------
# Quantitative metrics
# ------------------------------------------------------------
# Layout of the figure:
# "vertical" : classes on the y-axis, one panel per metric side by side
# (single column, QUANTITATIVE_WIDTH x QUANTITATIVE_HEIGHT).
# "horizontal" : classes on the x-axis, panels stacked
# (double column, HORIZONTAL_WIDTH x HORIZONTAL_HEIGHT).
QUANTITATIVE_LAYOUT = "horizontal"
# Figure size in inches for the horizontal layout. The vertical layout
# keeps using QUANTITATIVE_WIDTH and QUANTITATIVE_HEIGHT.
HORIZONTAL_WIDTH = 7.16
HORIZONTAL_HEIGHT = 3.8
# Scale of the Chamfer axis: "log" or "linear".
CHAMFER_SCALE = "linear"
# Rotation of the class labels in degrees (0 = horizontal).
# Vertical layout: the left margin adapts to the angle.
# Horizontal layout: the bottom margin adapts to the angle; use 30 to 90
# (0 would make the labels overlap).
CLASS_LABEL_ROTATION = 40
# Class order. SORT_BY: None (CSV order), "alphabetical", or a metric
# column such as "chamfer_mm" or "scale_err_abs".
# SORT_METHOD: None sorts by the mean over both methods; a method name
# such as "TRELLIS" sorts by that method only.
# The first class is drawn at the top (vertical) or at the left
# (horizontal).
SORT_BY = "chamfer_mm"
SORT_METHOD = "TRELLIS"
SORT_DESCENDING = False
# Print the numeric values next to the marks: None (off), "chamfer",
# "scale" or "both". Number formats are set per metric in METRICS
# ("value_format"). In the horizontal layout the values are rotated 90
# degrees and placed above the marks.
SHOW_VALUES = "both"
VALUE_FONT_SIZE = 6
# Light background band behind every other class (first, third, ...).
SHOW_BANDS = True
BAND_COLOR = "#EFEFEF"
# Bar thickness and offset of each method within a class
# (class pitch = 1.0).
BAR_HEIGHT = 0.34
METHOD_OFFSETS = {
"3DGS": -0.19,
"TRELLIS": 0.19,
}
# "bar" : bars (Chamfer)
# "lollipop" : line with dot (scale error)
METRICS = [
{
"column": "chamfer_mm",
"title": "Chamfer distance",
"xlabel": "Chamfer (mm)",
"kind": "bar",
"value_format": "{:.2f}",
},
{
"column": "scale_err_abs",
"title": "Absolute scale error",
"xlabel": "Scale error (%)",
"kind": "lollipop",
"value_format": "{:.1f}",
},
]
# ============================================================
# Matplotlib publication style
# ============================================================
mpl.rcParams.update({
# Typography.
"font.family": "serif",
"font.serif": [
"STIX Two Text",
"STIXGeneral",
"DejaVu Serif",
],
"mathtext.fontset": "stix",
"font.size": FONT_SIZE,
"axes.titlesize": FONT_SIZE,
"axes.labelsize": FONT_SIZE,
"xtick.labelsize": FONT_SIZE,
"ytick.labelsize": FONT_SIZE,
"legend.fontsize": FONT_SIZE,
# All text remains black.
"text.color": "black",
"axes.labelcolor": "black",
"axes.titlecolor": "black",
"xtick.color": "black",
"ytick.color": "black",
# Lines and axes.
"axes.linewidth": 0.65,
"lines.linewidth": 0.9,
"xtick.major.width": 0.6,
"ytick.major.width": 0.6,
"xtick.major.size": 2.5,
"ytick.major.size": 0,
# Background.
"figure.facecolor": "white",
"axes.facecolor": "white",
"savefig.facecolor": "white",
"axes.edgecolor": "black",
"grid.color": "#D9D9D9",
"grid.linewidth": 0.45,
"grid.alpha": 0.8,
# Vector-friendly PDF output.
"pdf.fonttype": 42,
"ps.fonttype": 42,
"svg.fonttype": "none",
# Export resolution.
"savefig.dpi": DPI,
})
# ============================================================
# Validation and loading
# ============================================================
def load_metrics(path: Path) -> pd.DataFrame:
"""Load and validate the per-class metrics CSV."""
if not path.exists():
raise FileNotFoundError(
f"Metrics CSV not found: {path}"
)
df = pd.read_csv(path)
required = {
"method",
"cls",
"chamfer_mm",
"hd_mm",
"scale_err_abs",
}
missing = required.difference(df.columns)
if missing:
raise ValueError(
f"Missing required CSV columns: {sorted(missing)}"
)
df["method"] = df["method"].astype(str).str.strip()
df["cls"] = df["cls"].astype(str).str.strip()
# Keep only the methods being compared.
df = df[df["method"].isin(METHODS)].copy()
# Convert relevant metrics to numeric values.
for column in [
"chamfer_mm",
"hd_mm",
"scale_err_abs",
]:
df[column] = pd.to_numeric(
df[column],
errors="coerce",
)
df = df.replace(
[np.inf, -np.inf],
np.nan,
)
# Check for duplicate method/class pairs.
duplicates = df.duplicated(
subset=["method", "cls"],
keep=False,
)
if duplicates.any():
pairs = df.loc[
duplicates,
["method", "cls"],
]
raise ValueError(
"Duplicate method/class entries found:\n"
f"{pairs.to_string(index=False)}"
)
if df.empty:
raise ValueError(
"No measurements found for 3DGS or TRELLIS."
)
return df
# ============================================================
# Image loading and cropping
# ============================================================
def load_image(path: Path):
"""
Load an RGB image and crop its right edge.
Cropping is performed on the original image before insertion
into the figure. The image height remains unchanged.
"""
if not 0.0 <= CROP_RIGHT_FRACTION < 1.0:
raise ValueError(
"CROP_RIGHT_FRACTION must be >= 0 and < 1."
)
if not path.exists():
warnings.warn(
f"Image not found: {path}",
stacklevel=2,
)
return None
try:
with Image.open(path) as im:
im = im.convert("RGB")
width, height = im.size
cropped_width = max(
1,
int(round(
width * (1.0 - CROP_RIGHT_FRACTION)
)),
)
# Crop from x=0 to the new right boundary.
im = im.crop(
(0, 0, cropped_width, height)
)
return np.asarray(im)
except Exception as exc:
warnings.warn(
f"Could not read image {path}: {exc}",
stacklevel=2,
)
return None
def image_path(method: str, cls: str) -> Path:
"""Return the expected reconstruction PNG path."""
return FIGURES_DIR / f"{method}_{cls}_dev.png"
# ============================================================
# Save figures
# ============================================================
def save_figure(
fig,
pdf_path: Path,
png_path: Path,
):
"""
Save PDF and PNG without cropping the figure canvas.
Using bbox_inches=None preserves the configured dimensions
and avoids unintended changes to the figure's aspect ratio.
"""
fig.savefig(
pdf_path,
format="pdf",
dpi=DPI,
bbox_inches=None,
pad_inches=0,
)
fig.savefig(
png_path,
format="png",
dpi=DPI,
bbox_inches=None,
pad_inches=0,
)
plt.close(fig)
print(f"Saved PDF: {pdf_path}")
print(f"Saved PNG: {png_path}")
# ============================================================
# Qualitative comparison
# ============================================================
def make_qualitative_figure():
"""
Create the qualitative comparison matrix.
Layout:
Columns: object classes
Rows: 3DGS and TRELLIS
Right: native Matplotlib deviation colorbar
The colorbar is independent of the image grid and is placed
at the far right of the figure.
"""
n_examples = len(EXAMPLES)
fig = plt.figure(
figsize=(
QUALITATIVE_WIDTH,
QUALITATIVE_HEIGHT,
),
facecolor="white",
)
# The grid contains only the image matrix.
# The colorbar has a dedicated figure-level axes.
#
# A slightly larger left margin accommodates the rotated
# method labels. The right margin leaves space for the
# independently positioned colorbar.
gs = GridSpec(
3,
n_examples,
figure=fig,
height_ratios=[0.20, 1.0, 1.0],
left=0.095,
right=0.86,
top=0.96,
bottom=0.04,
hspace=0.04,
wspace=0.08,
)
first_image_axes = {}
# --------------------------------------------------------
# Column headers
# --------------------------------------------------------
for col, cls in enumerate(EXAMPLES):
ax = fig.add_subplot(gs[0, col])
ax.axis("off")
ax.text(
0.5,
0.5,
cls,
ha="center",
va="center",
fontsize=FONT_SIZE,
fontweight="semibold",
color="black",
transform=ax.transAxes,
)
# --------------------------------------------------------
# Reconstruction images
# --------------------------------------------------------
for row, method in enumerate(METHODS, start=1):
for col, cls in enumerate(EXAMPLES):
ax = fig.add_subplot(gs[row, col])
img = load_image(
image_path(method, cls)
)
if img is not None:
ax.imshow(
img,
interpolation="nearest",
)
else:
ax.text(
0.5,
0.5,
"Not available",
ha="center",
va="center",
fontsize=FONT_SIZE,
color="black",
transform=ax.transAxes,
)
ax.set_xticks([])
ax.set_yticks([])
for spine in ax.spines.values():
spine.set_visible(False)
ax.patch.set_edgecolor("#DDDDDD")
ax.patch.set_linewidth(0.4)
if col == 0:
first_image_axes[method] = ax
# --------------------------------------------------------
# Method labels
# --------------------------------------------------------
for method, ax in first_image_axes.items():
ax.text(
-0.035,
0.5,
method,
rotation=90,
ha="right",
va="center",
fontsize=FONT_SIZE,
fontweight="bold",
color="black",
transform=ax.transAxes,
clip_on=False,
)
# --------------------------------------------------------
# Native Matplotlib colorbar
# --------------------------------------------------------
cmap = mpl.colormaps["viridis"]
norm = Normalize(
vmin=COLORBAR_MIN,
vmax=COLORBAR_MAX,
)
sm = ScalarMappable(
norm=norm,
cmap=cmap,
)
sm.set_array([])
# Dedicated axes outside the image grid.
#
# Increase the first value to move the colorbar right.
# Decrease it if more room is needed for the label.
colorbar_ax = fig.add_axes(
COLORBAR_AXES
)
cbar = fig.colorbar(
sm,
cax=colorbar_ax,
orientation="vertical",
extend="max",
extendfrac=0.06,
)
cbar.set_label(
COLORBAR_LABEL,
fontsize=FONT_SIZE,
color="black",
labelpad=5,
)
# Ticks from 0.0 through 1.4 mm in 0.2 mm increments.
cbar.set_ticks(
np.arange(0.0, 1.51, 0.2)
)
cbar.ax.tick_params(
labelsize=FONT_SIZE,
colors="black",
width=0.6,
length=2.5,
pad=2,
)
cbar.outline.set_edgecolor("black")
cbar.outline.set_linewidth(0.65)
# --------------------------------------------------------
# Export
# --------------------------------------------------------
save_figure(
fig,
OUTPUT_QUALITATIVE_PDF,
OUTPUT_QUALITATIVE_PNG,
)
# ============================================================
# Quantitative comparison
# ============================================================
def _sort_classes(
df: pd.DataFrame,
classes: list,
sort_by,
sort_method,
descending: bool,
):
"""Return classes in the requested order (missing values last)."""
if sort_by is None:
return classes
if sort_by == "alphabetical":
return sorted(
classes,
key=str.lower,
reverse=descending,
)
if sort_by not in df.columns:
raise ValueError(
f"Unknown sort_by value: {sort_by!r}"
)
subset = df[df["cls"].isin(classes)]
if sort_method is not None:
if sort_method not in METHODS:
raise ValueError(
f"Unknown sort_method: {sort_method!r}"
)
subset = subset[subset["method"] == sort_method]
key = subset.groupby("cls")[sort_by].mean()
valid = [c for c in classes if pd.notna(key.get(c, np.nan))]
missing = [c for c in classes if c not in valid]
valid = sorted(
valid,
key=lambda c: key[c],
reverse=descending,
)
return valid + missing
def add_metric_panel(
ax,
df: pd.DataFrame,
classes: list,
metric: dict,
show_class_labels: bool,
chamfer_scale: str,
label_rotation: float,
show_values: bool = False,
layout: str = "vertical",
bands: bool = False,
):
"""
Plot one metric panel.
layout == "vertical" : classes on the y-axis, values on the x-axis.
layout == "horizontal" : classes on the x-axis, values on the y-axis.
kind == "bar" : grouped bars (one per method). On a log axis the
bars start at the lower axis limit (a power of
ten below the data).
kind == "lollipop" : line from zero to the value, with a dot.
If show_values is True, each value is printed next to its mark and
the value-axis limit is widened so the text stays inside the axes.
If bands is True, every other class gets a light background band.
"""
horizontal = (layout == "horizontal")
column = metric["column"]
kind = metric["kind"]
use_log = (kind == "bar" and chamfer_scale == "log")
n_classes = len(classes)
pos = np.arange(n_classes)
# Axis-dependent helpers: the "value axis" carries the metric,
# the "class axis" carries the classes.
value_axis = ax.yaxis if horizontal else ax.xaxis
value_axis_name = "y" if horizontal else "x"
set_value_scale = ax.set_yscale if horizontal else ax.set_xscale
set_value_lim = ax.set_ylim if horizontal else ax.set_xlim
# --------------------------------------------------------
# Collect valid values
# --------------------------------------------------------
records = []
for method in METHODS:
subset = (
df[df["method"] == method]
.set_index("cls")
)
for i, cls in enumerate(classes):
if cls not in subset.index:
continue
value = subset.loc[cls, column]
if pd.isna(value):
continue
value = float(value)
# Logarithmic axes cannot display zero or negative values.
if use_log and value <= 0:
continue
records.append(
(method, pos[i] + METHOD_OFFSETS[method], value)
)
if not records:
raise ValueError(
f"No valid values for metric {column!r}."
)
all_values = np.array([r[2] for r in records])
# --------------------------------------------------------
# Value-axis scale, limits, and bar baseline
# --------------------------------------------------------
value_format = metric.get("value_format", "{:.3g}")
# Fraction of the value axis reserved for the printed values.
frac = 0.0
if show_values:
bbox = ax.get_position()
if horizontal:
axis_len_in = bbox.height * ax.figure.get_figheight()
else:
axis_len_in = bbox.width * ax.figure.get_figwidth()
longest = max(
len(value_format.format(v)) for v in all_values
)
label_len_in = longest * VALUE_FONT_SIZE * 0.52 / 72.0 + 0.06
frac = min(label_len_in / axis_len_in, 0.6)
vmax = max(all_values.max(), 1e-9)
if use_log:
baseline = 10 ** np.floor(np.log10(all_values.min()))
if baseline >= all_values.min():
baseline /= 10.0
set_value_scale("log")
# Place the largest value at (1 - frac) of the axis length.
span = np.log10(vmax / baseline)
upper = max(
vmax * 1.25,
baseline * 10 ** (span / (1.0 - frac)),
)
set_value_lim(baseline, upper)
else:
baseline = 0.0
upper = max(vmax * 1.08, vmax / (1.0 - frac))
set_value_lim(0.0, upper)
# --------------------------------------------------------
# Alternating class bands (behind everything else)
# --------------------------------------------------------
if bands:
for i in range(0, n_classes, 2):
if horizontal:
ax.axvspan(
i - 0.5,
i + 0.5,
facecolor=BAND_COLOR,
edgecolor="none",
linewidth=0,
zorder=0,
)
else:
ax.axhspan(
i - 0.5,
i + 0.5,
facecolor=BAND_COLOR,
edgecolor="none",
linewidth=0,
zorder=0,
)
# --------------------------------------------------------
# Draw
# --------------------------------------------------------
for method in METHODS:
ps = np.array(
[r[1] for r in records if r[0] == method]
)
vs = np.array(
[r[2] for r in records if r[0] == method]
)
if ps.size == 0:
continue
color = METHOD_COLORS[method]
if kind == "bar":
if horizontal:
ax.bar(
ps,
vs - baseline,
bottom=baseline,
width=BAR_HEIGHT,
color=color,
edgecolor="none",
zorder=3,
)
else:
ax.barh(
ps,
vs - baseline,
left=baseline,
height=BAR_HEIGHT,
color=color,
edgecolor="none",
zorder=3,
)
offset = 2.0
else:
if horizontal:
ax.vlines(
ps,
0.0,
vs,
color=color,
linewidth=0.8,
zorder=2,
)
ax.scatter(
ps,
vs,
s=13,
marker="o",
color=color,
edgecolors="white",
linewidths=0.35,
zorder=3,
)
else:
ax.hlines(
ps,
0.0,
vs,
color=color,
linewidth=0.8,
zorder=2,
)
ax.scatter(
vs,
ps,
s=13,
marker="o",
color=color,
edgecolors="white",
linewidths=0.35,
zorder=3,
)
offset = 4.0
if show_values:
for p, v in zip(ps, vs):
if horizontal:
# Vertical text above the mark.
ax.annotate(
value_format.format(v),
xy=(p, v),
xytext=(0, offset),
textcoords="offset points",
ha="center",
va="bottom",
rotation=90,
fontsize=VALUE_FONT_SIZE,
color="black",
zorder=5,
)
else:
ax.annotate(
value_format.format(v),
xy=(v, p),
xytext=(offset, 0),
textcoords="offset points",
ha="left",
va="center",
fontsize=VALUE_FONT_SIZE,
color="black",
zorder=5,
)
# --------------------------------------------------------
# Titles and labels: always black
# --------------------------------------------------------
if horizontal:
# The y-label already names the metric, so no panel title is
# drawn; this saves vertical space between the stacked panels.
ax.set_ylabel(
metric["xlabel"],
labelpad=3,
color="black",
)
else:
ax.set_title(
metric["title"],
loc="left",
pad=5,
fontweight="semibold",
color="black",
)
ax.set_xlabel(
metric["xlabel"],
labelpad=4,
color="black",
)
# --------------------------------------------------------
# Class labels (exact names, underscores preserved)
# --------------------------------------------------------
if horizontal:
ax.set_xticks(pos)
ax.set_xlim(-0.5, n_classes - 0.5)
if show_class_labels:
if label_rotation >= 80:
ha, mode = "center", "default"
else:
ha, mode = "right", "anchor"
# The end of each label is anchored at its tick and the text
# rotates around that point.
ax.set_xticklabels(
classes,
rotation=label_rotation,
ha=ha,
va="top",
rotation_mode=mode,
color="black",
)
else:
ax.set_xticklabels([])
ax.tick_params(axis="x", length=0, pad=2)
else:
ax.set_yticks(pos)
if show_class_labels:
ax.set_yticklabels(
classes,
rotation=label_rotation,
ha="right",
va="center",
rotation_mode="anchor",
color="black",
)
else:
ax.set_yticklabels([])
ax.tick_params(axis="y", length=0, pad=2)
ax.invert_yaxis()
ax.set_ylim(
n_classes - 0.5,
-0.5,
)
# --------------------------------------------------------
# Grid and spines
# --------------------------------------------------------
ax.set_axisbelow(True)
other_axis_name = "x" if horizontal else "y"
ax.grid(
axis=value_axis_name,
linestyle="-",
linewidth=0.45,
alpha=0.8,
zorder=0,
)
ax.grid(
axis=other_axis_name,
visible=False,
)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
if not horizontal:
ax.spines["left"].set_visible(False)
# --------------------------------------------------------
# Value-axis ticks
# --------------------------------------------------------
if use_log:
value_axis.set_major_locator(
mpl.ticker.LogLocator(base=10, numticks=5)
)
value_axis.set_major_formatter(
FuncFormatter(lambda value, _: f"{value:g}")
)
value_axis.set_minor_formatter(
mpl.ticker.NullFormatter()
)
else:
value_axis.set_major_locator(
MaxNLocator(nbins=4)
)
value_axis.set_major_formatter(
FuncFormatter(lambda value, _: f"{value:g}")
)
ax.tick_params(
axis=value_axis_name,
length=2.5,
pad=2,
colors="black",
)
def make_quantitative_figure(
df: pd.DataFrame,
chamfer_scale: str = None,
label_rotation: float = None,
sort_by=None,
sort_method=None,
sort_descending: bool = None,
show_values=None,
layout: str = None,
bands: bool = None,
):
"""
Create the quantitative comparison figure.
Panels: Chamfer distance [mm] (bars, log or linear axis) and
absolute scale error [%] (line with dot).
Parameters
----------
chamfer_scale : "log" or "linear". Defaults to CHAMFER_SCALE.
label_rotation : class label angle in degrees. Defaults to
CLASS_LABEL_ROTATION.
sort_by : None, "alphabetical", or a metric column name.
Defaults to SORT_BY.
sort_method : None (mean over methods) or a method name.
Defaults to SORT_METHOD.
sort_descending: reverse the order. Defaults to SORT_DESCENDING.
show_values : None (use SHOW_VALUES), False (off), "chamfer",
"scale" or "both": print the values on the plots.
layout : "vertical" or "horizontal". Defaults to
QUANTITATIVE_LAYOUT.
bands : True/False, light background band behind every
other class. Defaults to SHOW_BANDS.
"""
if chamfer_scale is None:
chamfer_scale = CHAMFER_SCALE
if label_rotation is None:
label_rotation = CLASS_LABEL_ROTATION
if sort_by is None:
sort_by = SORT_BY
if sort_method is None:
sort_method = SORT_METHOD
if sort_descending is None:
sort_descending = SORT_DESCENDING
if show_values is None:
show_values = SHOW_VALUES
if layout is None:
layout = QUANTITATIVE_LAYOUT
if bands is None:
bands = SHOW_BANDS
value_kinds = {
None: set(),
False: set(),
"chamfer": {"bar"},
"scale": {"lollipop"},
"both": {"bar", "lollipop"},
}
if show_values not in value_kinds:
raise ValueError(
"show_values must be None, False, 'chamfer', "
"'scale' or 'both'."
)
if chamfer_scale not in ("log", "linear"):
raise ValueError(
"chamfer_scale must be 'log' or 'linear'."
)
if layout not in ("vertical", "horizontal"):
raise ValueError(
"layout must be 'vertical' or 'horizontal'."
)
horizontal = (layout == "horizontal")
# Preserve the CSV class order unless sorting is requested.
classes = df["cls"].drop_duplicates().tolist()
# Remove the unused collar class if present.
classes = [
cls for cls in classes
if cls != "GF_Collar_S"
]
if not classes:
raise ValueError(
"No classes remain after filtering."
)
classes = _sort_classes(
df,
classes,
sort_by,
sort_method,
sort_descending,
)
if horizontal:
fig_w, fig_h = HORIZONTAL_WIDTH, HORIZONTAL_HEIGHT
else:
fig_w, fig_h = QUANTITATIVE_WIDTH, QUANTITATIVE_HEIGHT
fig = plt.figure(
figsize=(fig_w, fig_h),
facecolor="white",
)
# --------------------------------------------------------
# Layout in inches
# --------------------------------------------------------
pt = 1.0 / 72.0
theta = np.deg2rad(label_rotation)
# Approximate extent of the longest class label.
longest = max(len(c) for c in classes)
text_w = longest * FONT_SIZE * 0.56 * pt
text_h = FONT_SIZE * 1.2 * pt
n_panels = len(METRICS)
if horizontal:
# Height taken by the rotated labels below the bottom panel.
bottom_in = (
text_w * abs(np.sin(theta))
+ text_h * abs(np.cos(theta))
+ 0.08
)
top_in = FONT_SIZE * 2.0 * pt + 0.08 # legend
left_in = FONT_SIZE * 4.6 * pt # y-label and tick labels
right_in = 0.06
gap_in = 0.12
axes_h = (
fig_h - top_in - bottom_in - (n_panels - 1) * gap_in
) / n_panels
if axes_h < 0.8:
warnings.warn(
f"Panels are only {axes_h:.2f} in tall; increase "
"HORIZONTAL_HEIGHT or reduce CLASS_LABEL_ROTATION.",
stacklevel=2,
)
gs = GridSpec(
n_panels,
1,
figure=fig,
left=left_in / fig_w,
right=1.0 - right_in / fig_w,
top=1.0 - top_in / fig_h,
bottom=bottom_in / fig_h,
hspace=gap_in / axes_h,
)
else:
# Width taken by the rotated labels left of the first panel.
left_in = (
text_w * abs(np.cos(theta))
+ text_h * abs(np.sin(theta))
+ 0.08
)
# Room for the legend and the panel titles.
top_in = FONT_SIZE * 3.4 * pt + 0.08
gs = GridSpec(
1,
n_panels,
figure=fig,
width_ratios=[1.0] + [0.8] * (n_panels - 1),
left=left_in / fig_w,
right=0.97,
top=1.0 - top_in / fig_h,
bottom=0.09,
wspace=0.15,
)
for i, metric in enumerate(METRICS):
ax = fig.add_subplot(
gs[i, 0] if horizontal else gs[0, i]
)
# Class labels once: bottom panel (horizontal) or first panel
# (vertical).
show_class_labels = (
(i == n_panels - 1) if horizontal else (i == 0)
)
add_metric_panel(
ax=ax,
df=df,
classes=classes,
metric=metric,
show_class_labels=show_class_labels,
chamfer_scale=chamfer_scale,
label_rotation=label_rotation,
show_values=(
metric["kind"] in value_kinds[show_values]
),
layout=layout,
bands=bands,
)
# --------------------------------------------------------
# Shared legend (color = method)
# --------------------------------------------------------
handles = [
mpl.patches.Patch(
facecolor=METHOD_COLORS[method],
edgecolor="none",
label=method,
)
for method in METHODS
]
fig.legend(
handles=handles,
loc="upper center",
bbox_to_anchor=(0.5, 1.0),
ncol=len(handles),
frameon=False,
handletextpad=0.4,
columnspacing=1.2,
borderaxespad=0.1,
)
# --------------------------------------------------------
# Export
# --------------------------------------------------------
save_figure(
fig,
OUTPUT_QUANTITATIVE_PDF,
OUTPUT_QUANTITATIVE_PNG,
)
def _order_classes(df: pd.DataFrame, classes: list, sort_by):
"""Return classes in the requested order."""
if sort_by is None:
return classes
if sort_by == "alphabetical":
return sorted(classes, key=str.lower)
if sort_by in df.columns:
key = (
df[df["cls"].isin(classes)]
.groupby("cls")[sort_by]
.mean()
)
return sorted(
classes,
key=lambda c: key.get(c, np.inf)
if pd.notna(key.get(c, np.nan)) else np.inf,
)
raise ValueError(
f"Unknown sort_by value: {sort_by!r}"
)
def make_compact_quantitative_figure(
df: pd.DataFrame,
font_size: float = COMPACT_FONT_SIZE,
n_rows: int = COMPACT_N_ROWS,
sort_by=COMPACT_SORT_BY,
):
"""
Compact double-column quantitative comparison with dual y-axes.
Encoding
--------
Spatial grouping : one group per class (alternating grey bands).
Inside a group, the left pair of slots uses the
left axis [mm] and the right pair uses the right
axis [%]. Within each pair: 3DGS, then TRELLIS.
Color : method (viridis).
Marker : metric (circle = Chamfer, triangle = Hausdorff,
diamond = absolute scale error).
Connectors : a vertical line joins Chamfer and Hausdorff of the
same method and class; scale error has a stem to
the zero baseline of the right axis.
Chamfer and Hausdorff share a logarithmic left axis [mm]. The scale
error uses a linear right axis [%] starting at zero.
Parameters
----------
font_size : font size in points for all text in this figure.
n_rows : number of stacked rows the classes are split into.
sort_by : None, "alphabetical", or a metric column name.
"""
# --------------------------------------------------------
# Data preparation
# --------------------------------------------------------
classes = [
c for c in df["cls"].drop_duplicates().tolist()
if c not in COMPACT_EXCLUDED_CLASSES
]
if not classes:
raise ValueError("No classes remain after filtering.")
classes = _order_classes(df, classes, sort_by)
n_classes = len(classes)
per_row = int(np.ceil(n_classes / n_rows))
sub = df[df["cls"].isin(classes)]
lookup = sub.set_index(["method", "cls"])
mm_cols = [m["column"] for m in COMPACT_MM_METRICS]
pct_col = COMPACT_PCT_METRIC["column"]
mm_vals = sub[mm_cols].to_numpy(dtype=float).ravel()
mm_vals = mm_vals[np.isfinite(mm_vals) & (mm_vals > 0)]
pct_vals = sub[pct_col].to_numpy(dtype=float)
pct_vals = pct_vals[np.isfinite(pct_vals)]
if mm_vals.size == 0 or pct_vals.size == 0:
raise ValueError("No valid values to plot.")
# Shared limits across rows so that rows are directly comparable.
mm_lo = mm_vals.min() / 1.4
mm_hi = mm_vals.max() * 1.4
pct_hi = max(pct_vals.max(), 1e-9) * 1.08
decades = np.log10(mm_hi / mm_lo)
log_subs = (1.0, 2.0, 5.0) if decades <= 2.5 else (1.0,)
# --------------------------------------------------------
# Layout in inches (robust to font size changes)
# --------------------------------------------------------
pt = 1.0 / 72.0
longest = max(len(c) for c in classes)
label_h = longest * font_size * 0.56 * pt + 0.06
legend_h = font_size * 2.0 * pt + 0.04
left_in = font_size * 4.4 * pt
right_in = font_size * 4.2 * pt
row_gap = 0.08
plot_h = COMPACT_ROW_PLOT_HEIGHT
fig_w = COMPACT_WIDTH
fig_h = (
legend_h
+ n_rows * (plot_h + label_h)
+ (n_rows - 1) * row_gap
+ 0.04
)
rc = {
"font.size": font_size,
"axes.titlesize": font_size,
"axes.labelsize": font_size,
"xtick.labelsize": font_size,
"ytick.labelsize": font_size,
"legend.fontsize": font_size,
"ytick.major.size": 2.5,
}
with mpl.rc_context(rc):
fig = plt.figure(
figsize=(fig_w, fig_h),
facecolor="white",
)
for r in range(n_rows):
chunk = classes[r * per_row:(r + 1) * per_row]
if not chunk:
continue
top_in = legend_h + r * (plot_h + label_h + row_gap)
bottom_in = fig_h - (top_in + plot_h)
ax = fig.add_axes([
left_in / fig_w,
bottom_in / fig_h,
(fig_w - left_in - right_in) / fig_w,
plot_h / fig_h,
])
ax2 = ax.twinx()
ax.set_yscale("log")
ax.set_axisbelow(True)
# ------------------------------------------------
# Data
# ------------------------------------------------
for i, cls in enumerate(chunk):
if i % 2 == 0:
ax.axvspan(
i - 0.5,
i + 0.5,
facecolor=COMPACT_BAND_COLOR,
linewidth=0,
zorder=0,
)
for k, method in enumerate(METHODS):
if (method, cls) not in lookup.index:
continue
rec = lookup.loc[(method, cls)]
color = COMPACT_METHOD_COLORS[method]
# Left axis: Chamfer and Hausdorff [mm].
x_mm = i + COMPACT_MM_OFFSETS[k]
pts = []
for metric in COMPACT_MM_METRICS:
value = pd.to_numeric(
rec[metric["column"]],
errors="coerce",
)
if not np.isfinite(value) or value <= 0:
continue
pts.append(float(value))
ax.scatter(
x_mm,
value,
s=metric["size"],
marker=metric["marker"],
color=color,
edgecolors="black",
linewidths=0.25,
zorder=4,
)
if len(pts) == 2:
ax.plot(
[x_mm, x_mm],
pts,
color=color,
linewidth=0.8,
solid_capstyle="butt",
zorder=3,
)
# Right axis: absolute scale error [%].
x_pct = i + COMPACT_PCT_OFFSETS[k]
se = pd.to_numeric(
rec[pct_col],
errors="coerce",
)
if np.isfinite(se):
ax2.vlines(
x_pct,
0,
se,
color=color,
linewidth=0.6,
alpha=0.6,
zorder=3,
)
ax2.scatter(
x_pct,
se,
s=COMPACT_PCT_METRIC["size"],
marker=COMPACT_PCT_METRIC["marker"],
color=color,
edgecolors="black",
linewidths=0.25,
zorder=4,
)
# ------------------------------------------------
# Axes formatting
# ------------------------------------------------
ax.set_xlim(-0.5, per_row - 0.5)
ax.set_ylim(mm_lo, mm_hi)
ax2.set_ylim(0, pct_hi)
ax.set_xticks(range(len(chunk)))
ax.set_xticklabels(
chunk,
rotation=90,
ha="center",
va="top",
color="black",
)
ax.tick_params(axis="x", length=0, pad=2)
ax.yaxis.set_major_locator(
LogLocator(base=10, subs=log_subs, numticks=20)
)
ax.yaxis.set_minor_locator(NullLocator())
ax.yaxis.set_major_formatter(
FuncFormatter(lambda v, _: f"{v:g}")
)
ax2.yaxis.set_major_locator(MaxNLocator(nbins=5))
ax2.yaxis.set_major_formatter(
FuncFormatter(lambda v, _: f"{v:g}")
)
ax.grid(
axis="y",
color="#D0D0D0",
linewidth=0.45,
zorder=0.5,
)
ax.grid(axis="x", visible=False)
ax2.grid(False)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("top", "left", "bottom"):
ax2.spines[side].set_visible(False)
ax.set_ylabel("Distance [mm]", labelpad=2)
ax2.set_ylabel(
"Scale error [%]",
rotation=270,
va="bottom",
labelpad=2,
)
ax.tick_params(axis="y", colors="black", pad=2)
ax2.tick_params(axis="y", colors="black", pad=2)
# ----------------------------------------------------
# Shared legend (method = color, metric = marker)
# ----------------------------------------------------
handles = [
Patch(
facecolor=COMPACT_METHOD_COLORS[m],
edgecolor="black",
linewidth=0.3,
label=m,
)
for m in METHODS
]
for metric, side in zip(
COMPACT_MM_METRICS + [COMPACT_PCT_METRIC],
["left", "left", "right"],
):
handles.append(
Line2D(
[0],
[0],
marker=metric["marker"],
linestyle="none",
markerfacecolor="#6E6E6E",
markeredgecolor="black",
markeredgewidth=0.3,
markersize=np.sqrt(metric["size"]) + 0.8,
label=f"{metric['label']} ({side} axis)",
)
)
fig.legend(
handles=handles,
loc="upper center",
bbox_to_anchor=(0.5, 1.0),
ncol=len(handles),
frameon=False,
handletextpad=0.4,
columnspacing=1.1,
borderaxespad=0.1,
)
save_figure(
fig,
OUTPUT_COMPACT_PDF,
OUTPUT_COMPACT_PNG,
)
# ============================================================
# Main
# ============================================================
def main():
print("Loading metrics...")
df = load_metrics(CSV_PATH)
print(
f"Loaded {len(df)} measurements "
f"for {df['cls'].nunique()} classes."
)
print(
"Methods:",
", ".join(
method
for method in METHODS
if method in df["method"].unique()
),
)
# Validate requested quantitative metrics.
for metric in METRICS:
column = metric["column"]
if df[column].notna().sum() == 0:
raise ValueError(
f"No valid values for metric {column!r}."
)
# --------------------------------------------------------
# Figure 1: qualitative comparison
# --------------------------------------------------------
print("\nGenerating qualitative comparison...")
make_qualitative_figure()
# --------------------------------------------------------
# Figure 2: quantitative comparison
# --------------------------------------------------------
print("\nGenerating quantitative comparison...")
make_quantitative_figure(df)
print("\nGenerating compact quantitative comparison...")
#make_compact_quantitative_figure(df)
make_compact_quantitative_figure(df, font_size=9, sort_by="chamfer_mm")
print("\nAll figures generated successfully.")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Publication-ready comparison of 3DGS and TRELLIS.
Generates two separate figures:
1. Qualitative comparison:
- 3DGS and TRELLIS reconstructions
- Four representative object classes
- Native Matplotlib viridis colorbar (0.0–1.5 mm)
- Optional right-edge cropping of every input PNG
2. Quantitative comparison:
- Chamfer distance (mm)
- Hausdorff distance (mm)
- Absolute scale error (%)
- All object classes, preserving underscores in class names
Input files
-----------
/media/rtx5090/IASSET/tmp/metrics_per_class.csv
/media/rtx5090/IASSET/tmp/figures/
3DGS_C_Steel_Ball_L_dev.png
3DGS_FestoY_dev.png
3DGS_GF_Plain_Screw_M8_dev.png
3DGS_MM_Spring_dev.png
TRELLIS_C_Steel_Ball_L_dev.png
TRELLIS_FestoY_dev.png
TRELLIS_GF_Plain_Screw_M8_dev.png
TRELLIS_GF_Plain_Screw_M8_colorbar.pdf # Not required
TRELLIS_MM_Spring_dev.png
Output files
------------
qualitative_comparison.pdf
qualitative_comparison.png
quantitative_comparison.pdf
quantitative_comparison.png
Dependencies
------------
pip install numpy pandas matplotlib pillow
"""
from pathlib import Path
import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.lines import Line2D
from matplotlib.ticker import MaxNLocator, FuncFormatter
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from PIL import Image
from matplotlib.patches import Patch
from matplotlib.ticker import LogLocator, NullLocator
# ============================================================
# Configuration
# ============================================================
BASE_DIR = Path("/media/rtx5090/IASSET/tmp")
CSV_PATH = BASE_DIR / "metrics_per_class.csv"
FIGURES_DIR = BASE_DIR / "figures"
# Output paths.
OUTPUT_QUALITATIVE_PDF = BASE_DIR / "qualitative_geometry_comparison.pdf"
OUTPUT_QUALITATIVE_PNG = BASE_DIR / "qualitative_geometry_comparison.png"
OUTPUT_QUANTITATIVE_PDF = BASE_DIR / "quantitative_geometry_comparison.pdf"
OUTPUT_QUANTITATIVE_PNG = BASE_DIR / "quantitative_geometry_comparison.png"
# ------------------------------------------------------------
# Figure dimensions
# ------------------------------------------------------------
# Qualitative figure: double-column width.
QUALITATIVE_WIDTH = 7.16
QUALITATIVE_HEIGHT = 2.55
# Quantitative figure: single-column width.
QUANTITATIVE_WIDTH = 3.50
QUANTITATIVE_HEIGHT = 7.2
DPI = 600
# ------------------------------------------------------------
# Typography
# ------------------------------------------------------------