# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""T-State Injection and a Heralded Repeat-Until-Success Loop: the code of the tutorial, as one script.

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

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

# %% The T gate is a phase change of the drive tone
import math

import numpy as np

import cudaq_pulse as pulse

system = pulse.quantum_system("transmon_surface17")
qubit = system.qudit("D5")

t_gate = qubit.get_calibration(pulse.gates.T)
print(t_gate)

# Prints:
#   VirtualZ(phase_rad=0.7853981633974483)


@pulse.kernel
def prepare_t(qudit):
    drive_line = get_drive_line(qudit)
    y90 = drive_line.get_calibration(pulse.gates.Y90)
    t_gate = drive_line.get_calibration(pulse.gates.T)

    # |0> to |+>, then |+> to |T>.
    drive(drive_line, y90)
    drive(drive_line, t_gate)


print(f"{'kind':8} {'start':>6} {'length':>6}")
for event in prepare_t.lower(qubit).schedule:
    start = event.start_cycles
    length = event.duration_cycles
    print(f"{event.kind:8} {start:>6} {length:>6}")

# Prints:
#   kind      start length
#   drive         0     80


# %% Reading the state against the tone
@pulse.kernel
def plus(qudit):
    drive_line = get_drive_line(qudit)
    y90 = drive_line.get_calibration(pulse.gates.Y90)
    drive(drive_line, y90)


ground = [1.0, 0.0, 0.0]

with_t = pulse.simulate(prepare_t, qubit, initial_state=ground)
without_t = pulse.simulate(plus, qubit, initial_state=ground)

same = np.allclose(with_t.density_matrix, without_t.density_matrix)
print("same state with and without T:", same)

# Prints:
#   same state with and without T: True


# %% Tomography
X_AXIS, Y_AXIS, Z_AXIS = 0, 1, 2


@pulse.kernel
def t_tomography(qudit, axis: int):
    drive_line = get_drive_line(qudit)
    readout_line = get_readout_line(qudit)
    y90 = drive_line.get_calibration(pulse.gates.Y90)
    t_gate = drive_line.get_calibration(pulse.gates.T)
    x90 = drive_line.get_calibration(pulse.gates.X90)
    measurement = readout_line.get_calibration(pulse.gates.READOUT)

    drive(drive_line, y90)
    drive(drive_line, t_gate)

    if axis == X_AXIS:
        drive(drive_line, y90.replace(amplitude=-y90.amplitude))
    elif axis == Y_AXIS:
        drive(drive_line, x90)

    sync(drive_line, readout_line)
    readout(readout_line, measurement)


# %% From readouts to fidelity
def last_readout(branch):
    """The level the last readout a shot took reported."""
    return [level for level in branch.levels if level >= 0][-1]


def expectation(result):
    """<Z> of the last readout, from its outcomes' probabilities."""
    excited = 0.0
    for branch in result.branches:
        if last_readout(branch) > 0:
            excited += branch.probability
    return 1 - 2 * excited


T_BLOCH = np.array([1.0, 1.0, 0.0]) / math.sqrt(2)


def fidelity(bloch):
    """<T|rho|T> for the Bloch vector, at most length 1."""
    length = max(1.0, float(np.linalg.norm(bloch)))
    unit = bloch / length
    return (1 + float(unit @ T_BLOCH)) / 2


def measured_fidelity(mode, **start):
    bloch = np.zeros(3)
    for axis in (X_AXIS, Y_AXIS, Z_AXIS):
        result = pulse.simulate(
            t_tomography,
            qubit,
            axis,
            readout=mode,
            **start,
        )
        bloch[axis] = expectation(result)
    return fidelity(bloch)


print("readout  infidelity")
for mode in ("ideal", "model"):
    measured = measured_fidelity(mode, initial_state=ground)
    print(f"{mode:7}  {1 - measured:.1e}")

# Prints:
#   readout  infidelity
#   ideal    2.4e-05
#   model    1.5e-03


# %% The thermal start
excited = system.thermal_populations[qubit.index]
print(f"excited at the start: {excited:.3f}")

print("readout  infidelity")
for mode in ("ideal", "model"):
    print(f"{mode:7}  {1 - measured_fidelity(mode):.1e}")

# Prints:
#   excited at the start: 0.027
#   readout  infidelity
#   ideal    2.6e-02
#   model    2.9e-02


# %% A herald on the controller
from cudaq_pulse.classical import Link

controller_link = Link(fixed_ns=4, feedback_ns=8, slots=2)
links = {"controller": controller_link}
control_system = pulse.ControlSystem(links=links)


@pulse.classical(
    min_latency_ns=20,
    nominal_latency_ns=30,
    max_latency_ns=40,
    link="controller",
)
def herald(outcome: pulse.Bits) -> bool:
    """Accept the shot when the qubit read 0."""
    return outcome[0] == 0


# %% Repeat until success
@pulse.kernel
def heralded_t(qudit, attempts: int, axis: int):
    drive_line = get_drive_line(qudit)
    readout_line = get_readout_line(qudit)
    flip = drive_line.get_calibration(pulse.gates.X)
    measurement = readout_line.get_calibration(pulse.gates.READOUT)

    outcome = readout(readout_line, measurement)
    request = herald.submit([outcome])
    accepted = request.result()
    sync(drive_line, readout_line)
    if accepted:
        # Success: prepare |T> and measure one axis. No more attempts.
        t_tomography(qudit, axis)
    else:
        # Back to |0>, and try again while attempts remain.
        drive(drive_line, flip)
        sync(drive_line, readout_line)
        if attempts > 1:
            heralded_t(qudit, attempts - 1, axis)


compiled = pulse.compile(
    heralded_t,
    quantum_system=system,
    control_system=control_system,
)


# %% Keep the shots that succeeded
def succeeded(branch):
    return branch.answers("herald")[-1]


def heralded_fidelity(attempts, mode="ideal"):
    bloch = np.zeros(3)
    for axis in (X_AXIS, Y_AXIS, Z_AXIS):
        program = compiled.lower(qubit, attempts, axis)
        result = pulse.simulate(program, readout=mode)
        kept = result.postselect(succeeded)
        bloch[axis] = expectation(kept)
    # The attempts a shot took: its herald answers, over all shots.
    taken = 0.0
    for branch in result.branches:
        taken += branch.probability * len(branch.answers("herald"))
    return fidelity(bloch), kept.acceptance, taken


print("readout  at most  succeeded  infidelity  attempts")
for mode, most in (("ideal", 3), ("model", 2)):
    for attempts in range(1, most + 1):
        heralded, share, taken = heralded_fidelity(attempts, mode)
        print(
            f"{mode:7}  {attempts:7}  {share:9.4f}  "
            f"{1 - heralded:10.1e}  {taken:8.3f}"
        )

# Prints:
#   readout  at most  succeeded  infidelity  attempts
#   ideal          1     0.9723     2.4e-05     1.000
#   ideal          2     0.9992     2.4e-05     1.028
#   ideal          3     0.9993     2.4e-05     1.029
#   model          1     0.9696     1.6e-03     1.000
#   model          2     0.9964     2.0e-03     1.030


# %% When the answers are due
program = compiled.lower(qubit, 1, Z_AXIS)

print("function  sent (ns)  due (ns)  slack")
for call in program.classical_report():
    sent_ns = call.submit_cycles / system.clock_ghz
    due_ns = call.due_cycles / system.clock_ghz
    slack = call.slack_cycles
    print(f"{call.function:8}  {sent_ns:9}  {due_ns:8}  {slack:5}")

# Prints:
#   function  sent (ns)  due (ns)  slack
#   herald        300.0     352.0      0


# %% A chain to inject into
from cudaq_pulse.quantum_systems import (
    Coupling,
    DispersiveReadout,
    DragPulse,
    PhysicalQudit,
    ReadoutPulse,
)


def transmon(index, frequency_hz, thermal_population=0.0):
    return PhysicalQudit(
        index=index,
        frequency_hz=frequency_hz,
        t1_us=100.0,
        t2_star_us=80.0,
        anharmonicity_hz=-2.2e8,
        thermal_population=thermal_population,
        readout=DispersiveReadout(error_1to0=0.01, error_0to1=0.005),
        calibrations={
            pulse.gates.X: DragPulse(duration_ns=40.0, sigma_ns=10.0),
            pulse.gates.READOUT: ReadoutPulse(duration_ns=300.0, amplitude=0.05),
        },
    )


# The middle qubit takes |T>. It starts as warm as D5; its neighbours, the
# rest of the code, start cold.
chain = pulse.quantum_system(
    name="t_chain",
    qudits={
        0: transmon(0, 5.15e9),
        1: transmon(1, 5.25e9, thermal_population=0.027),
        2: transmon(2, 5.35e9),
    },
    couplings=[
        Coupling((0, 1), strength_hz=4.0e6),
        Coupling((1, 2), strength_hz=4.0e6),
    ],
)
first, source, second = chain.qudits
# Two levels per transmon, in steps of 0.5 ns: 20 to a period of the
# 100 MHz between neighbours.
CHAIN = {"levels": 2, "dt_ns": 0.5}


T_AXIS = 3


# %% A CNOT from a cross-resonance pulse
@pulse.kernel
def controlled_turn(control, target, amplitude: float):
    """An echoed cross-resonance pulse: the control's line is driven at the
    target's tone, and the target turns one way with the control in |0> and
    the other way with it in |1>. The pi pulse between the two halves, with
    the second half reversed, cancels what the drive does to the control
    itself."""
    control_drive = get_drive_line(control)
    target_drive = get_drive_line(target)
    flip = control_drive.get_calibration(pulse.gates.X)
    cross = gaussian_square(180 * pulse.ns, amplitude, 10 * pulse.ns, 100 * pulse.ns)
    back = gaussian_square(180 * pulse.ns, -amplitude, 10 * pulse.ns, 100 * pulse.ns)

    sync(control_drive, target_drive)
    drive(control_drive, cross, tone=target_drive.tone)
    drive(control_drive, flip)
    drive(control_drive, back, tone=target_drive.tone)
    drive(control_drive, flip)
    sync(control_drive, target_drive)


@pulse.kernel
def cnot(control, target, amplitude: float, axis_rad: float):
    """The controlled turn, a quarter turn each way, then a quarter turn of
    the target about the same axis: none in all, or a half turn."""
    controlled_turn(control, target, amplitude)
    target_drive = get_drive_line(target)
    # With its tone's phase moved by -axis_rad, a pulse turns about the axis
    # at axis_rad.
    shift_phase(target_drive.tone, -axis_rad)
    drive(target_drive, target_drive.get_calibration(pulse.gates.X90))
    shift_phase(target_drive.tone, axis_rad)


@pulse.kernel
def turn_check(control, target, amplitude: float):
    controlled_turn(control, target, amplitude)


@pulse.kernel
def cnot_check(control, target, excite: int, amplitude: float, axis_rad: float):
    control_drive = get_drive_line(control)
    if excite:
        drive(control_drive, control_drive.get_calibration(pulse.gates.X))
    cnot(control, target, amplitude, axis_rad)


def target_excited(kernel, target, *args):
    pair = np.zeros(4)
    pair[0] = 1.0
    result = pulse.simulate(kernel, source, target, *args, initial_state=pair, **CHAIN)
    return float(result.level_populations(target)[1])


def calibrate_cnot(target):
    """The two numbers of the CNOT from ``source`` to *target*, each from
    simulated runs, as a calibration measures them."""
    # The amplitude of a quarter turn: the target ends half excited.
    amplitude = 0.15
    for _ in range(2):
        excited = target_excited(turn_check, target, amplitude)
        amplitude *= (math.pi / 2) / (2 * math.asin(math.sqrt(excited)))
    # The axis of the turn: the phase of the target's own quarter turn that
    # brings it back to |0> when the control is in |0>.
    along = target_excited(cnot_check, target, 0, amplitude, 0.0)
    across = target_excited(cnot_check, target, 0, amplitude, math.pi / 2)
    axis_rad = math.atan2(across - 0.5, along - 0.5) + math.pi
    return amplitude, axis_rad


cnots = {}
print("target  amplitude  axis (deg)  flipped: control 0, control 1")
for name, target in (("first", first), ("second", second)):
    cnots[name] = calibrate_cnot(target)
    amplitude, axis_rad = cnots[name]
    flipped = []
    for excite in (0, 1):
        share = target_excited(cnot_check, target, excite, *cnots[name])
        flipped.append(share)
    print(
        f"{name:6}  {amplitude:9.4f}  {math.degrees(axis_rad) % 360:10.1f}  "
        f"{flipped[0]:18.3f}  {flipped[1]:9.3f}"
    )

# Prints:
#   target  amplitude  axis (deg)  flipped: control 0, control 1
#   first      0.1624         0.1               0.002      0.997
#   second     0.1624       179.9               0.002      0.997


# %% Inject the state into the code
@pulse.kernel
def encode_and_measure(
    source,
    first,
    second,
    first_amplitude: float,
    first_axis_rad: float,
    second_amplitude: float,
    second_axis_rad: float,
    axis: int,
):
    source_drive = get_drive_line(source)
    drives = [get_drive_line(first), source_drive, get_drive_line(second)]
    readouts = [get_readout_line(first), get_readout_line(source), get_readout_line(second)]

    # The state to inject.
    drive(source_drive, source_drive.get_calibration(pulse.gates.Y90))
    drive(source_drive, source_drive.get_calibration(pulse.gates.T))

    # Copy the source's 0 or 1 onto each neighbour: a|000> + b|111>.
    cnot(source, first, first_amplitude, first_axis_rad)
    cnot(source, second, second_amplitude, second_axis_rad)

    # Two settings. Z reads each qubit as it is. T takes the source's tone
    # back by the T gate's pi / 4 and reads X on all three, X_L: the axis
    # the injected state points along.
    sync(drives[0], drives[1], drives[2])
    if axis == T_AXIS:
        shift_phase(source_drive.tone, -math.pi / 4)
        for line in drives:
            y90 = line.get_calibration(pulse.gates.Y90)
            drive(line, y90.replace(amplitude=-y90.amplitude))
    sync(drives[0], drives[1], drives[2], readouts[0], readouts[1], readouts[2])
    for line in readouts:
        readout(line, line.get_calibration(pulse.gates.READOUT))


def code_readouts(branch):
    """The last three readouts a shot took: first, source, second."""
    return [min(level, 1) for level in branch.levels if level >= 0][-3:]


def parity(result):
    """The mean of +1 or -1 by the parity of the three readouts: what a
    product of Paulis on the three qubits reads."""
    return sum((-1) ** sum(code_readouts(b)) * b.probability for b in result.branches)


def in_code_space(result):
    """The share of shots whose three readouts agree: 000 or 111."""
    return sum(b.probability for b in result.branches if len(set(code_readouts(b))) == 1)


def encoded_fidelity(z_setting, t_setting):
    """The fidelity with (|000> + e^{i pi/4}|111>) / sqrt(2) from the two
    settings: the populations of 000 and 111, which the Z setting reads,
    and twice the coherence between them, which the T setting's parity
    reads, halved."""
    return (in_code_space(z_setting) + parity(t_setting)) / 2


@pulse.kernel
def injected_t(
    source,
    first,
    second,
    attempts: int,
    first_amplitude: float,
    first_axis_rad: float,
    second_amplitude: float,
    second_axis_rad: float,
    axis: int,
):
    drive_line = get_drive_line(source)
    readout_line = get_readout_line(source)

    outcome = readout(readout_line, readout_line.get_calibration(pulse.gates.READOUT))
    request = herald.submit([outcome])
    accepted = request.result()
    sync(drive_line, readout_line)
    if accepted:
        encode_and_measure(
            source,
            first,
            second,
            first_amplitude,
            first_axis_rad,
            second_amplitude,
            second_axis_rad,
            axis,
        )
    else:
        drive(drive_line, drive_line.get_calibration(pulse.gates.X))
        sync(drive_line, readout_line)
        if attempts > 1:
            injected_t(
                source,
                first,
                second,
                attempts - 1,
                first_amplitude,
                first_axis_rad,
                second_amplitude,
                second_axis_rad,
                axis,
            )


compiled_injection = pulse.compile(
    injected_t,
    quantum_system=chain,
    control_system=control_system,
)
first_amplitude, first_axis_rad = cnots["first"]
second_amplitude, second_axis_rad = cnots["second"]


def injected(axis, mode="ideal"):
    program = compiled_injection.lower(
        source,
        first,
        second,
        2,
        first_amplitude,
        first_axis_rad,
        second_amplitude,
        second_axis_rad,
        axis,
    )
    result = pulse.simulate(program, readout=mode, **CHAIN)
    return result.postselect(succeeded)


z_setting = injected(Z_AXIS)
t_setting = injected(T_AXIS)
fidelity_ideal = encoded_fidelity(z_setting, t_setting)
print(f"shots that succeeded: {z_setting.acceptance:.4f}")
print(f"in the code space:    {in_code_space(z_setting):.3f}")
print(f"parity along T:       {parity(t_setting):.3f}")
print(f"fidelity with |T_L>:  {fidelity_ideal:.3f}")

# Prints:
#   shots that succeeded: 0.9999
#   in the code space:    0.986
#   parity along T:       0.966
#   fidelity with |T_L>:  0.976


z_model = injected(Z_AXIS, "model")
t_model = injected(T_AXIS, "model")
fidelity_model = encoded_fidelity(z_model, t_model)
print(f"shots that succeeded: {z_model.acceptance:.4f}")
print(f"in the code space:    {in_code_space(z_model):.3f}")
print(f"parity along T:       {parity(t_model):.3f}")
print(f"fidelity with |T_L>:  {fidelity_model:.3f}")

# Prints:
#   shots that succeeded: 0.9950
#   in the code space:    0.964
#   parity along T:       0.922
#   fidelity with |T_L>:  0.943
