# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Real-Time Decoding with a Deadline: the code of the tutorial, as one script.

https://nvidia.github.io/cudaq-pulse/tutorials/realtime_decoding.html

Generated from docs/tutorials/realtime_decoding.rst by tools/tutorial-scripts.py: edit
the page, not this file.
"""

import importlib.util


# Blocks under ``if GPU:`` need the GPU runtime (Linux, an NVIDIA GPU and
# ``pip install "cudaq-pulse[cu12]"`` or ``[cu13]``).
def _gpu_runtime_loads() -> bool:
    from cudaq_pulse.runtime import require_gpu_runtime

    try:
        require_gpu_runtime()
    except Exception:
        return False
    return True


GPU = _gpu_runtime_loads()


# Blocks under ``if CUDAQ_QEC:`` need CUDA-Q QEC (``pip install cudaq-qec``)
# and the GPU runtime.
CUDAQ_QEC = GPU and importlib.util.find_spec("cudaq_qec") is not None


# %% The code and its syndrome
import cudaq_pulse as pulse


def lookup(syndrome: pulse.Bits) -> pulse.Bits:
    s0, s1 = syndrome[0], syndrome[1]
    # One correction bit per data qubit.
    return [s0 & (1 - s1), s0 & s1, s1 & (1 - s0)]


decode = pulse.classical(
    lookup,
    link="gpu",
    nominal_latency_ns=62_000,
    max_latency_ns=75_000,
)


# %% Five transmons in a row
import itertools

from cudaq_pulse.quantum_systems import (
    Coupling,
    DragPulse,
    PhysicalQudit,
)

# Qudit indices along the chain.
CHAIN = [0, 3, 1, 4, 2]
x_pulse = {pulse.gates.X: DragPulse(duration_ns=40.0, sigma_ns=10.0)}

qudits = {}
for position, index in enumerate(CHAIN):
    qudits[index] = PhysicalQudit(
        index=index,
        frequency_hz=5.0e9 + position * 50e6,
        t1_us=60.0,
        t2_star_us=40.0,
        anharmonicity_hz=-330e6,
        calibrations=x_pulse,
    )

couplings = []
for pair in itertools.pairwise(CHAIN):
    couplings.append(Coupling(pair, strength_hz=4.0e6))

system = pulse.quantum_system(
    name="repetition_chain",
    qudits=qudits,
    couplings=couplings,
)
data = system.qudits[0:3]
ancillas = system.qudits[3:5]


# %% Extract the syndrome with pulses
@pulse.kernel
def extract(data, ancillas):
    cross = gaussian_square(
        190 * pulse.ns,
        0.12,
        10 * pulse.ns,
        150 * pulse.ns,
    )
    for step in range(2):
        # Step 0: data 0 turns ancilla 0, data 1 turns ancilla 1.
        # Step 1: data 1 turns ancilla 0, data 2 turns ancilla 1.
        for check in range(2):
            line = get_drive_line(data[check + step])
            ancilla_tone = get_drive_line(ancillas[check]).tone
            drive(line, cross, tone=ancilla_tone)
        sync(
            get_drive_line(data[0]),
            get_drive_line(data[1]),
            get_drive_line(data[2]),
        )


# %% One round, with a deadline
NO_ERROR = -1


@pulse.kernel
def qec_round(data, ancillas, error: int, deadline_ns: int):
    measurement = square(400 * pulse.ns, 0.05)

    # The error: a π pulse on one data qubit, or none.
    if error != NO_ERROR:
        line = get_drive_line(data[error])
        drive(line, line.get_calibration(pulse.gates.X))

    extract(data, ancillas)
    sync(
        get_drive_line(data[0]),
        get_readout_line(ancillas[0]),
        get_readout_line(ancillas[1]),
    )
    s0 = readout(get_readout_line(ancillas[0]), measurement)
    s1 = readout(get_readout_line(ancillas[1]), measurement)

    request = decode.submit([s0, s1])
    in_time, fix = request.result(timeout=deadline_ns * pulse.ns)

    # The fallback, computed on the controller.
    table = [s0 and not s1, s0 and s1, s1 and not s0]
    for i in range(3):
        flip = fix[i] if in_time else table[i]
        if flip:
            line = get_drive_line(data[i])
            drive(line, line.get_calibration(pulse.gates.X))


# %% Check the timing
gpu_link = pulse.Link(feedback_ns=50)
control_system = pulse.ControlSystem(links={"gpu": gpu_link})
compiled = pulse.compile(
    qec_round,
    quantum_system=system,
    control_system=control_system,
)


scheduled = compiled.lower(
    data,
    ancillas,
    NO_ERROR,
    deadline_ns=80_000,
)
call = scheduled.classical_report()[0]
sent_ns = call.submit_cycles / system.clock_ghz
send_ns = call.submit_duration_cycles / system.clock_ghz
due_ns = call.due_cycles / system.clock_ghz
print(f"syndrome sent at {sent_ns} ns, for {send_ns} ns")
print(f"answer due at {due_ns} ns")

# Prints:
#   syndrome sent at 780.0 ns, for 0.5 ns
#   answer due at 80830.5 ns


# %% Simulate both arms
def simulate_round(compiled, error, deadline_ns):
    program = compiled.lower(
        data,
        ancillas,
        error,
        deadline_ns=deadline_ns,
    )
    return pulse.simulate(
        program,
        levels=2,
        latency_branching=True,
        dt_ns=1.0,
    )


def syndrome_read(result):
    shares = {}
    for branch in result.branches:
        outcomes = tuple(branch.levels)
        shares[outcomes] = shares.get(outcomes, 0.0) + branch.probability
    likeliest = max(shares, key=lambda outcomes: shares[outcomes])
    return likeliest, shares[likeliest]


def decoder_used(result):
    used = 0.0
    for branch in result.branches:
        if branch.calls and branch.calls[-1].in_time:
            used += branch.probability
    return used


def data_restored(result):
    restored = 0.0
    for index in range(32):
        # The data qubits are the three lowest bits.
        if index & 0b111 == 0:
            restored += result.density_matrix[index, index].real
    return restored


ERRORS = (NO_ERROR, 0, 1, 2)

results = {}
print("flipped  syndrome  share of shots  data back in 000")
for error in ERRORS:
    result = simulate_round(compiled, error, deadline_ns=1_000)
    results[error] = result
    (s0, s1), share = syndrome_read(result)
    flipped = "none" if error == NO_ERROR else f"data {error}"
    back = data_restored(result)
    print(f"{flipped:7}  ({s0}, {s1})    {share:.3f}           {back:.3f}")

# Prints:
#   flipped  syndrome  share of shots  data back in 000
#   none     (0, 0)    0.995           0.995
#   data 0   (1, 0)    0.980           0.927
#   data 1   (1, 1)    0.960           0.920
#   data 2   (0, 1)    0.978           0.927


def summary(results):
    results = list(results)
    used = sum(decoder_used(r) for r in results) / len(results)
    restored = sum(data_restored(r) for r in results) / len(results)
    return round(float(used), 3), round(float(restored), 3)


used, restored = summary(results.values())
print(f"decoder's answer used: {used}")
print(f"data back in 000:      {restored}")

# Prints:
#   decoder's answer used: 0.0
#   data back in 000:      0.942


# %% Give the decoder a budget that fits
decode = pulse.classical(lookup, link="gpu", max_latency_ns=500)
fast = pulse.compile(
    qec_round,
    quantum_system=system,
    control_system=control_system,
)

in_time = simulate_round(fast, 1, deadline_ns=1_000)
used, restored = summary([in_time])
print(f"decoder's answer used: {used}")
print(f"data back in 000:      {restored}")

# Prints:
#   decoder's answer used: 1.0
#   data back in 000:      0.92


# %% With a CUDA-Q QEC decoder
if CUDAQ_QEC:
    import cudaq_qec


if CUDAQ_QEC:
    # Decoder 0: BP+OSD for a distance-3 repetition code.
    cudaq_qec.configure_decoders_from_str("""
    decoders:
      - id: 0
        type: nv-qldpc-decoder
        block_size: 3
        syndrome_size: 2
        H_sparse: [0, 1, -1, 1, 2, -1]
        O_sparse: [0, -1, 1, -1, 2, -1]
        D_sparse: [0, -1, 1, -1]
        decoder_custom_args:
          error_rate_vec: [0.1, 0.1, 0.1]
          use_sparsity: true
          max_iterations: 50
          use_osd: true
          osd_method: 3
          osd_order: 7
    """)


if CUDAQ_QEC:
    # Its real-time calls, sent to the decoding server over the GPU link.
    enqueue_syndromes = pulse.classical(
        cudaq_qec.qec.enqueue_syndromes,
        link="gpu",
    )
    get_corrections = pulse.classical(
        cudaq_qec.qec.get_corrections,
        link="gpu",
        nominal_latency_ns=62_000,
        max_latency_ns=75_000,
    )
    reset_decoder = pulse.classical(
        cudaq_qec.qec.reset_decoder,
        link="gpu",
    )


if CUDAQ_QEC:
    @pulse.kernel
    def qec_round(data, ancillas, error: int, deadline_ns: int):
        measurement = square(400 * pulse.ns, 0.05)

        # The error: a pi pulse on one data qubit, or none.
        if error != NO_ERROR:
            line = get_drive_line(data[error])
            drive(line, line.get_calibration(pulse.gates.X))

        # Syndrome extraction, then the ancillas' readouts.
        extract(data, ancillas)
        sync(
            get_drive_line(data[0]),
            get_readout_line(ancillas[0]),
            get_readout_line(ancillas[1]),
        )
        s0 = readout(get_readout_line(ancillas[0]), measurement)
        s1 = readout(get_readout_line(ancillas[1]), measurement)

        # Decoder 0, round 0.
        enqueue_syndromes.submit(0, [s0, s1], 0)
        request = get_corrections.submit(0, 3, False)
        in_time, fix = request.result(timeout=deadline_ns * pulse.ns)

        # The decoder's answer, or the local table if it is late.
        table = [s0 and not s1, s0 and s1, s1 and not s0]
        for i in range(3):
            flip = fix[i] if in_time else table[i]
            if flip:
                line = get_drive_line(data[i])
                drive(line, line.get_calibration(pulse.gates.X))


if CUDAQ_QEC:
    decoded = pulse.compile(
        qec_round,
        quantum_system=system,
        control_system=control_system,
    )
    late = [simulate_round(decoded, e, deadline_ns=1_000) for e in ERRORS]
    used, restored = summary(late)
    print(f"decoder's answer used: {used}")
    print(f"data back in 000:      {restored}")

# Prints:
#   decoder's answer used: 0.0
#   data back in 000:      0.943


if CUDAQ_QEC:
    get_corrections = pulse.classical(
        cudaq_qec.qec.get_corrections,
        link="gpu",
        max_latency_ns=500,
    )
    decoded_fast = pulse.compile(
        qec_round,
        quantum_system=system,
        control_system=control_system,
    )
    in_time = []
    for error in ERRORS:
        result = simulate_round(decoded_fast, error, deadline_ns=1_000)
        in_time.append(result)
    used, restored = summary(in_time)
    print(f"decoder's answer used: {used}")
    print(f"data back in 000:      {restored}")
    cudaq_qec.finalize_decoders()

# Prints:
#   decoder's answer used: 1.0
#   data back in 000:      0.943
