Source code for bragi_quantum.experiments.utils.q1asm_dump

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


import json
from pathlib import Path

import plotly.graph_objects as go
from colorama import Fore, Style
from plotly.subplots import make_subplots
from qblox_scheduler.json_utils import SchedulerJSONEncoder
from qblox_scheduler.schedules.schedule import CompiledSchedule

from bragi_quantum.datalayer.managing.time_tracing import TimingTraceCategory
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.utils.logging.visuals import log_size_on_disk
from bragi_quantum.experiments.utils.cluster_snapshots import cluster_metadata_dir
from bragi_quantum.experiments.utils.timing import timed


[docs] def plot_module_waveforms( module_dir: Path, measurement_id: str, seq_waveforms: list[tuple[str, dict]], ) -> Path | None: """Plot waveforms for all sequencers of a module into a single figure. Create one subplot per sequencer that has waveforms (up to 6), arranged in a single column with a shared x axis. Each subplot title is the sequencer index; each line label (sequencer-prefixed, in the shared legend) is the waveform index field. The figure title is the measurement ID. Safe to call from a background thread. Return the path to the written ``waveforms.jpg``, or ``None`` when there is nothing to plot. """ if not seq_waveforms: return None n = len(seq_waveforms) fig = make_subplots( rows=n, cols=1, shared_xaxes=True, subplot_titles=[f"Sequencer{seq_suffix}" for seq_suffix, _ in seq_waveforms], vertical_spacing=max(0.02, 0.3 / n), ) for i, (seq_suffix, waveforms) in enumerate(seq_waveforms): row = i + 1 for wf_data in waveforms.values(): wf_index_str = str(wf_data.get("index", "?")) arr = wf_data.get("data", []) label = f"Seq{seq_suffix} — idx {wf_index_str} ({len(arr)} pts)" fig.add_trace( go.Scatter(y=arr, mode="lines+markers", marker={"size": 3}, name=label), row=row, col=1, ) fig.update_xaxes(title_text="Time [ns]", row=row, col=1) fig.update_layout( template="plotly_white", title=measurement_id, width=1000, height=max(300, 260 * n), legend={"font": {"size": 9}}, ) out_path = module_dir / "waveforms.jpg" fig.write_image(out_path, format="jpg") return out_path
[docs] def dump_q1asm_programs( data_path: Path | None, compiled_schedule: CompiledSchedule, measurement: tuple[int, int], ) -> None: """Dump compiled q1asm programs to data_path/q1asm_programs/<cluster>/<module>/<sequencer>.json. The folder hierarchy mirrors the hardware topology: data_path/q1asm_programs/<cluster_name>/<module_name>/<sequencer_name>.json For each sequencer the following files are written: * ``sequencerX.json`` — full serialised sequencer data * ``sequencerX.q1asm`` — extracted assembly program text * ``waveforms.jpg`` — one subplot per sequencer with waveforms (per module) """ if data_path is None: return q1asm_root = cluster_metadata_dir(data_path, measurement) json_files: list[Path] = [] q1asm_files: list[Path] = [] jpg_files: list[Path] = [] seen_waveform_keys: set[str] = set() total_waveform_floats: int = 0 _NON_MODULE_KEYS = frozenset({"settings", "acq_channels_data", "repetitions"}) with timed("q1asm dump took: ", timing_category=TimingTraceCategory.LOGGING): for ( cluster_name, cluster_program, ) in compiled_schedule.compiled_instructions.items(): cluster_dir = q1asm_root / cluster_name for key, module_program in cluster_program.items(): if key in _NON_MODULE_KEYS: continue # key is e.g. "cluster_b_module20" – strip the cluster prefix to get "module20" module_folder_name = key.removeprefix(f"{cluster_name}_") module_dir = cluster_dir / module_folder_name module_dir.mkdir(parents=True, exist_ok=True) seq_waveforms: list[tuple[str, dict]] = [] for seq_name, seq_data in module_program.get("sequencers", {}).items(): # seq_name is e.g. "seq0" – map to "sequencer0" seq_suffix = seq_name.removeprefix("seq") # Serialize once; reuse the plain dict for both files to avoid # calling methods on qblox custom objects. json_str = json.dumps(seq_data, cls=SchedulerJSONEncoder, indent=2) seq_dict = json.loads(json_str) json_path = module_dir / f"sequencer{seq_suffix}.json" json_path.write_text(json_str) json_files.append(json_path) program_text = (seq_dict.get("sequence") or {}).get("program") if program_text is not None: q1asm_path = module_dir / f"sequencer{seq_suffix}.q1asm" q1asm_path.write_text(program_text) q1asm_files.append(q1asm_path) waveforms = (seq_dict.get("sequence") or {}).get("waveforms", {}) if waveforms: seq_waveforms.append((seq_suffix, waveforms)) for wf_key, wf_data in waveforms.items(): if wf_key not in seen_waveform_keys: seen_waveform_keys.add(wf_key) total_waveform_floats += len(wf_data.get("data", [])) waveforms_path = plot_module_waveforms( module_dir, data_path.name, seq_waveforms ) if waveforms_path is not None: jpg_files.append(waveforms_path) all_files = json_files + q1asm_files + jpg_files if all_files: if json_files: log_size_on_disk(" .json written:", json_files) if q1asm_files: log_size_on_disk(" .q1asm written:", q1asm_files) if jpg_files: log_size_on_disk(" waveform plots written:", jpg_files) if seen_waveform_keys: waveform_kb = total_waveform_floats * 8 / 1024 logger.status( f" Unique waveforms uploaded: {len(seen_waveform_keys)}" f" ({Fore.RED}{Style.BRIGHT}{waveform_kb:.1f} kB{Style.RESET_ALL}" f" of float64 data)" ) log_size_on_disk("q1asm programs total:", all_files)