Source code for bragi_quantum.datalayer.visualization.figure_utils

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   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:
#
#   Michele Faucci Giannelli, faucci@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Theresa Fuchs, gerda@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


# This code is part of Tergite
#
# (C) Copyright Michele Faucci Giannelli 2025
# (C) Copyright Stefan Hill 2026
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
#
# Modified from tergite-autocalibration
# (https://github.com/tergite/tergite-autocalibration), file:
#   tergite_autocalibration/lib/base/utils/figure_utils.py


"""
Utility module for standardizing plot figures and metadata headers.
"""

import base64
from datetime import datetime
from functools import lru_cache
from pathlib import Path

# QC2 bragi_quantum.datalayer Imports
from bragi_quantum.datalayer.managing.session import ActiveSession


def _nice_node_name(name: str) -> str:
    """
    Convert `snake_case` or `mixed_case` into a human-readable name.

    Args:
        name (str): The raw node name.

    Returns:
        str: A nicely formatted sentence-case node name.
    """
    original_name = name

    # Handle snake_case
    name = name.replace("_", " ")

    # Normalize whitespace
    name = " ".join(name.split())

    if not name:
        return original_name

    # Convert to title case
    return name.title()


[docs] def node_metadata_text(node_name: str) -> str: """Return the branded one-line metadata header for a node's figures. ``{owner} {chip} | {Nice Node Name} | CL: {cooldown} | Acquisition: … | Analysis: … [| Internal]`` — read from the active session. Falls back to just the nice node name when no session/metadata is available (e.g. a standalone reanalysis). """ nice = _nice_node_name(node_name) try: session = ActiveSession.get() session_options = session.session_options acquisition_date = _infer_date_from_path(session.root_path) analysis_date = datetime.now().strftime("%d-%m-%Y") chip_name = getattr(session.device_config, "name", "Unknown Device") chip_owner = getattr(session.device_config, "owner", "Unknown Owner") # The device config's cooldown, unless the session options set one. cooldown = session_options.last_cooldown or session.device_config.last_cooldown text = ( f"{chip_owner} {chip_name} | {nice} | CL: {cooldown} | " f"Acquisition: {acquisition_date} | Analysis: {analysis_date}" ) if session_options.is_internal: text += " | Internal" return text except Exception: return nice
[docs] @lru_cache(maxsize=1) def qc2_logo_data_uri() -> str | None: """Return the QC2 logo as an SVG ``data:`` URI for embedding in plotly figures. Looks for ``docs/public/qc2_logo_dark.svg`` walking up from this file; returns ``None`` if not found (the logo is then simply omitted). """ for parent in Path(__file__).resolve().parents: candidate = parent / "docs" / "public" / "qc2_logo_dark.svg" if candidate.exists(): b64 = base64.b64encode(candidate.read_bytes()).decode("ascii") return f"data:image/svg+xml;base64,{b64}" return None
def _infer_date_from_path(path: Path) -> str: """ Return the date the run was started, as ``DD-MM-YYYY``, read from a folder in ``path`` named ``YYYYMMDD_HHMMSS[_name]`` (a run folder, as the orchestrator creates them) or ``YYYY-MM-DD``. ``"Unknown"`` if there is none. Args: path (Path): The root path to parse. Returns: str: A formatted date string. """ for part in path.parts: for candidate, fmt in ((part, "%Y-%m-%d"), (part[:15], "%Y%m%d_%H%M%S")): try: return datetime.strptime(candidate, fmt).strftime("%d-%m-%Y") except ValueError: pass return "Unknown"