Add agent skills under .agents/skills for Codex

Copy of the project skills (.claude/skills is gitignored) so Codex on
other machines picks them up; skills-lock.json records their sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 16:09:25 +00:00
parent 5a6fb2fc8c
commit 954bbf0127
135 changed files with 39094 additions and 0 deletions

View File

@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Shared, network-free safety helpers for visualization command-line tools."""
from __future__ import annotations
import json
import os
import stat
import tempfile
from pathlib import Path
from typing import Any
MAX_INPUT_BYTES = 200 * 1024 * 1024
MAX_REPORT_BYTES = 4 * 1024 * 1024
class CliError(ValueError):
"""An expected command-line validation error."""
def checked_input_file(
value: str | os.PathLike[str],
*,
max_bytes: int = MAX_INPUT_BYTES,
) -> Path:
"""Return a bounded regular input file, rejecting symlinks."""
path = Path(value).expanduser()
if path.is_symlink():
raise CliError(f"input must not be a symlink: {path}")
try:
info = path.stat()
except OSError as exc:
raise CliError(f"cannot access input file {path}: {exc}") from exc
if not stat.S_ISREG(info.st_mode):
raise CliError(f"input is not a regular file: {path}")
if info.st_size > max_bytes:
raise CliError(
f"input is {info.st_size} bytes; limit is {max_bytes} bytes"
)
return path.resolve()
def checked_output_file(
value: str | os.PathLike[str],
*,
force: bool = False,
mkdir: bool = False,
) -> Path:
"""Validate an explicit output path without following a destination symlink."""
path = Path(value).expanduser()
if path.name in {"", ".", ".."}:
raise CliError("output must name a file")
if path.is_symlink():
raise CliError(f"output must not be a symlink: {path}")
parent = path.parent
if mkdir:
parent.mkdir(parents=True, exist_ok=True)
if not parent.exists() or not parent.is_dir():
raise CliError(f"output parent directory does not exist: {parent}")
if parent.is_symlink():
raise CliError(f"output parent must not be a symlink: {parent}")
if path.exists():
if not path.is_file():
raise CliError(f"output exists and is not a regular file: {path}")
if not force:
raise CliError(f"refusing to overwrite existing output: {path}")
return parent.resolve() / path.name
def atomic_write_bytes(path: Path, payload: bytes, *, force: bool = False) -> None:
"""Write bytes through a same-directory temporary file."""
destination = checked_output_file(path, force=force)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{destination.name}.",
suffix=".tmp",
dir=destination.parent,
)
temporary = Path(temporary_name)
try:
with os.fdopen(descriptor, "wb") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.chmod(temporary, 0o600)
if force:
os.replace(temporary, destination)
else:
# A second existence check followed by replace still races another
# writer. Linking a same-filesystem temporary refuses collisions.
try:
os.link(temporary, destination)
except FileExistsError as exc:
raise CliError(f"refusing to overwrite existing output: {destination}") from exc
finally:
try:
temporary.unlink()
except FileNotFoundError:
pass
def emit_json(
document: dict[str, Any],
*,
output: str | os.PathLike[str] | None = None,
force: bool = False,
) -> None:
"""Print deterministic JSON or write it safely to an explicit file."""
payload = (
json.dumps(document, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
).encode("utf-8")
if len(payload) > MAX_REPORT_BYTES:
raise CliError(
f"report is {len(payload)} bytes; limit is {MAX_REPORT_BYTES} bytes"
)
if output is None:
print(payload.decode("utf-8"), end="")
return
atomic_write_bytes(Path(output), payload, force=force)
def positive_int(value: str) -> int:
"""Argparse converter for strictly positive integers."""
try:
parsed = int(value)
except ValueError as exc:
raise CliError(f"expected an integer, got {value!r}") from exc
if parsed <= 0:
raise CliError("value must be greater than zero")
return parsed
def positive_float(value: str) -> float:
"""Argparse converter for finite, strictly positive floats."""
try:
parsed = float(value)
except ValueError as exc:
raise CliError(f"expected a number, got {value!r}") from exc
if not (parsed > 0 and parsed < float("inf")):
raise CliError("value must be finite and greater than zero")
return parsed

View File

@@ -0,0 +1,541 @@
#!/usr/bin/env python3
"""Build and screen against dated publication-export planning snapshots."""
from __future__ import annotations
import argparse
import json
import math
import sys
from pathlib import Path
from typing import Any
from _common import CliError, emit_json, positive_float
SCHEMA_VERSION = "1.0"
PROFILE_PATH = Path(__file__).resolve().parents[1] / "assets" / "publisher_profiles.json"
def load_profiles() -> dict[str, Any]:
try:
document = json.loads(PROFILE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise CliError(f"cannot load publisher profile asset: {exc}") from exc
if not isinstance(document.get("profiles"), dict):
raise CliError("publisher profile asset does not contain profiles")
return document
def build_plan(
publisher: str,
*,
figure_type: str,
width: str | None = None,
phase: str | None = None,
) -> dict[str, Any]:
"""Build an explicit plan without exporting or claiming compliance."""
document = load_profiles()
try:
profile = document["profiles"][publisher]
except KeyError as exc:
raise CliError(
f"unknown publisher profile {publisher!r}; "
f"available: {', '.join(sorted(document['profiles']))}"
) from exc
widths = profile.get("widths_mm") or {}
if width is not None and width not in widths:
raise CliError(
f"unknown width {width!r} for {publisher}; "
f"available: {', '.join(sorted(widths))}"
)
format_map = profile.get("formats") or {}
dpi_map = profile.get("raster_dpi") or {}
available_types = sorted(set(format_map) | set(dpi_map))
if figure_type not in available_types and available_types:
raise CliError(
f"unknown figure type {figure_type!r} for {publisher}; "
f"available: {', '.join(available_types)}"
)
profile_phase = profile.get("phase")
phase_matches = phase is None or phase == profile_phase
selected_width = float(widths[width]) if width is not None else None
return {
"schema_version": SCHEMA_VERSION,
"publisher": publisher,
"label": profile["label"],
"scope": profile["scope"],
"profile_accessed": profile.get("accessed", document["accessed"]),
"source_status": profile.get("source_status", "reviewed"),
"profile_phase": profile_phase,
"requested_phase": phase,
"phase_matches_snapshot": phase_matches,
"journal_specific": profile.get("journal_specific"),
"figure_type": figure_type,
"width": {
"name": width,
"millimeters": selected_width,
"available": widths,
},
"max_height_mm": profile.get("max_height_mm"),
"recommended_max_height_mm": profile.get("recommended_max_height_mm"),
"max_height_includes_legend": profile.get("max_height_includes_legend", False),
"tiff_requirements": profile.get("tiff_requirements"),
"formats": format_map.get(figure_type) if format_map else None,
"raster_dpi": dpi_map.get(figure_type) if dpi_map else None,
"color_modes": profile.get("color_modes"),
"preferred_color_mode": profile.get("preferred_color_mode"),
"max_file_bytes": profile.get("max_file_bytes"),
"max_file_bytes_exclusive": profile.get("max_file_bytes_exclusive"),
"width_range_px_at_300_dpi": profile.get("width_range_px_at_300_dpi"),
"max_height_px_at_300_dpi": profile.get("max_height_px_at_300_dpi"),
"sources": profile["sources"],
"notes": profile.get("notes", []),
"notice": document["notice"],
}
def _finding(
name: str,
status: str,
*,
actual: Any,
expected: Any,
detail: str,
) -> dict[str, Any]:
return {
"name": name,
"status": status,
"actual": actual,
"expected": expected,
"detail": detail,
}
def _normalized_mode(mode: str | None) -> str | None:
if mode is None:
return None
if mode in {"RGB", "RGBA"}:
return "RGB"
if mode in {"L", "LA", "1", "I", "I;16", "F"}:
return "L"
return mode
def _effective_dimensions(
metadata: dict[str, Any], target_width_mm: float | None
) -> tuple[float | None, float | None, float | None]:
"""Return effective DPI, width mm, and height mm."""
width_px = metadata.get("width_px")
height_px = metadata.get("height_px")
if target_width_mm is not None and width_px:
dpi = float(width_px) / (target_width_mm / 25.4)
height_mm = (
float(height_px) / float(width_px) * target_width_mm
if height_px
else None
)
return dpi, target_width_mm, height_mm
width_mm = metadata.get("width_mm") or metadata.get("width_mm_from_metadata")
height_mm = metadata.get("height_mm") or metadata.get("height_mm_from_metadata")
dpi_values = [
float(value)
for value in (metadata.get("dpi_x"), metadata.get("dpi_y"))
if value
]
return (
min(dpi_values) if dpi_values else None,
float(width_mm) if width_mm is not None else None,
float(height_mm) if height_mm is not None else None,
)
def validate_against_plan(
plan: dict[str, Any],
input_path: str | Path,
*,
width_tolerance_mm: float = 1.0,
) -> dict[str, Any]:
"""Screen inspectable file properties against one explicit plan."""
try:
from image_metadata import inspect_file
except ImportError as exc:
raise CliError(f"cannot import image_metadata.py: {exc}") from exc
inspected = inspect_file(input_path)
metadata = inspected["metadata"]
findings: list[dict[str, Any]] = []
if not plan.get("phase_matches_snapshot", True):
findings.append(_finding(
"submission_phase", "review", actual=plan.get("requested_phase"),
expected=plan.get("profile_phase"),
detail="Requested phase differs; these snapshot rules may not apply.",
))
if plan.get("source_status", "reviewed") != "reviewed":
findings.append(_finding(
"source_currency", "review", actual=plan.get("source_status"),
expected="current target-journal instructions",
detail="Historical or legacy profile requires current journal verification.",
))
if metadata.get("cropbox_differs_from_mediabox"):
findings.append(_finding(
"pdf_page_box", "review", actual="CropBox differs from MediaBox",
expected="confirm intended displayed/production page box",
detail="Width screening below uses the rotated MediaBox, not the cropped view.",
))
formats = plan.get("formats")
actual_format = str(metadata.get("format", "")).lower()
if formats is None:
findings.append(
_finding(
"format",
"unknown",
actual=actual_format,
expected=None,
detail="The profile does not state a universal format for this type.",
)
)
elif not formats:
findings.append(
_finding(
"format",
"unknown",
actual=actual_format,
expected=[],
detail="No raster format was stated on the cited profile page.",
)
)
else:
findings.append(
_finding(
"format",
"pass" if actual_format in formats else "fail",
actual=actual_format,
expected=formats,
detail="Compared with formats explicitly recorded in the snapshot.",
)
)
target_width = plan["width"]["millimeters"]
effective_dpi, effective_width, effective_height = _effective_dimensions(
metadata, target_width
)
dpi_rule = plan.get("raster_dpi")
if metadata.get("kind") == "raster" and dpi_rule:
if effective_dpi is None:
dpi_status = "unknown"
elif (
dpi_rule.get("min") is not None
and effective_dpi < float(dpi_rule["min"])
and not math.isclose(
effective_dpi,
float(dpi_rule["min"]),
rel_tol=1e-12,
abs_tol=1e-9,
)
):
dpi_status = "fail"
elif (
dpi_rule.get("min_exclusive") is not None
and effective_dpi <= float(dpi_rule["min_exclusive"])
):
dpi_status = "fail"
elif (
dpi_rule.get("max") is not None
and effective_dpi > float(dpi_rule["max"])
and not math.isclose(
effective_dpi,
float(dpi_rule["max"]),
rel_tol=1e-12,
abs_tol=1e-9,
)
):
dpi_status = "fail"
else:
dpi_status = (
"review" if set(dpi_rule) == {"target"} else "pass"
)
findings.append(
_finding(
"effective_raster_dpi",
dpi_status,
actual=effective_dpi,
expected=dpi_rule,
detail=(
"Calculated at the selected final width when supplied; "
"otherwise uses embedded DPI metadata. Upsampling is not "
"evidence of added detail. A target without a defined tolerance "
"is a recommendation requiring review, not a pass threshold."
),
)
)
elif dpi_rule and metadata.get("kind") != "raster":
findings.append(
_finding(
"effective_raster_dpi",
"unknown",
actual=None,
expected=dpi_rule,
detail=(
"Vector-container DPI is not meaningful and embedded raster "
"objects were not individually inspected."
),
)
)
else:
findings.append(
_finding(
"effective_raster_dpi",
"unknown",
actual=effective_dpi,
expected=dpi_rule,
detail="No binding DPI rule was recorded for this figure type.",
)
)
if target_width is not None:
if effective_width is None:
width_status = "unknown"
else:
width_status = (
"pass"
if abs(effective_width - target_width) <= width_tolerance_mm
else "fail"
)
findings.append(
_finding(
"final_width_mm",
width_status,
actual=effective_width,
expected={
"target": target_width,
"tolerance": width_tolerance_mm,
},
detail=(
"Raster inputs are evaluated at the requested target width; "
"vector containers use their page dimensions."
),
)
)
max_height = plan.get("max_height_mm")
recommended_height = plan.get("recommended_max_height_mm")
if max_height is None and recommended_height is not None:
max_height = recommended_height
if max_height is not None:
findings.append(
_finding(
"final_height_mm",
(
"unknown"
if effective_height is None
else (
("review" if plan.get("max_height_includes_legend") else "pass")
if effective_height <= float(max_height)
else ("review" if recommended_height is not None else "fail")
)
),
actual=effective_height,
expected={"max": max_height},
detail=(
"Measured exported page/canvas height; legends outside the file "
"are not included. Recommended maxima are advisory; limits "
"including an external legend require manual review."
),
)
)
pixel_range = plan.get("width_range_px_at_300_dpi")
if pixel_range and metadata.get("width_px") is not None:
# The published pixel range is a size equivalence at 300 dpi, not a
# cap on pixels in a valid 600 dpi image at the same physical size.
actual_width_px = effective_width / 25.4 * 300 if effective_width else None
findings.append(
_finding(
"pixel_width_snapshot",
(
"unknown" if actual_width_px is None else (
"pass" if pixel_range[0] - 0.5 <= actual_width_px <= pixel_range[1] + 0.5
else "fail"
)
),
actual=actual_width_px,
expected={"min": pixel_range[0], "max": pixel_range[1]},
detail="Equivalent width at 300 dpi, computed from final physical size; half-pixel rounding tolerance.",
)
)
max_bytes = plan.get("max_file_bytes")
max_bytes_exclusive = plan.get("max_file_bytes_exclusive")
if max_bytes is not None or max_bytes_exclusive is not None:
actual_bytes = inspected["input"]["size_bytes"]
if max_bytes_exclusive is not None:
size_status = (
"pass" if actual_bytes < int(max_bytes_exclusive) else "fail"
)
expected_size = {"less_than": max_bytes_exclusive}
else:
size_status = "pass" if actual_bytes <= int(max_bytes) else "fail"
expected_size = {"max": max_bytes}
findings.append(
_finding(
"file_size",
size_status,
actual=actual_bytes,
expected=expected_size,
detail="Compared with the dated snapshot's file-size limit.",
)
)
allowed_modes = plan.get("color_modes")
actual_mode = metadata.get("mode")
if allowed_modes:
normalized_mode = _normalized_mode(actual_mode)
findings.append(
_finding(
"color_mode",
(
"unknown"
if normalized_mode is None
else (
"pass"
if normalized_mode in allowed_modes
else "fail"
)
),
actual=actual_mode,
expected=allowed_modes,
detail=(
"Raster mode is screened coarsely. ICC profiles and print "
"conversion require separate color-management review."
),
)
)
tiff_rules = plan.get("tiff_requirements") or {}
if actual_format == "tiff":
for field, expected in tiff_rules.items():
actual = metadata.get(field)
findings.append(_finding(
f"tiff_{field}",
"unknown" if actual is None else ("pass" if actual == expected else "fail"),
actual=actual, expected=expected,
detail="Explicit TIFF property recorded by the selected publisher profile.",
))
if metadata.get("has_alpha") is True and "has_alpha" not in tiff_rules:
findings.append(
_finding(
"transparency",
"review",
actual=True,
expected="verify against target journal/background",
detail=(
"The raster has alpha/transparency. Blending can change "
"contrast, and no universal publisher rule is assumed."
),
)
)
counts = {
status: sum(item["status"] == status for item in findings)
for status in ("pass", "fail", "review", "unknown")
}
return {
"schema_version": SCHEMA_VERSION,
"plan": plan,
"inspection": inspected,
"findings": findings,
"screening_summary": counts,
"notice": (
"This screen compares only machine-readable properties with a dated "
"profile. It cannot certify journal acceptance, font appearance, "
"embedded-raster quality, accessibility, or scientific integrity."
),
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Plan publication export from dated official-source snapshots and "
"optionally screen a local file. No network access is used."
)
)
parser.add_argument("--list", action="store_true", help="list profiles")
parser.add_argument("--publisher", help="publisher/profile key")
parser.add_argument(
"--figure-type",
default="combination",
help="figure type in the selected profile (default: combination)",
)
parser.add_argument("--width", help="named final width from the profile")
parser.add_argument(
"--phase", help="your submission phase, for an explicit scope check"
)
parser.add_argument("--input", help="optional local file to screen")
parser.add_argument(
"--width-tolerance-mm",
type=positive_float,
default=1.0,
help="vector/page width tolerance (default: 1.0)",
)
parser.add_argument("--output", help="optional JSON output path")
parser.add_argument("--force", action="store_true")
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
document = load_profiles()
if args.list:
emit_json(
{
"schema_version": SCHEMA_VERSION,
"accessed": document["accessed"],
"profiles": {
name: {
"label": profile["label"],
"scope": profile["scope"],
"phase": profile["phase"],
"accessed": profile.get("accessed", document["accessed"]),
"source_status": profile.get("source_status", "reviewed"),
"sources": profile["sources"],
}
for name, profile in sorted(document["profiles"].items())
},
"notice": document["notice"],
},
output=args.output,
force=args.force,
)
return 0
if not args.publisher:
parser.error("--publisher is required unless --list is used")
plan = build_plan(
args.publisher,
figure_type=args.figure_type,
width=args.width,
phase=args.phase,
)
result = (
validate_against_plan(
plan,
args.input,
width_tolerance_mm=args.width_tolerance_mm,
)
if args.input
else plan
)
emit_json(result, output=args.output, force=args.force)
if args.input:
return 1 if result["screening_summary"]["fail"] else 0
return 0
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,670 @@
#!/usr/bin/env python3
"""Safe Matplotlib export helpers with explicit, auditable settings.
This module does not certify journal compliance. Publisher profiles are dated
planning snapshots and must be confirmed against the target journal.
"""
from __future__ import annotations
import argparse
import importlib.metadata
import json
import math
import os
import sys
import tempfile
from pathlib import Path
from typing import Any, Iterable
from _common import CliError, checked_output_file, emit_json, positive_float
SCHEMA_VERSION = "1.0"
SUPPORTED_FORMATS = {
"pdf",
"svg",
"eps",
"ps",
"png",
"tiff",
"jpeg",
"webp",
}
FORMAT_ALIASES = {"jpg": "jpeg", "tif": "tiff"}
VECTOR_FORMATS = {"pdf", "svg", "eps", "ps"}
RASTER_FORMATS = {"png", "tiff", "jpeg", "webp"}
METADATA_FORMATS = {"pdf", "svg", "png", "eps", "ps"}
MAX_FORMATS = 8
def _normalize_formats(formats: Iterable[str]) -> list[str]:
normalized: list[str] = []
for item in formats:
for value in item.split(","):
raw_name = value.strip().lower().lstrip(".")
name = FORMAT_ALIASES.get(raw_name, raw_name)
if not name:
continue
if name not in SUPPORTED_FORMATS:
raise CliError(
f"unsupported format {name!r}; "
f"available: {', '.join(sorted(SUPPORTED_FORMATS))}"
)
if name not in normalized:
normalized.append(name)
if not normalized:
raise CliError("at least one output format is required")
if len(normalized) > MAX_FORMATS:
raise CliError(f"at most {MAX_FORMATS} output formats are allowed")
return normalized
def _base_output_path(value: str | os.PathLike[str]) -> Path:
path = Path(value).expanduser()
if path.suffix.lower().lstrip(".") in SUPPORTED_FORMATS | set(FORMAT_ALIASES):
path = path.with_suffix("")
if not path.name:
raise CliError("output must include a base filename")
return path
def _font_rc(font_mode: str) -> dict[str, Any]:
if font_mode == "current":
return {}
if font_mode == "truetype":
return {
"pdf.fonttype": 42,
"ps.fonttype": 42,
# Editable SVG text; unlike PDF Type 42, this is not embedded.
"svg.fonttype": "none",
}
if font_mode == "paths":
return {
"pdf.fonttype": 3,
"ps.fonttype": 3,
"svg.fonttype": "path",
}
raise CliError("font_mode must be 'truetype', 'paths', or 'current'")
def _package_version(distribution: str) -> str | None:
try:
return importlib.metadata.version(distribution)
except importlib.metadata.PackageNotFoundError:
return None
def _atomic_savefig(
fig: Any,
destination: Path,
*,
format_name: str,
save_kwargs: dict[str, Any],
overwrite: bool,
tiff_rgb: bool = False,
) -> None:
destination = checked_output_file(destination, force=overwrite)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{destination.stem}.",
suffix=f".{format_name}",
dir=destination.parent,
)
os.close(descriptor)
temporary = Path(temporary_name)
try:
fig.savefig(temporary, format=format_name, **save_kwargs)
if tiff_rgb and format_name == "tiff":
from PIL import Image
with Image.open(temporary) as rendered:
if "A" in rendered.getbands() and rendered.getchannel("A").getextrema() != (255, 255):
raise CliError("RGB TIFF requires an opaque rendered background")
rgb = rendered.convert("RGB")
pillow_options = dict(save_kwargs.get("pil_kwargs", {}))
pillow_options.setdefault("dpi", rendered.info.get("dpi", (save_kwargs["dpi"],) * 2))
if rendered.info.get("icc_profile"):
pillow_options.setdefault("icc_profile", rendered.info["icc_profile"])
try:
rgb.save(temporary, format="TIFF", **pillow_options)
finally:
rgb.close()
if not temporary.exists() or temporary.stat().st_size == 0:
raise CliError(f"Matplotlib produced no data for {destination}")
if overwrite:
os.replace(temporary, destination)
else:
try:
os.link(temporary, destination)
except FileExistsError as exc:
raise CliError(f"refusing to overwrite existing output: {destination}") from exc
except CliError:
raise
except Exception as exc:
raise CliError(
f"failed to export {destination.name} as {format_name}: {exc}"
) from exc
finally:
try:
temporary.unlink()
except FileNotFoundError:
pass
def _validate_provenance(provenance: dict[str, Any] | None) -> dict[str, Any]:
if provenance is None:
return {}
if not isinstance(provenance, dict):
raise CliError("provenance must be a dictionary")
try:
encoded = json.dumps(provenance, sort_keys=True).encode("utf-8")
except (TypeError, ValueError) as exc:
raise CliError(f"provenance must be JSON serializable: {exc}") from exc
if len(encoded) > 1_000_000:
raise CliError("provenance metadata is limited to 1,000,000 bytes")
return provenance
def export_figure(
fig: Any,
filename: str | os.PathLike[str],
*,
formats: Iterable[str] = ("pdf", "png"),
dpi: float = 300,
transparent: bool = False,
tiff_rgb: bool = False,
bbox_inches: str | None = None,
pad_inches: float = 0.1,
facecolor: str = "white",
edgecolor: str = "none",
font_mode: str = "truetype",
overwrite: bool = False,
mkdir: bool = False,
metadata: dict[str, Any] | None = None,
provenance: dict[str, Any] | None = None,
write_manifest: bool = False,
savefig_kwargs: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Export a Matplotlib figure atomically with explicit format settings.
``dpi`` is passed to vector backends too because it controls rasterized
artists and embedded raster images. ``bbox_inches=None`` preserves the
figure's physical page dimensions; use ``"tight"`` only when that change is
intentional.
"""
if not (float(dpi) > 0 and math.isfinite(float(dpi))):
raise CliError("dpi must be finite and greater than zero")
if not (float(pad_inches) >= 0 and math.isfinite(float(pad_inches))):
raise CliError("pad_inches must be finite and non-negative")
normalized_formats = _normalize_formats(formats)
if tiff_rgb and ("tiff" not in normalized_formats or transparent):
raise CliError("tiff_rgb requires TIFF output and transparent=False")
base = _base_output_path(filename)
parent = base.parent
if mkdir:
parent.mkdir(parents=True, exist_ok=True)
if not parent.exists() or not parent.is_dir():
raise CliError(f"output parent directory does not exist: {parent}")
if parent.is_symlink():
raise CliError(f"output parent must not be a symlink: {parent}")
for format_name in normalized_formats:
checked_output_file(
parent / f"{base.name}.{format_name}",
force=overwrite,
)
if write_manifest:
checked_output_file(
parent / f"{base.name}.export.json",
force=overwrite,
)
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError(
"Matplotlib is required for figure export; "
"run with --with 'matplotlib==3.11.2'"
) from exc
provenance_document = _validate_provenance(provenance)
user_metadata = dict(metadata or {})
creator = user_metadata.setdefault(
"Creator",
f"scientific-visualization figure_export.py; Matplotlib {mpl.__version__}",
)
if not isinstance(creator, str):
raise CliError("metadata Creator must be a string")
extra_kwargs = dict(savefig_kwargs or {})
if "format" in extra_kwargs:
raise CliError("savefig_kwargs must not override format")
protected = {
"dpi",
"transparent",
"bbox_inches",
"pad_inches",
"facecolor",
"edgecolor",
"metadata",
}
overlap = protected.intersection(extra_kwargs)
if overlap:
raise CliError(
"savefig_kwargs must not override explicit settings: "
+ ", ".join(sorted(overlap))
)
figure_size = [float(value) for value in fig.get_size_inches()]
outputs: list[dict[str, Any]] = []
warnings_list: list[str] = []
export_rc = _font_rc(font_mode)
if bbox_inches is None:
# Prevent a user's global savefig.bbox="tight" from changing page size.
export_rc["savefig.bbox"] = None
with mpl.rc_context(export_rc):
for format_name in normalized_formats:
destination = parent / f"{base.name}.{format_name}"
checked_output_file(destination, force=overwrite)
if format_name in {"eps", "ps"}:
format_metadata = {"Creator": user_metadata["Creator"]}
elif format_name in METADATA_FORMATS:
format_metadata = user_metadata
else:
format_metadata = None
if user_metadata and format_name not in METADATA_FORMATS:
warnings_list.append(
f"{format_name}: Matplotlib does not support savefig metadata "
"for this format; metadata remains in the optional manifest."
)
save_kwargs: dict[str, Any] = {
"dpi": float(dpi),
"transparent": transparent,
"bbox_inches": bbox_inches,
"pad_inches": float(pad_inches),
"facecolor": "none" if transparent else facecolor,
"edgecolor": "none" if transparent else edgecolor,
**extra_kwargs,
}
if format_metadata is not None:
save_kwargs["metadata"] = format_metadata
if format_name == "tiff":
save_kwargs["pil_kwargs"] = {
**save_kwargs.get("pil_kwargs", {}),
"compression": "tiff_lzw",
}
_atomic_savefig(
fig,
destination,
format_name=format_name,
save_kwargs=save_kwargs,
overwrite=overwrite,
tiff_rgb=tiff_rgb,
)
outputs.append(
{
"path": str(destination.resolve()),
"format": format_name,
"kind": (
"vector-container"
if format_name in VECTOR_FORMATS
else "raster"
),
"size_bytes": destination.stat().st_size,
}
)
report: dict[str, Any] = {
"schema_version": SCHEMA_VERSION,
"outputs": outputs,
"settings": {
"formats": normalized_formats,
"dpi": float(dpi),
"transparent": transparent,
"tiff_rgb": tiff_rgb,
"bbox_inches": bbox_inches,
"pad_inches": float(pad_inches),
"facecolor": facecolor,
"font_mode": font_mode,
"figure_size_inches": figure_size,
},
"versions": {
"matplotlib": mpl.__version__,
"pillow": _package_version("Pillow"),
},
"provenance": provenance_document,
"warnings": sorted(set(warnings_list)),
"notice": (
"Export completed with explicit settings. This report does not "
"establish visual, accessibility, scientific-integrity, or "
"journal-submission compliance."
),
}
if write_manifest:
manifest_path = parent / f"{base.name}.export.json"
emit_json(report, output=manifest_path, force=overwrite)
report["manifest"] = str(manifest_path.resolve())
return report
def save_publication_figure(
fig: Any,
filename: str | os.PathLike[str],
formats: Iterable[str] = ("pdf", "png"),
dpi: float = 300,
transparent: bool = False,
bbox_inches: str | None = None,
pad_inches: float = 0.1,
facecolor: str = "white",
*,
overwrite: bool = False,
provenance: dict[str, Any] | None = None,
write_manifest: bool = False,
**kwargs: Any,
) -> list[Path]:
"""Compatibility wrapper returning saved paths.
Unlike the previous implementation, this function refuses implicit
overwrite, does not silently swallow export errors, does not cap vector
DPI, and preserves figure dimensions unless ``bbox_inches="tight"`` is
requested.
"""
report = export_figure(
fig,
filename,
formats=formats,
dpi=dpi,
transparent=transparent,
bbox_inches=bbox_inches,
pad_inches=pad_inches,
facecolor=facecolor,
overwrite=overwrite,
provenance=provenance,
write_manifest=write_manifest,
savefig_kwargs=kwargs,
)
return [Path(item["path"]) for item in report["outputs"]]
def _load_profiles() -> dict[str, Any]:
profile_path = Path(__file__).resolve().parents[1] / "assets" / "publisher_profiles.json"
try:
document = json.loads(profile_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise CliError(f"cannot load publisher profiles: {exc}") from exc
if not isinstance(document.get("profiles"), dict):
raise CliError("publisher profile asset is malformed")
return document
def check_figure_size(
fig: Any,
journal: str = "nature",
*,
tolerance_mm: float = 1.0,
) -> dict[str, Any]:
"""Compare figure dimensions with a dated profile without claiming compliance."""
if not (tolerance_mm >= 0 and math.isfinite(tolerance_mm)):
raise CliError("tolerance_mm must be finite and non-negative")
document = _load_profiles()
try:
profile = document["profiles"][journal]
except KeyError as exc:
raise CliError(
f"unknown profile {journal!r}; "
f"available: {', '.join(sorted(document['profiles']))}"
) from exc
width_inches, height_inches = (float(value) for value in fig.get_size_inches())
width_mm = width_inches * 25.4
height_mm = height_inches * 25.4
candidates = {
name: float(value)
for name, value in (profile.get("widths_mm") or {}).items()
}
nearest_name = None
nearest_width = None
difference = None
if candidates:
nearest_name, nearest_width = min(
candidates.items(), key=lambda item: abs(width_mm - item[1])
)
difference = abs(width_mm - nearest_width)
max_height = profile.get("max_height_mm")
return {
"schema_version": SCHEMA_VERSION,
"profile": journal,
"profile_label": profile["label"],
"profile_scope": profile["scope"],
"profile_accessed": profile.get("accessed", document["accessed"]),
"source_status": profile.get("source_status", "reviewed"),
"figure": {
"width_inches": width_inches,
"height_inches": height_inches,
"width_mm": width_mm,
"height_mm": height_mm,
},
"nearest_profile_width": {
"name": nearest_name,
"width_mm": nearest_width,
"difference_mm": difference,
"matches_tolerance": (
difference is not None and difference <= tolerance_mm
),
},
"height_screen": {
"maximum_mm": max_height,
"within_snapshot": (
None if max_height is None else height_mm <= float(max_height)
),
},
"notice": (
"A dimensional match to this dated snapshot is not a journal "
"compliance determination."
),
}
def save_for_journal(
fig: Any,
filename: str | os.PathLike[str],
journal: str,
figure_type: str = "combination",
*,
confirm_profile: bool = False,
format_name: str | None = None,
dpi: float | None = None,
overwrite: bool = False,
) -> list[Path]:
"""Use a dated profile only after explicit caller confirmation.
This compatibility helper intentionally requires ``confirm_profile=True``.
Prefer ``export_plan.py`` and ``export_figure`` for an auditable workflow.
"""
if not confirm_profile:
raise CliError(
"publisher rules are date-sensitive; run export_plan.py, verify the "
"target journal, then pass confirm_profile=True if this snapshot is "
"appropriate"
)
document = _load_profiles()
try:
profile = document["profiles"][journal]
except KeyError as exc:
raise CliError(f"unknown publisher profile: {journal!r}") from exc
profile_formats = profile.get("formats") or {}
allowed = profile_formats.get(figure_type) or []
selected = (
_normalize_formats([format_name])[0]
if format_name is not None
else next((name for name in allowed if name in SUPPORTED_FORMATS), None)
)
if selected is None:
raise CliError(
f"profile {journal!r} has no directly exportable {figure_type!r} "
"format; choose settings manually"
)
if selected not in allowed:
raise CliError(
f"format {selected!r} is not recorded for {journal} "
f"{figure_type}; recorded formats: {', '.join(allowed)}"
)
if dpi is None:
raise CliError(
"provide an explicit dpi after reviewing embedded raster content; "
"the compatibility helper does not choose one automatically"
)
dpi_profile = (profile.get("raster_dpi") or {}).get(figure_type) or {}
if dpi_profile.get("min") is not None and dpi < float(dpi_profile["min"]):
raise CliError(f"dpi is below the profile snapshot minimum: {dpi_profile}")
if (
dpi_profile.get("min_exclusive") is not None
and dpi <= float(dpi_profile["min_exclusive"])
):
raise CliError(
f"dpi does not exceed the profile snapshot threshold: {dpi_profile}"
)
if dpi_profile.get("max") is not None and dpi > float(dpi_profile["max"]):
raise CliError(f"dpi is above the profile snapshot maximum: {dpi_profile}")
return save_publication_figure(
fig,
filename,
formats=[selected],
dpi=dpi,
overwrite=overwrite,
provenance={
"publisher_profile": journal,
"profile_accessed": profile.get("accessed", document["accessed"]),
"source_status": profile.get("source_status", "reviewed"),
"profile_scope": profile["scope"],
"caller_confirmed_snapshot": True,
},
write_manifest=True,
)
def verify_font_embedding(pdf_path: str | os.PathLike[str]) -> dict[str, Any]:
"""Return a conservative PDF font-resource report using the metadata tool."""
try:
from image_metadata import inspect_file
except ImportError as exc:
raise CliError(f"cannot import image_metadata.py: {exc}") from exc
report = inspect_file(pdf_path)
if report["metadata"]["format"] != "PDF":
raise CliError("font embedding inspection requires a PDF input")
return {
"path": report["input"]["path"],
"font_resources": report["metadata"].get("font_resources"),
"notice": (
"Inspection covers declared first-page font resources only; "
"publisher preflight may apply additional checks."
),
}
def _demo_figure() -> Any:
try:
import matplotlib.pyplot as plt
except ImportError as exc:
raise CliError(
"Matplotlib is required for --demo; "
"run with --with 'matplotlib==3.11.2'"
) from exc
x_values = [index / 20.0 for index in range(121)]
first = [math.sin(value) for value in x_values]
second = [math.cos(value) for value in x_values]
fig, ax = plt.subplots(figsize=(3.5, 2.5), layout="constrained")
ax.plot(x_values, first, label="sin(x)", marker="o", markevery=20)
ax.plot(
x_values,
second,
label="cos(x)",
linestyle="--",
marker="s",
markevery=20,
)
ax.axhline(0, color="0.35", linewidth=0.7)
ax.set(xlabel="Angle (radians)", ylabel="Amplitude (unitless)")
ax.legend()
return fig
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Render a deterministic Matplotlib export smoke-test. Programmatic "
"helpers in this module support explicit, safe figure export."
)
)
parser.add_argument(
"--demo",
metavar="BASE_PATH",
help="render a deterministic demo to this base path",
)
parser.add_argument(
"--formats",
default="pdf,png",
help="comma-separated formats (default: pdf,png)",
)
parser.add_argument("--dpi", type=positive_float, default=300.0)
parser.add_argument(
"--font-mode",
choices=("truetype", "paths", "current"),
default="truetype",
)
parser.add_argument("--transparent", action="store_true")
parser.add_argument(
"--tight",
action="store_true",
help="use bbox_inches='tight' (changes physical page dimensions)",
)
parser.add_argument("--manifest", action="store_true")
parser.add_argument("--force", action="store_true")
parser.add_argument(
"--style",
choices=("default", "nature", "science", "cell", "minimal", "presentation"),
default="default",
)
parser.add_argument("--palette", default="okabe_ito_on_white")
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
if not args.demo:
parser.error("--demo BASE_PATH is required")
try:
from style_presets import style_context
except ImportError as exc:
raise CliError(f"cannot import style_presets.py: {exc}") from exc
with style_context(args.style, palette_name=args.palette):
fig = _demo_figure()
try:
report = export_figure(
fig,
args.demo,
formats=args.formats.split(","),
dpi=args.dpi,
transparent=args.transparent,
bbox_inches="tight" if args.tight else None,
font_mode=args.font_mode,
overwrite=args.force,
provenance={
"purpose": "deterministic export smoke test",
"raw_data": "analytical sin/cos values generated in code",
"transformations": ["none"],
},
write_manifest=args.manifest,
)
finally:
import matplotlib.pyplot as plt
plt.close(fig)
emit_json(report)
return 0
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,756 @@
#!/usr/bin/env python3
"""Inspect figure/image metadata and screen it against explicit constraints.
The tool is network-free. Pillow is loaded only for raster inputs and pypdf is
loaded only for PDF inputs. A successful screen is not a journal-compliance
claim.
"""
from __future__ import annotations
import argparse
import math
import re
import sys
import warnings
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Iterable
from _common import (
MAX_INPUT_BYTES,
CliError,
checked_input_file,
emit_json,
positive_float,
positive_int,
)
SCHEMA_VERSION = "1.0"
DEFAULT_MAX_PIXELS = 100_000_000
MAX_XML_ELEMENTS = 100_000
MAX_SVG_BYTES = 20 * 1024 * 1024
FORMAT_ALIASES = {
"jpg": "JPEG",
"jpeg": "JPEG",
"tif": "TIFF",
"tiff": "TIFF",
"svg": "SVG",
"pdf": "PDF",
"eps": "EPS",
"ps": "PS",
"png": "PNG",
"webp": "WEBP",
}
VECTOR_SUFFIXES = {".svg", ".pdf", ".eps", ".ps"}
LENGTH_RE = re.compile(
r"^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)"
r"\s*(px|pt|pc|in|cm|mm)?\s*$"
)
def _finite_number(value: Any) -> float | None:
"""Convert a scalar or rational-like value to a finite float."""
try:
number = float(value)
except (TypeError, ValueError, OverflowError):
return None
return number if math.isfinite(number) else None
def _dpi_pair(value: Any) -> tuple[float | None, float | None]:
"""Normalize common Pillow DPI metadata representations."""
if isinstance(value, (tuple, list)) and len(value) >= 2:
return _finite_number(value[0]), _finite_number(value[1])
scalar = _finite_number(value)
return scalar, scalar
def _length_to_inches(value: str | None) -> tuple[float | None, str | None]:
"""Parse an SVG/CSS absolute length using the CSS 96 px/in convention."""
if value is None:
return None, None
match = LENGTH_RE.match(value)
if not match:
return None, None
number = float(match.group(1))
unit = (match.group(2) or "px").lower()
factors = {
"px": 1.0 / 96.0,
"pt": 1.0 / 72.0,
"pc": 1.0 / 6.0,
"in": 1.0,
"cm": 1.0 / 2.54,
"mm": 1.0 / 25.4,
}
if not math.isfinite(number) or number <= 0:
raise CliError("SVG dimensions must be finite and greater than zero")
return number * factors[unit], unit
def _base_metadata(path: Path) -> dict[str, Any]:
info = path.stat()
return {
"path": str(path),
"name": path.name,
"suffix": path.suffix.lower(),
"size_bytes": info.st_size,
}
def inspect_raster(path: Path, *, max_pixels: int) -> dict[str, Any]:
"""Inspect a raster image with Pillow without decoding all pixel data."""
try:
from PIL import Image
except ImportError as exc:
raise CliError(
"Pillow is required for raster metadata; "
"run with --with 'pillow==12.3.0'"
) from exc
previous_limit = Image.MAX_IMAGE_PIXELS
Image.MAX_IMAGE_PIXELS = max_pixels
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as image:
width, height = image.size
if width * height > max_pixels:
raise CliError(
f"image has {width * height} pixels; "
f"limit is {max_pixels}"
)
dpi_x, dpi_y = _dpi_pair(image.info.get("dpi"))
icc = image.info.get("icc_profile")
metadata = {
"format": (image.format or path.suffix.lstrip(".")).upper(),
"kind": "raster",
"width_px": int(width),
"height_px": int(height),
"pixel_count": int(width * height),
"mode": image.mode,
"bands": list(image.getbands()),
"has_alpha": "A" in image.getbands()
or "transparency" in image.info,
"frames": int(getattr(image, "n_frames", 1)),
"dpi_x": dpi_x,
"dpi_y": dpi_y,
"width_mm_from_metadata": (
width / dpi_x * 25.4 if dpi_x and dpi_x > 0 else None
),
"height_mm_from_metadata": (
height / dpi_y * 25.4 if dpi_y and dpi_y > 0 else None
),
"icc_profile_present": bool(icc),
"icc_profile_bytes": len(icc) if isinstance(icc, bytes) else 0,
"compression": image.info.get("compression"),
"exif_present": bool(image.info.get("exif")),
}
image.verify()
return metadata
except Image.DecompressionBombWarning as exc:
raise CliError(f"image exceeds safe pixel limits: {exc}") from exc
except Image.DecompressionBombError as exc:
raise CliError(f"image exceeds safe pixel limits: {exc}") from exc
except OSError as exc:
raise CliError(f"Pillow could not inspect {path}: {exc}") from exc
finally:
Image.MAX_IMAGE_PIXELS = previous_limit
def inspect_svg(path: Path) -> dict[str, Any]:
"""Inspect SVG dimensions and resource types with bounded XML parsing."""
if path.stat().st_size > MAX_SVG_BYTES:
raise CliError(
f"SVG is {path.stat().st_size} bytes; limit is {MAX_SVG_BYTES} bytes"
)
try:
payload = path.read_bytes()
if re.search(br"<!ENTITY\b", payload, flags=re.IGNORECASE) or re.search(
br"<!DOCTYPE[^>]*\[", payload, flags=re.IGNORECASE | re.DOTALL
):
raise CliError("SVG internal DTD/entity declarations are not allowed")
root = ET.fromstring(payload)
except (ET.ParseError, OSError) as exc:
raise CliError(f"invalid SVG/XML input: {exc}") from exc
if root.tag not in {"svg", "{http://www.w3.org/2000/svg}svg"}:
raise CliError("XML root must be an SVG element")
width_raw = root.get("width")
height_raw = root.get("height")
width_in, width_unit = _length_to_inches(width_raw)
height_in, height_unit = _length_to_inches(height_raw)
viewbox_raw = root.get("viewBox")
viewbox: list[float] | None = None
if viewbox_raw:
try:
values = [float(item) for item in re.split(r"[\s,]+", viewbox_raw.strip())]
except ValueError:
values = []
if len(values) == 4 and all(math.isfinite(item) for item in values):
viewbox = values
element_count = 0
text_count = 0
image_count = 0
external_images = 0
for element in root.iter():
element_count += 1
if element_count > MAX_XML_ELEMENTS:
raise CliError(
f"SVG has more than {MAX_XML_ELEMENTS} elements; refusing input"
)
local_name = element.tag.rsplit("}", 1)[-1].lower()
if local_name == "text":
text_count += 1
elif local_name == "image":
image_count += 1
href = (
element.get("href")
or element.get("{http://www.w3.org/1999/xlink}href")
or ""
)
if href and not href.startswith("data:"):
external_images += 1
return {
"format": "SVG",
"kind": "vector",
"width_raw": width_raw,
"height_raw": height_raw,
"width_unit": width_unit,
"height_unit": height_unit,
"width_mm": width_in * 25.4 if width_in is not None else None,
"height_mm": height_in * 25.4 if height_in is not None else None,
"viewbox": viewbox,
"dpi_x": None,
"dpi_y": None,
"mode": None,
"element_count": element_count,
"text_element_count": text_count,
"image_element_count": image_count,
"external_image_count": external_images,
"note": (
"SVG is resolution-independent except for embedded raster images; "
"external image resources were counted but not fetched."
),
}
def _pdf_font_report(page: Any) -> dict[str, Any]:
"""Return a conservative first-page PDF font resource report."""
try:
resources = page.get("/Resources")
resources = resources.get_object() if resources else None
fonts = resources.get("/Font") if resources else None
fonts = fonts.get_object() if fonts else None
except Exception:
fonts = None
if not fonts:
return {
"resource_count": 0,
"embedded_count": 0,
"unembedded_count": 0,
"unknown_count": 0,
"all_embedded": None,
"fonts": [],
}
def embedded_status(font: Any) -> bool | None:
try:
subtype = str(font.get("/Subtype", ""))
if subtype == "/Type3":
# Type 3 glyph programs live in the PDF CharProcs dictionary.
return True if font.get("/CharProcs") else None
candidates = [font]
descendants = font.get("/DescendantFonts")
if descendants:
candidates.extend(
reference.get_object() for reference in descendants
)
saw_descriptor = False
for candidate in candidates:
descriptor = candidate.get("/FontDescriptor")
descriptor = descriptor.get_object() if descriptor else None
if descriptor:
saw_descriptor = True
if any(
descriptor.get(key)
for key in ("/FontFile", "/FontFile2", "/FontFile3")
):
return True
return False if saw_descriptor else None
except Exception:
return None
records: list[dict[str, Any]] = []
for resource_name, reference in fonts.items():
try:
font = reference.get_object()
embedded = embedded_status(font)
records.append(
{
"resource": str(resource_name),
"base_font": str(font.get("/BaseFont", "")),
"subtype": str(font.get("/Subtype", "")),
"embedded": embedded,
}
)
except Exception:
records.append(
{
"resource": str(resource_name),
"base_font": "",
"subtype": "",
"embedded": None,
}
)
definite = [item["embedded"] for item in records if item["embedded"] is not None]
unknown_count = sum(item["embedded"] is None for item in records)
return {
"resource_count": len(records),
"embedded_count": sum(item is True for item in definite),
"unembedded_count": sum(item is False for item in definite),
"unknown_count": unknown_count,
"all_embedded": (
None
if not definite or unknown_count
else all(item is True for item in definite)
),
"fonts": records,
"scope": "first page resource dictionary only",
}
def inspect_pdf(path: Path) -> dict[str, Any]:
"""Inspect PDF page dimensions and first-page font resources with pypdf."""
try:
from pypdf import PdfReader
except ImportError as exc:
raise CliError(
"pypdf is required for PDF metadata; "
"run with --with 'pypdf==6.19.0'"
) from exc
try:
reader = PdfReader(path, strict=False)
if reader.is_encrypted:
try:
unlocked = reader.decrypt("")
except Exception:
unlocked = 0
if not unlocked:
return {
"format": "PDF",
"kind": "vector-container",
"encrypted": True,
"page_count": None,
"width_mm": None,
"height_mm": None,
"dpi_x": None,
"dpi_y": None,
"mode": None,
"font_resources": None,
"note": "Encrypted PDF could not be inspected without a password.",
}
page_count = len(reader.pages)
if page_count < 1:
raise CliError("PDF has no pages")
page = reader.pages[0]
width_pt = float(page.mediabox.width)
height_pt = float(page.mediabox.height)
user_unit = float(page.user_unit)
rotation = int(page.rotation) % 360
crop_width = float(page.cropbox.width)
crop_height = float(page.cropbox.height)
if rotation not in {0, 90, 180, 270} or not all(
math.isfinite(value) and value > 0
for value in (width_pt, height_pt, crop_width, crop_height, user_unit)
):
raise CliError("PDF page dimensions, UserUnit, or rotation are invalid")
display_width, display_height = width_pt * user_unit, height_pt * user_unit
crop_width, crop_height = crop_width * user_unit, crop_height * user_unit
if rotation in {90, 270}:
display_width, display_height = display_height, display_width
crop_width, crop_height = crop_height, crop_width
return {
"format": "PDF",
"kind": "vector-container",
"encrypted": bool(reader.is_encrypted),
"page_count": page_count,
"first_page_width_pt": width_pt,
"first_page_height_pt": height_pt,
"user_unit": user_unit,
"rotation_degrees": rotation,
"width_mm": display_width / 72.0 * 25.4,
"height_mm": display_height / 72.0 * 25.4,
"crop_width_mm": crop_width / 72.0 * 25.4,
"crop_height_mm": crop_height / 72.0 * 25.4,
"cropbox_differs_from_mediabox": list(page.cropbox) != list(page.mediabox),
"dpi_x": None,
"dpi_y": None,
"mode": None,
"font_resources": _pdf_font_report(page),
"note": (
"Dimensions use first-page MediaBox with UserUnit and rotation; "
"CropBox dimensions are reported separately. Raw first_page_*_pt "
"values are unscaled user coordinates. Page size and fonts do not establish the "
"resolution of embedded raster images."
),
}
except CliError:
raise
except Exception as exc:
raise CliError(f"pypdf could not inspect {path}: {exc}") from exc
def inspect_eps(path: Path) -> dict[str, Any]:
"""Inspect an EPS/PS bounding box without invoking PostScript."""
size = path.stat().st_size
with path.open("rb") as handle:
prefix = handle.read(min(size, 128 * 1024))
suffix = b""
if size > len(prefix):
handle.seek(max(0, size - 128 * 1024))
suffix = handle.read(128 * 1024)
text = (prefix + b"\n" + suffix).decode("latin-1", errors="replace")
matches = re.findall(
r"^%%(?:HiRes)?BoundingBox:\s+"
r"([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+"
r"([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s*$",
text,
flags=re.MULTILINE,
)
bbox = [float(value) for value in matches[-1]] if matches else None
width_pt = bbox[2] - bbox[0] if bbox else None
height_pt = bbox[3] - bbox[1] if bbox else None
return {
"format": "EPS" if path.suffix.lower() == ".eps" else "PS",
"kind": "vector-container",
"bounding_box_pt": bbox,
"width_mm": width_pt / 72.0 * 25.4 if width_pt is not None else None,
"height_mm": (
height_pt / 72.0 * 25.4 if height_pt is not None else None
),
"dpi_x": None,
"dpi_y": None,
"mode": None,
"note": "PostScript was not executed; only DSC bounding-box text was read.",
}
def inspect_file(
value: str | Path,
*,
max_bytes: int = MAX_INPUT_BYTES,
max_pixels: int = DEFAULT_MAX_PIXELS,
) -> dict[str, Any]:
"""Inspect a supported local figure/image and return structured metadata."""
path = checked_input_file(value, max_bytes=max_bytes)
suffix = path.suffix.lower()
if suffix == ".svg":
metadata = inspect_svg(path)
elif suffix == ".pdf":
metadata = inspect_pdf(path)
elif suffix in {".eps", ".ps"}:
metadata = inspect_eps(path)
else:
metadata = inspect_raster(path, max_pixels=max_pixels)
return {
"schema_version": SCHEMA_VERSION,
"input": _base_metadata(path),
"metadata": metadata,
}
def _normalize_formats(values: Iterable[str]) -> list[str]:
normalized: list[str] = []
for value in values:
for item in value.split(","):
name = item.strip().lower().lstrip(".")
if not name:
continue
normalized.append(FORMAT_ALIASES.get(name, name.upper()))
return sorted(set(normalized))
def _check(
name: str,
status: str,
*,
actual: Any,
expected: Any,
detail: str,
) -> dict[str, Any]:
return {
"name": name,
"status": status,
"actual": actual,
"expected": expected,
"detail": detail,
}
def screen_metadata(
report: dict[str, Any],
*,
expected_formats: Iterable[str] = (),
expected_modes: Iterable[str] = (),
min_dpi: float | None = None,
max_dpi: float | None = None,
min_width_px: int | None = None,
max_width_px: int | None = None,
min_height_px: int | None = None,
max_height_px: int | None = None,
max_file_bytes: int | None = None,
target_width_mm: float | None = None,
alpha_policy: str | None = None,
) -> dict[str, Any]:
"""Apply only caller-supplied constraints to an inspection report."""
metadata = report["metadata"]
checks: list[dict[str, Any]] = []
formats = _normalize_formats(expected_formats)
if formats:
actual = str(metadata.get("format", "")).upper()
checks.append(
_check(
"format",
"pass" if actual in formats else "fail",
actual=actual,
expected=formats,
detail="File format is compared with the explicit allow-list.",
)
)
modes = sorted(
{
item.strip().upper()
for value in expected_modes
for item in value.split(",")
if item.strip()
}
)
if modes:
actual_mode = metadata.get("mode")
status = (
"unknown"
if actual_mode is None
else ("pass" if str(actual_mode).upper() in modes else "fail")
)
checks.append(
_check(
"mode",
status,
actual=actual_mode,
expected=modes,
detail="Vector containers generally do not expose one image mode.",
)
)
width_px = metadata.get("width_px")
height_px = metadata.get("height_px")
for name, actual, minimum, maximum in (
("width_px", width_px, min_width_px, max_width_px),
("height_px", height_px, min_height_px, max_height_px),
):
if minimum is None and maximum is None:
continue
if actual is None:
status = "unknown"
elif minimum is not None and actual < minimum:
status = "fail"
elif maximum is not None and actual > maximum:
status = "fail"
else:
status = "pass"
checks.append(
_check(
name,
status,
actual=actual,
expected={"min": minimum, "max": maximum},
detail="Pixel dimensions are available for raster inputs.",
)
)
dpi_x = metadata.get("dpi_x")
dpi_y = metadata.get("dpi_y")
effective_dpi = None
if target_width_mm is not None and width_px is not None:
effective_dpi = width_px / (target_width_mm / 25.4)
actual_dpi = effective_dpi
dpi_basis = "effective at target width"
if actual_dpi is None and dpi_x and dpi_y:
actual_dpi = min(float(dpi_x), float(dpi_y))
dpi_basis = "embedded metadata"
if min_dpi is not None or max_dpi is not None:
if actual_dpi is None:
status = "unknown"
elif (
min_dpi is not None
and actual_dpi < min_dpi
and not math.isclose(actual_dpi, min_dpi, rel_tol=1e-12, abs_tol=1e-9)
):
status = "fail"
elif (
max_dpi is not None
and actual_dpi > max_dpi
and not math.isclose(actual_dpi, max_dpi, rel_tol=1e-12, abs_tol=1e-9)
):
status = "fail"
else:
status = "pass"
checks.append(
_check(
"dpi",
status,
actual=actual_dpi,
expected={"min": min_dpi, "max": max_dpi},
detail=(
f"DPI basis: {dpi_basis}. Metadata DPI is not a quality "
"measure; effective DPI depends on final physical size."
),
)
)
if max_file_bytes is not None:
actual_bytes = report["input"]["size_bytes"]
checks.append(
_check(
"file_size",
"pass" if actual_bytes <= max_file_bytes else "fail",
actual=actual_bytes,
expected={"max": max_file_bytes},
detail="File size is measured from the local input.",
)
)
if alpha_policy is not None:
if alpha_policy not in {"allow", "forbid", "require"}:
raise CliError("alpha_policy must be allow, forbid, or require")
has_alpha = metadata.get("has_alpha")
if has_alpha is None:
alpha_status = "unknown"
elif alpha_policy == "allow":
alpha_status = "pass"
elif alpha_policy == "forbid":
alpha_status = "pass" if not has_alpha else "fail"
else:
alpha_status = "pass" if has_alpha else "fail"
checks.append(
_check(
"alpha",
alpha_status,
actual=has_alpha,
expected=alpha_policy,
detail=(
"Alpha is detected for raster modes/transparency metadata. "
"Vector transparency requires rendered-content inspection."
),
)
)
counts = {
status: sum(item["status"] == status for item in checks)
for status in ("pass", "fail", "warning", "unknown")
}
screened = dict(report)
screened["checks"] = checks
screened["screening_summary"] = counts
screened["notice"] = (
"This deterministic metadata screen checks only the supplied constraints. "
"It does not verify visual quality, scientific integrity, accessibility, "
"embedded-raster resolution in vector files, or journal compliance."
)
return screened
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Inspect local raster, SVG, PDF, EPS, or PS metadata and optionally "
"screen it against explicit constraints. No network access is used."
)
)
parser.add_argument("input", help="local figure/image file (symlinks rejected)")
parser.add_argument(
"--format",
dest="formats",
action="append",
default=[],
help="allowed format; repeat or use comma-separated values",
)
parser.add_argument(
"--mode",
dest="modes",
action="append",
default=[],
help="allowed raster mode (for example RGB,L); repeat as needed",
)
parser.add_argument("--min-dpi", type=positive_float)
parser.add_argument("--max-dpi", type=positive_float)
parser.add_argument(
"--target-width-mm",
type=positive_float,
help="calculate effective raster DPI at this final width",
)
parser.add_argument("--min-width-px", type=positive_int)
parser.add_argument("--max-width-px", type=positive_int)
parser.add_argument("--min-height-px", type=positive_int)
parser.add_argument("--max-height-px", type=positive_int)
parser.add_argument("--max-file-bytes", type=positive_int)
parser.add_argument(
"--alpha-policy",
choices=("allow", "forbid", "require"),
help="optional raster alpha/transparency screen",
)
parser.add_argument(
"--max-input-bytes",
type=positive_int,
default=MAX_INPUT_BYTES,
help=f"input byte limit (default: {MAX_INPUT_BYTES})",
)
parser.add_argument(
"--max-pixels",
type=positive_int,
default=DEFAULT_MAX_PIXELS,
help=f"raster pixel limit (default: {DEFAULT_MAX_PIXELS})",
)
parser.add_argument("--output", help="optional JSON report path")
parser.add_argument(
"--force", action="store_true", help="overwrite an existing JSON report"
)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
report = inspect_file(
args.input,
max_bytes=args.max_input_bytes,
max_pixels=args.max_pixels,
)
report = screen_metadata(
report,
expected_formats=args.formats,
expected_modes=args.modes,
min_dpi=args.min_dpi,
max_dpi=args.max_dpi,
min_width_px=args.min_width_px,
max_width_px=args.max_width_px,
min_height_px=args.min_height_px,
max_height_px=args.max_height_px,
max_file_bytes=args.max_file_bytes,
target_width_mm=args.target_width_mm,
alpha_policy=args.alpha_policy,
)
emit_json(report, output=args.output, force=args.force)
return 1 if report["screening_summary"]["fail"] else 0
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,327 @@
#!/usr/bin/env python3
"""Audit palette contrast and heuristic grayscale distinguishability.
WCAG contrast calculations are exact for the supplied sRGB values. Whether a
specific WCAG success criterion applies depends on how a color is used. The
grayscale delta-L* threshold is a screening heuristic, not a standard.
"""
from __future__ import annotations
import argparse
import importlib.util
import itertools
import math
import sys
from pathlib import Path
from types import ModuleType
from typing import Any, Iterable
from _common import CliError, emit_json, positive_float
SCHEMA_VERSION = "1.0"
DEFAULT_BACKGROUND = "#FFFFFF"
DEFAULT_GRAYSCALE_DELTA = 10.0
ROLE_THRESHOLDS = {
"graphical": 3.0,
"large-text": 3.0,
"normal-text": 4.5,
"enhanced-text": 7.0,
}
def parse_hex_color(value: str) -> tuple[int, int, int]:
"""Parse an opaque six-digit sRGB color."""
normalized = value.strip().lstrip("#")
if len(normalized) != 6:
raise CliError(f"expected six-digit hex color, got {value!r}")
try:
channels = tuple(int(normalized[index : index + 2], 16) for index in (0, 2, 4))
except ValueError as exc:
raise CliError(f"invalid hex color: {value!r}") from exc
return channels # type: ignore[return-value]
def canonical_hex(rgb: tuple[int, int, int]) -> str:
return "#" + "".join(f"{channel:02X}" for channel in rgb)
def _linear_channel(channel: int) -> float:
encoded = channel / 255.0
return encoded / 12.92 if encoded <= 0.04045 else ((encoded + 0.055) / 1.055) ** 2.4
def relative_luminance(rgb: tuple[int, int, int]) -> float:
"""Return WCAG relative luminance for an sRGB color."""
red, green, blue = (_linear_channel(channel) for channel in rgb)
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
def contrast_ratio(
first: tuple[int, int, int], second: tuple[int, int, int]
) -> float:
"""Return WCAG contrast ratio for two opaque sRGB colors."""
first_luminance = relative_luminance(first)
second_luminance = relative_luminance(second)
lighter = max(first_luminance, second_luminance)
darker = min(first_luminance, second_luminance)
return (lighter + 0.05) / (darker + 0.05)
def cie_lstar(rgb: tuple[int, int, int]) -> float:
"""Return CIE L* from sRGB/D65, used for grayscale screening."""
luminance = relative_luminance(rgb)
delta = 6.0 / 29.0
if luminance > delta**3:
transformed = luminance ** (1.0 / 3.0)
else:
transformed = luminance / (3.0 * delta**2) + 4.0 / 29.0
return 116.0 * transformed - 16.0
def _load_palette_asset() -> ModuleType:
asset = Path(__file__).resolve().parents[1] / "assets" / "color_palettes.py"
spec = importlib.util.spec_from_file_location(
"_scientific_visualization_color_palettes", asset
)
if spec is None or spec.loader is None:
raise CliError(f"cannot load bundled palette asset: {asset}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def bundled_palettes() -> dict[str, list[str]]:
"""Load bundled palettes without importing Matplotlib."""
module = _load_palette_asset()
palettes = getattr(module, "PALETTES", None)
if not isinstance(palettes, dict):
raise CliError("bundled color_palettes.py does not define PALETTES")
normalized: dict[str, list[str]] = {}
for name, colors in palettes.items():
if isinstance(name, str) and isinstance(colors, (list, tuple)):
normalized[name] = [canonical_hex(parse_hex_color(item)) for item in colors]
return normalized
def audit_palette(
colors: Iterable[str],
*,
background: str = DEFAULT_BACKGROUND,
role: str = "graphical",
contrast_threshold: float | None = None,
grayscale_min_delta: float = DEFAULT_GRAYSCALE_DELTA,
name: str | None = None,
) -> dict[str, Any]:
"""Return deterministic palette contrast and grayscale screening results."""
if role not in ROLE_THRESHOLDS and contrast_threshold is None:
raise CliError(
f"unknown role {role!r}; provide an explicit contrast threshold"
)
threshold = (
float(contrast_threshold)
if contrast_threshold is not None
else ROLE_THRESHOLDS[role]
)
if not math.isfinite(threshold) or threshold <= 1:
raise CliError("contrast threshold must be finite and greater than 1")
if not math.isfinite(grayscale_min_delta) or grayscale_min_delta <= 0:
raise CliError("grayscale delta threshold must be positive and finite")
canonical = [canonical_hex(parse_hex_color(color)) for color in colors]
if not canonical:
raise CliError("at least one color is required")
if len(canonical) > 32:
raise CliError("palette is limited to 32 colors")
background_rgb = parse_hex_color(background)
background_hex = canonical_hex(background_rgb)
color_records: list[dict[str, Any]] = []
parsed: list[tuple[int, int, int]] = []
for index, color in enumerate(canonical):
rgb = parse_hex_color(color)
parsed.append(rgb)
ratio = contrast_ratio(rgb, background_rgb)
color_records.append(
{
"index": index,
"hex": color,
"rgb": list(rgb),
"relative_luminance": round(relative_luminance(rgb), 6),
"cie_lstar": round(cie_lstar(rgb), 3),
"contrast_against_background": round(ratio, 3),
"background_screen": "pass" if ratio >= threshold else "review",
}
)
pair_records: list[dict[str, Any]] = []
for first, second in itertools.combinations(range(len(parsed)), 2):
first_rgb = parsed[first]
second_rgb = parsed[second]
delta = abs(cie_lstar(first_rgb) - cie_lstar(second_rgb))
pair_records.append(
{
"first_index": first,
"second_index": second,
"first_hex": canonical[first],
"second_hex": canonical[second],
"contrast_ratio": round(contrast_ratio(first_rgb, second_rgb), 3),
"grayscale_delta_lstar": round(delta, 3),
"grayscale_screen": (
"pass" if delta >= grayscale_min_delta else "review"
),
}
)
background_reviews = sum(
item["background_screen"] == "review" for item in color_records
)
grayscale_reviews = sum(
item["grayscale_screen"] == "review" for item in pair_records
)
return {
"schema_version": SCHEMA_VERSION,
"palette": {
"name": name,
"colors": color_records,
"color_count": len(color_records),
},
"background": background_hex,
"contrast_screen": {
"role": role,
"threshold": threshold,
"review_count": background_reviews,
"basis": (
"WCAG 2.2 contrast mathematics. Applicability depends on use; "
"for example, SC 1.4.11 covers graphical objects required to "
"understand web content."
),
},
"grayscale_screen": {
"minimum_delta_lstar": grayscale_min_delta,
"review_count": grayscale_reviews,
"pair_count": len(pair_records),
"basis": (
"Heuristic CIE L* separation after removing hue. It does not "
"predict all viewing, printing, or color-vision conditions."
),
},
"pairs": pair_records,
"notice": (
"No palette can establish accessibility by itself. Preserve labels "
"and add redundant encodings such as markers, line styles, direct "
"labels, or patterns; evaluate the rendered figure in context."
),
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Audit sRGB palette contrast against a background and screen "
"pairwise grayscale distinguishability. No network is used."
)
)
source = parser.add_mutually_exclusive_group(required=False)
source.add_argument(
"--palette", help="bundled palette name (use --list-palettes)"
)
source.add_argument(
"--color",
action="append",
default=[],
help="six-digit hex color; repeat for each palette color",
)
parser.add_argument(
"--list-palettes",
action="store_true",
help="print bundled palette names and exit",
)
parser.add_argument("--background", default=DEFAULT_BACKGROUND)
parser.add_argument(
"--role",
choices=sorted(ROLE_THRESHOLDS),
default="graphical",
help="select the WCAG contrast screening threshold",
)
parser.add_argument(
"--contrast-threshold",
type=positive_float,
help="override the role threshold",
)
parser.add_argument(
"--grayscale-min-delta",
type=positive_float,
default=DEFAULT_GRAYSCALE_DELTA,
help=(
"heuristic minimum CIE L* separation "
f"(default: {DEFAULT_GRAYSCALE_DELTA})"
),
)
parser.add_argument(
"--fail-on",
choices=("none", "background", "grayscale", "any"),
default="none",
help="return exit 1 for selected review findings (default: none)",
)
parser.add_argument("--output", help="optional JSON report path")
parser.add_argument(
"--force", action="store_true", help="overwrite an existing JSON report"
)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
palettes = bundled_palettes()
if args.list_palettes:
emit_json(
{
"schema_version": SCHEMA_VERSION,
"palettes": {
name: {"count": len(colors), "colors": colors}
for name, colors in sorted(palettes.items())
},
},
output=args.output,
force=args.force,
)
return 0
if args.palette:
if args.palette not in palettes:
raise CliError(
f"unknown palette {args.palette!r}; "
f"available: {', '.join(sorted(palettes))}"
)
colors = palettes[args.palette]
palette_name = args.palette
else:
colors = args.color
palette_name = "custom"
if not colors:
raise CliError("provide --palette or at least one --color")
report = audit_palette(
colors,
background=args.background,
role=args.role,
contrast_threshold=args.contrast_threshold,
grayscale_min_delta=args.grayscale_min_delta,
name=palette_name,
)
emit_json(report, output=args.output, force=args.force)
background_review = report["contrast_screen"]["review_count"] > 0
grayscale_review = report["grayscale_screen"]["review_count"] > 0
should_fail = (
(args.fail_on in {"background", "any"} and background_review)
or (args.fail_on in {"grayscale", "any"} and grayscale_review)
)
return 1 if should_fail else 0
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,503 @@
#!/usr/bin/env python3
"""Scoped Matplotlib style presets for scientific figures.
Presets are visual starting points, not journal-compliance profiles. Matplotlib
is imported lazily so listing and help work in a standard-library environment.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import sys
from contextlib import contextmanager
from pathlib import Path
from types import ModuleType
from typing import Any, Iterator
from _common import CliError, atomic_write_bytes, checked_output_file
ASSET_ROOT = Path(__file__).resolve().parents[1] / "assets"
PROFILE_PATH = ASSET_ROOT / "publisher_profiles.json"
SCHEMA_VERSION = "1.0"
BASE_STYLE: dict[str, Any] = {
"figure.dpi": 100,
"figure.facecolor": "white",
"figure.autolayout": False,
"figure.constrained_layout.use": False,
"font.size": 8,
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
"axes.linewidth": 0.6,
"axes.labelsize": 8,
"axes.titlesize": 8,
"axes.labelweight": "normal",
"axes.spines.top": False,
"axes.spines.right": False,
"axes.edgecolor": "black",
"axes.labelcolor": "black",
"axes.axisbelow": True,
"axes.grid": False,
"xtick.major.size": 3,
"xtick.minor.size": 2,
"xtick.major.width": 0.6,
"xtick.minor.width": 0.5,
"xtick.labelsize": 7,
"xtick.direction": "out",
"ytick.major.size": 3,
"ytick.minor.size": 2,
"ytick.major.width": 0.6,
"ytick.minor.width": 0.5,
"ytick.labelsize": 7,
"ytick.direction": "out",
"lines.linewidth": 1.4,
"lines.markersize": 4,
"lines.markeredgewidth": 0.6,
"patch.linewidth": 0.6,
"legend.fontsize": 7,
"legend.frameon": False,
"savefig.dpi": 300,
"savefig.format": "pdf",
# "tight" changes the exported physical page dimensions. Opt in explicitly.
"savefig.bbox": "standard",
"savefig.pad_inches": 0.05,
"savefig.transparent": False,
"savefig.facecolor": "white",
"savefig.edgecolor": "white",
"image.cmap": "viridis",
# Type 42 keeps TrueType fonts editable/embedded in PDF/PS.
"pdf.fonttype": 42,
"ps.fonttype": 42,
# SVG text remains text but depends on font availability at render time.
"svg.fonttype": "none",
}
STYLE_OVERRIDES: dict[str, dict[str, Any]] = {
"default": {},
"nature": {
"font.size": 7,
"axes.labelsize": 7,
"axes.titlesize": 7,
"xtick.labelsize": 6,
"ytick.labelsize": 6,
"legend.fontsize": 6,
"lines.linewidth": 1.0,
"savefig.dpi": 450,
},
"science": {
"font.size": 7,
"axes.labelsize": 7,
"axes.titlesize": 7,
"xtick.labelsize": 6,
"ytick.labelsize": 6,
"legend.fontsize": 6,
"savefig.dpi": 300,
},
"cell": {
"font.size": 7,
"axes.labelsize": 8,
"axes.titlesize": 8,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"legend.fontsize": 7,
"savefig.dpi": 300,
},
"minimal": {
"axes.linewidth": 0.8,
"xtick.major.width": 0.8,
"ytick.major.width": 0.8,
"lines.linewidth": 1.8,
},
"presentation": {
"font.size": 14,
"axes.labelsize": 16,
"axes.titlesize": 18,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"legend.fontsize": 12,
"axes.linewidth": 1.4,
"lines.linewidth": 2.4,
"lines.markersize": 8,
"savefig.format": "png",
},
}
STYLE_NOTICES = {
"nature": (
"Starting point based on flagship Nature final-artwork guidance "
"accessed 2026-10-01; verify article stage and current instructions."
),
"science": (
"Historical Science revised-manuscript guidance accessed 2026-07-23; "
"live access failed on 2026-10-01. Verify current journal instructions."
),
"cell": (
"Starting point based on general Cell Press production guidance accessed "
"2026-10-01; journal and article-type exceptions exist."
),
}
def _load_palette_asset() -> ModuleType:
asset = ASSET_ROOT / "color_palettes.py"
spec = importlib.util.spec_from_file_location(
"_scientific_visualization_color_palettes", asset
)
if spec is None or spec.loader is None:
raise CliError(f"cannot load bundled palette asset: {asset}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def available_palettes() -> dict[str, list[str]]:
palettes = getattr(_load_palette_asset(), "PALETTES", None)
if not isinstance(palettes, dict):
raise CliError("bundled palette asset does not define PALETTES")
return {name: list(colors) for name, colors in palettes.items()}
def get_style(
style_name: str = "default",
*,
palette_name: str = "okabe_ito_on_white",
) -> dict[str, Any]:
"""Return a validated plain rcParams dictionary without global mutation."""
if style_name not in STYLE_OVERRIDES:
raise CliError(
f"unknown style {style_name!r}; "
f"available: {', '.join(sorted(STYLE_OVERRIDES))}"
)
palettes = available_palettes()
if palette_name not in palettes:
raise CliError(
f"unknown palette {palette_name!r}; "
f"available: {', '.join(sorted(palettes))}"
)
style = dict(BASE_STYLE)
style.update(STYLE_OVERRIDES[style_name])
# Stored separately because a Matplotlib Cycler is not JSON serializable.
style["_palette_colors"] = palettes[palette_name]
return style
def _matplotlib_style(style: dict[str, Any]) -> dict[str, Any]:
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError(
"Matplotlib is required to apply styles; "
"run with --with 'matplotlib==3.11.2'"
) from exc
prepared = dict(style)
colors = prepared.pop("_palette_colors")
prepared["axes.prop_cycle"] = mpl.cycler(color=colors)
# rcParams validation catches stale or misspelled keys.
validated = mpl.RcParams()
validated.update(prepared)
return dict(validated)
def apply_publication_style(
style_name: str = "default",
*,
palette_name: str = "okabe_ito_on_white",
reset: bool = False,
) -> dict[str, Any]:
"""Apply a validated style globally and return the settings used."""
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError(
"Matplotlib is required to apply styles; "
"run with --with 'matplotlib==3.11.2'"
) from exc
if reset:
mpl.rcdefaults()
style = _matplotlib_style(get_style(style_name, palette_name=palette_name))
mpl.rcParams.update(style)
return {
"style": style_name,
"palette": palette_name,
"notice": STYLE_NOTICES.get(
style_name,
"General-purpose visual preset; review the rendered figure in context.",
),
}
@contextmanager
def style_context(
style_name: str = "default",
*,
palette_name: str = "okabe_ito_on_white",
) -> Iterator[dict[str, Any]]:
"""Temporarily apply a preset without leaking global rcParams changes."""
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError(
"Matplotlib is required to use a style context; "
"run with --with 'matplotlib==3.11.2'"
) from exc
style = _matplotlib_style(get_style(style_name, palette_name=palette_name))
with mpl.rc_context(style):
yield {
"style": style_name,
"palette": palette_name,
"notice": STYLE_NOTICES.get(style_name),
}
def set_color_palette(palette_name: str = "okabe_ito_on_white") -> list[str]:
"""Set only the Matplotlib color cycle, preserving other rcParams."""
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError(
"Matplotlib is required to set a palette; "
"run with --with 'matplotlib==3.11.2'"
) from exc
palettes = available_palettes()
if palette_name not in palettes:
raise CliError(
f"unknown palette {palette_name!r}; "
f"available: {', '.join(sorted(palettes))}"
)
colors = palettes[palette_name]
mpl.rcParams["axes.prop_cycle"] = mpl.cycler(color=colors)
return colors
def load_publisher_profiles() -> dict[str, Any]:
"""Load the bundled dated publisher snapshots."""
try:
document = json.loads(PROFILE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise CliError(f"cannot load publisher profiles: {exc}") from exc
profiles = document.get("profiles")
if not isinstance(profiles, dict):
raise CliError("publisher profile asset is malformed")
return document
def figure_size_for_profile(
publisher: str,
width: str,
*,
aspect: float = 0.75,
) -> tuple[float, float]:
"""Return width/height in inches from a dated profile snapshot."""
if not (math_is_finite_positive(aspect)):
raise CliError("aspect must be finite and greater than zero")
document = load_publisher_profiles()
try:
profile = document["profiles"][publisher]
except KeyError as exc:
raise CliError(
f"unknown publisher {publisher!r}; "
f"available: {', '.join(sorted(document['profiles']))}"
) from exc
widths = profile.get("widths_mm") or {}
if width not in widths:
raise CliError(
f"width {width!r} unavailable for {publisher}; "
f"available: {', '.join(sorted(widths))}"
)
width_inches = float(widths[width]) / 25.4
return width_inches, width_inches * aspect
def math_is_finite_positive(value: float) -> bool:
return value > 0 and value < float("inf")
def configure_for_journal(
journal: str,
figure_width: str = "single",
*,
aspect: float = 0.75,
palette_name: str = "okabe_ito_on_white",
) -> dict[str, Any]:
"""Compatibility helper using a dated profile, without claiming compliance."""
aliases = {
"plos": "default",
"acs": "default",
"ieee": "default",
"bmc": "default",
"elsevier": "default",
}
style_name = journal if journal in {"nature", "science", "cell"} else aliases.get(journal)
if style_name is None:
raise CliError(f"unknown journal/publisher profile: {journal!r}")
notice = apply_publication_style(style_name, palette_name=palette_name)
width_aliases = {
"nature": {"double": "full"},
"cell": {"double": "full"},
"plos": {"single": "text-column", "double": "full"},
"acs": {"double": "full"},
"ieee": {"double": "full"},
"bmc": {"single": "half", "double": "full"},
"elsevier": {"double": "full"},
}
profile_width = width_aliases.get(journal, {}).get(
figure_width, figure_width
)
width_inches, height_inches = figure_size_for_profile(
journal, profile_width, aspect=aspect
)
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError("Matplotlib is required to configure figure size") from exc
mpl.rcParams["figure.figsize"] = (width_inches, height_inches)
return {
**notice,
"publisher_profile": journal,
"profile_width": profile_width,
"figsize_inches": [width_inches, height_inches],
"profile_accessed": load_publisher_profiles()["profiles"][journal].get(
"accessed", load_publisher_profiles()["accessed"]
),
"notice": (
"Configured from a dated planning snapshot. This does not establish "
"journal compliance; verify current target-journal instructions."
),
}
def _mplstyle_value(key: str, value: Any) -> str:
if isinstance(value, bool):
return "True" if value else "False"
if isinstance(value, (list, tuple)):
return ", ".join(str(item) for item in value)
return str(value)
def create_style_template(
output_file: str | Path,
*,
style_name: str = "default",
palette_name: str = "okabe_ito_on_white",
force: bool = False,
) -> Path:
"""Write a parseable mplstyle file, refusing implicit overwrite."""
output = checked_output_file(output_file, force=force)
style = get_style(style_name, palette_name=palette_name)
colors = style.pop("_palette_colors")
lines = [
"# Scientific visualization style preset",
f"# style: {style_name}; palette: {palette_name}",
"# Verify current target-journal rules before submission.",
"",
]
for key, value in style.items():
lines.append(f"{key}: {_mplstyle_value(key, value)}")
lines.append(
"axes.prop_cycle: cycler('color', "
+ json.dumps(colors)
+ ")"
)
payload = ("\n".join(lines) + "\n").encode("utf-8")
atomic_write_bytes(output, payload, force=force)
return output
def reset_to_default() -> None:
"""Reset Matplotlib's global rcParams."""
try:
import matplotlib as mpl
except ImportError as exc:
raise CliError("Matplotlib is required to reset rcParams") from exc
mpl.rcdefaults()
def _serializable_style(style_name: str, palette_name: str) -> dict[str, Any]:
style = get_style(style_name, palette_name=palette_name)
colors = style.pop("_palette_colors")
return {
"schema_version": SCHEMA_VERSION,
"style": style_name,
"palette": palette_name,
"palette_colors": colors,
"rcparams": style,
"notice": STYLE_NOTICES.get(
style_name,
"General-purpose visual preset; verify the rendered output.",
),
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Inspect or write deterministic Matplotlib style presets. "
"Presets are not journal-compliance certifications."
)
)
parser.add_argument(
"--list", action="store_true", help="list available styles and palettes"
)
parser.add_argument(
"--show", metavar="STYLE", help="print one style as JSON"
)
parser.add_argument(
"--write", nargs=2, metavar=("STYLE", "PATH"), help="write an mplstyle file"
)
parser.add_argument(
"--palette", default="okabe_ito_on_white", help="palette name"
)
parser.add_argument(
"--force", action="store_true", help="overwrite an existing style file"
)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
if args.list:
print(
json.dumps(
{
"schema_version": SCHEMA_VERSION,
"styles": sorted(STYLE_OVERRIDES),
"palettes": {
name: colors
for name, colors in sorted(available_palettes().items())
},
},
indent=2,
sort_keys=True,
)
)
return 0
if args.show:
print(
json.dumps(
_serializable_style(args.show, args.palette),
indent=2,
sort_keys=True,
)
)
return 0
if args.write:
style_name, output = args.write
written = create_style_template(
output,
style_name=style_name,
palette_name=args.palette,
force=args.force,
)
print(written)
return 0
parser.error("choose --list, --show STYLE, or --write STYLE PATH")
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Generate a deterministic preview for a bundled scientific figure style."""
from __future__ import annotations
import argparse
import math
import sys
from typing import Any
from _common import CliError, emit_json, positive_float
def build_preview(style_name: str, palette_name: str) -> tuple[Any, dict[str, Any]]:
"""Create a deterministic multi-panel preview and palette audit."""
try:
import matplotlib as mpl
import matplotlib.pyplot as plt
except ImportError as exc:
raise CliError(
"Matplotlib is required for previews; "
"run with --with 'matplotlib==3.11.2'"
) from exc
from palette_audit import audit_palette
from style_presets import available_palettes, style_context
palettes = available_palettes()
if palette_name not in palettes:
raise CliError(
f"unknown palette {palette_name!r}; "
f"available: {', '.join(sorted(palettes))}"
)
colors = palettes[palette_name]
if len(colors) < 3:
raise CliError("preview palette must contain at least three colors")
audit = audit_palette(
colors,
background="#FFFFFF",
role="graphical",
name=palette_name,
)
with style_context(style_name, palette_name=palette_name):
fig, axes = plt.subplots(
2,
2,
figsize=(7.0, 5.2),
layout="constrained",
)
x_values = [index / 10.0 for index in range(41)]
line_styles = ["-", "--", "-.", ":"]
markers = ["o", "s", "^", "D"]
for index in range(4):
values = [
math.sin(value + index * 0.45) + index * 0.35
for value in x_values
]
axes[0, 0].plot(
x_values,
values,
color=colors[index % len(colors)],
linestyle=line_styles[index],
marker=markers[index],
markevery=8,
label=f"Series {index + 1}",
)
axes[0, 0].axhline(0, color="0.35", linewidth=0.7)
axes[0, 0].set(
xlabel="Time (hours)",
ylabel="Response (a.u.)",
title="Color plus redundant encoding",
)
axes[0, 0].legend(ncols=2)
categories = ["Control", "Low", "High"]
values = [0.0, 1.4, -0.8]
hatches = ["", "///", "xx"]
bars = axes[0, 1].bar(
categories,
values,
color=[colors[index % len(colors)] for index in range(3)],
edgecolor="black",
linewidth=0.7,
)
for bar, hatch in zip(bars, hatches):
bar.set_hatch(hatch)
axes[0, 1].axhline(0, color="black", linewidth=0.7)
axes[0, 1].set(
ylabel="Change from baseline (unit)",
title="Signed bars with visible zero",
)
matrix = [
[-2.0, -1.2, -0.4, 0.2, 1.0],
[-1.5, -0.8, float("nan"), 0.8, 1.7],
[-1.0, -0.2, 0.0, 1.1, 2.0],
]
colormap = mpl.colormaps["RdBu_r"].with_extremes(bad="#777777")
image = axes[1, 0].imshow(
matrix,
cmap=colormap,
norm=mpl.colors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=2),
aspect="auto",
interpolation="nearest",
)
axes[1, 0].set(
xlabel="Sample",
ylabel="Feature",
title="Centered normalization; gray = missing",
)
colorbar = fig.colorbar(image, ax=axes[1, 0])
colorbar.set_label("Effect (unit)")
groups = [
[1.0, 1.2, 0.9, 1.1, 1.4, 0.8],
[1.4, 1.8, 1.6, 1.5, 2.0, 1.7],
[0.7, 0.9, 1.0, 0.6, 0.8, 1.1],
]
for index, group in enumerate(groups):
offsets = [-0.08, -0.05, -0.02, 0.02, 0.05, 0.08]
axes[1, 1].scatter(
[index + offset for offset in offsets],
group,
color=colors[index % len(colors)],
edgecolor="black",
linewidth=0.4,
marker=markers[index],
zorder=2,
)
ordered = sorted(group)
median = (ordered[2] + ordered[3]) / 2
axes[1, 1].plot(
[index - 0.15, index + 0.15],
[median, median],
color="black",
linewidth=1.2,
)
axes[1, 1].set(
xticks=range(3),
xticklabels=categories,
ylabel="Observed value (unit)",
title="Raw observations with median",
)
for label, ax in zip("ABCD", axes.flat):
ax.text(
-0.12,
1.06,
label,
transform=ax.transAxes,
fontweight="bold",
va="top",
)
fig.suptitle(f"Style preview: {style_name} / {palette_name}")
return fig, audit
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Render a deterministic accessible-style preview with line, bar, "
"heatmap, missing-data, and raw-observation examples."
)
)
parser.add_argument("--output", required=True, help="output base path")
parser.add_argument(
"--style",
choices=("default", "nature", "science", "cell", "minimal", "presentation"),
default="default",
)
parser.add_argument("--palette", default="okabe_ito_on_white")
parser.add_argument(
"--formats", default="png,svg", help="comma-separated formats"
)
parser.add_argument("--dpi", type=positive_float, default=300.0)
parser.add_argument("--manifest", action="store_true")
parser.add_argument("--force", action="store_true")
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
try:
args = parser.parse_args(argv)
from figure_export import export_figure
fig, audit = build_preview(args.style, args.palette)
try:
report = export_figure(
fig,
args.output,
formats=args.formats.split(","),
dpi=args.dpi,
overwrite=args.force,
provenance={
"purpose": "deterministic bundled-style preview",
"style": args.style,
"palette": args.palette,
"data": "synthetic values defined in style_preview.py",
"transformations": [
"analytical sine offsets",
"explicit TwoSlopeNorm(-2, 0, 2)",
"median of displayed raw observations",
],
"palette_screen": {
"background_review_count": audit["contrast_screen"][
"review_count"
],
"grayscale_review_count": audit["grayscale_screen"][
"review_count"
],
},
},
write_manifest=args.manifest,
)
finally:
import matplotlib.pyplot as plt
plt.close(fig)
report["palette_audit"] = {
"contrast_screen": audit["contrast_screen"],
"grayscale_screen": audit["grayscale_screen"],
"notice": audit["notice"],
}
emit_json(report)
return 0
except CliError as exc:
parser.exit(2, f"error: {exc}\n")
if __name__ == "__main__":
sys.exit(main())