# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# QC2 @ CHALMERS CALIBRATION TOOLKIT
# (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
# CONTRIBUTORS list:
#
# Matteo Robbiati, robbiati@chalmers.se
# Axel Andersson, axean@chalmers.se
# Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""Utilities for creating PDF reports with images and text pages."""
import logging
import os
import textwrap
from datetime import datetime
from pathlib import Path
from pypdf import PdfWriter
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
# ------------------------ Defaults variables
PAGE_ORIENTATION = landscape
PAGESIZE = A4
LEFT_MARGIN = 50
RIGHT_MARGIN = 50
TOP_MARGIN = 60
BOTTOM_MARGIN = 50
TITLE_OFFSET = 30
FONTSIZE_TITLE = 18
FONTSIZE_BODY = 14
LINE_HEIGHT = 22
PARAGRAPH_SPACING = 12
WRAP_WIDTH = 90
FONT_NAME = "Helvetica"
FONT_NAME_BOLD = "Helvetica-Bold"
FONT_NAME_ITALIC = "Helvetica-Oblique"
PDF_REPORT_FILENAME = "calibration_report.pdf"
PDF_REPORT_FOLDER = "out/pdf"
logger = logging.getLogger(__name__)
# ------------------- Functions
[docs]
def merge_pdfs(base_pdf: Path, new_pdf: Path, output: Path):
"""Append new_pdf to base_pdf, writing result to output."""
merger = PdfWriter()
if base_pdf.exists():
merger.append(str(base_pdf))
merger.append(str(new_pdf))
with open(output, "wb") as f:
merger.write(f)
logger.info("Merged PDF saved to %s", output)
os.remove(new_pdf)
[docs]
def create_image_page(
image_path: Path,
output_path: Path,
node_name: str | None = None,
custom_name: str | None = None,
unique_id: str | None = None,
):
"""Render a PDF page with an image and three optional identification lines."""
c = canvas.Canvas(
str(output_path),
pagesize=PAGE_ORIENTATION(PAGESIZE),
pageCompression=1,
)
page_width, page_height = PAGE_ORIENTATION(PAGESIZE)
starting_y = page_height - TOP_MARGIN / 1.1
line_spacing = FONTSIZE_BODY + 6
header_lines = 0
c.setFont(FONT_NAME, FONTSIZE_BODY)
if node_name:
c.drawString(LEFT_MARGIN, starting_y, f"Tergite node name: {node_name}")
starting_y -= line_spacing
header_lines += 1
if custom_name:
c.drawString(LEFT_MARGIN, starting_y, f"Custom name: {custom_name}")
starting_y -= line_spacing
header_lines += 1
if unique_id:
c.drawString(LEFT_MARGIN, starting_y, f"Unique ID: {unique_id}")
starting_y -= line_spacing
header_lines += 1
header_reserved_space = (
header_lines * line_spacing + 30
) # small padding below header
image_bottom = BOTTOM_MARGIN
image_top = page_height - TOP_MARGIN - header_reserved_space
available_height = image_top - image_bottom
c.drawImage(
str(image_path),
LEFT_MARGIN,
image_bottom,
width=page_width - LEFT_MARGIN - RIGHT_MARGIN,
height=available_height,
preserveAspectRatio=True,
anchor="sw",
)
c.save()
[docs]
def create_text_page(
paragraphs: list[str],
output_path: Path,
title: str | None = None,
device_config=None,
):
"""Create a one-page PDF with a title, paragraphs, and optional '.all' table."""
c = canvas.Canvas(
str(output_path),
pagesize=PAGE_ORIENTATION(PAGESIZE),
pageCompression=1,
)
page_width, page_height = PAGE_ORIENTATION(PAGESIZE)
y = page_height - TOP_MARGIN
# ---- Title ----
if title:
c.setFont(FONT_NAME_BOLD, FONTSIZE_TITLE)
title_width = c.stringWidth(title, FONT_NAME_BOLD, FONTSIZE_TITLE)
c.drawString((page_width - title_width) / 2, y, title)
y -= 2 * LINE_HEIGHT
# ---- Paragraphs ----
for paragraph in paragraphs:
if y < BOTTOM_MARGIN + 80:
c.showPage()
y = page_height - TOP_MARGIN
c.setFont(
FONT_NAME_ITALIC if "Otherwise" in paragraph else FONT_NAME, FONTSIZE_BODY
)
for wrapped in textwrap.wrap(paragraph, width=WRAP_WIDTH):
c.drawString(LEFT_MARGIN, y, wrapped)
y -= LINE_HEIGHT
y -= PARAGRAPH_SPACING
# ---- Device configuration ----
if device_config and hasattr(device_config, "filepath"):
import yaml
try:
with open(device_config.filepath, encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception as e:
logger.warning(f"YAML load error: {e}")
data = None
if data:
c.showPage()
y = page_height - TOP_MARGIN
y = _draw_device_table(c, data, y, page_width)
c.save()
def _draw_device_table(c, data: dict, y: float, page_width: float) -> float:
"""Render '.all' sections on the first page and,
if present, couplers with non-zero parking currents on a second page."""
def walk(prefix, sub):
for k, v in sub.items():
new_key = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
yield from walk(new_key, v)
else:
yield new_key, v
flat = dict(walk("", data))
selected = [(k, v) for k, v in flat.items() if ".all" in k]
font_size = max(FONTSIZE_BODY - 2, 9)
title_size = font_size + 4
line_height = font_size + 2
page_inner_width = page_width - LEFT_MARGIN - RIGHT_MARGIN
col_width = page_inner_width / 2
x_left = LEFT_MARGIN
x_right = LEFT_MARGIN + col_width
# ------------------ PAGE 1 ------------------
now_text = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.setFont(FONT_NAME_BOLD, title_size)
title_text = (
f"Relevant device parameters at time {now_text}, shared by the chip components."
)
title_width = c.stringWidth(title_text, FONT_NAME_BOLD, title_size)
c.drawString((page_width - title_width) / 2, y, title_text)
y -= 1.6 * line_height # extra space after title
if not selected:
c.setFont(FONT_NAME_ITALIC, font_size)
c.drawString(LEFT_MARGIN, y, "(No '.all' sections found.)")
return y - line_height
# ---------- group .all data ----------
from collections import defaultdict
grouped = defaultdict(list)
for key, value in selected:
*section_parts, param = key.split(".")
section = ".".join(section_parts)
grouped[section].append((param, value))
# flatten into lines
lines = []
for section, pairs in grouped.items():
lines.append((True, f"[{section}]"))
for k, v in pairs:
lines.append((False, f"{k}: {v}"))
total_lines = len(lines)
per_col = (total_lines + 1) // 2
c.setFont(FONT_NAME_BOLD, font_size)
c.drawString(LEFT_MARGIN, y, "Device configuration (.all sections):")
y -= line_height
start_y = y
c.setFont(FONT_NAME, font_size)
for i, (is_header, text) in enumerate(lines):
if i < per_col:
col_x = x_left
cur_y = start_y - i * line_height
else:
col_x = x_right
cur_y = start_y - (i - per_col) * line_height
c.setFont(FONT_NAME_BOLD if is_header else FONT_NAME, font_size)
c.drawString(col_x, cur_y, text)
# Identify couplers with non‑zero parking current
couplers = data.get("device", {}).get("coupler", {})
coupler_sections = {}
for name, conf in couplers.items():
if isinstance(conf, dict):
try:
pc_val = float(conf.get("parking_current", 0))
except Exception:
continue
if abs(pc_val) > 1e-15:
coupler_sections[name] = conf
if not coupler_sections:
return start_y - per_col * line_height
# ------------------ PAGE 2 (only if some parking currents are non zero) ------------------
c.showPage()
page_width, page_height = PAGE_ORIENTATION(PAGESIZE)
y = page_height - TOP_MARGIN
# Page‑level title
c.setFont(FONT_NAME_BOLD, title_size)
title2 = "Coupler parameters, if coupler parking currents are non-zero."
title2_width = c.stringWidth(title2, FONT_NAME_BOLD, title_size)
c.drawString((page_width - title2_width) / 2, y, title2)
y -= 1.6 * line_height
# section header
c.setFont(FONT_NAME_BOLD, font_size)
y -= line_height
start_y = y
# Prepare coupler rows
lines_couplers = []
for name, fields in coupler_sections.items():
lines_couplers.append((True, f"[device.coupler.{name}]"))
for k, v in fields.items():
lines_couplers.append((False, f"{k}: {v}"))
total_lines_cpl = len(lines_couplers)
per_col_cpl = (total_lines_cpl + 1) // 2
for i, (is_header, text) in enumerate(lines_couplers):
col_x = x_left if i < per_col_cpl else x_right
cur_y = start_y - (i if i < per_col_cpl else i - per_col_cpl) * line_height
c.setFont(FONT_NAME_BOLD if is_header else FONT_NAME, font_size)
c.drawString(col_x, cur_y, text)
return start_y - per_col_cpl * line_height