# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""From a Kernel to Your Control Electronics: the code of the tutorial, as one script.

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

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

# %% Describe your control system
import cudaq_pulse as pulse
from cudaq_pulse.quantum_systems import PhysicalQudit

box = pulse.Controller(
    clock_ghz=1.0,
    cycles_per_timestep=4,
    sample_rate_ghz=1.0,
    min_pulse_cycles=16,
    waveform_memory_samples=16384,
    max_frequencies_per_line=4,
    max_amplitude=1.0,
    feedback_latency_cycles=200,
)


control_system = pulse.ControlSystem(controllers=[box])

qudit = PhysicalQudit(
    index=0,
    frequency_hz=5.0e9,
    t1_us=50.0,
    t2_star_us=30.0,
    anharmonicity_hz=-2.0e8,
)
system = pulse.quantum_system(
    name="one-qubit",
    qudits={0: qudit},
    clock_ghz=1.0,
    control_system=control_system,
)
print(len(control_system.controllers), "controller")
print("clock:", system.clock_ghz, "GHz")

# Prints:
#   1 controller
#   clock: 1.0 GHz


# %% Compile a kernel for it
@pulse.kernel
def active_reset(
    qudit,
    flip_duration,
    flip_sigma,
    flip_amplitude: float,
    readout_duration,
):
    drive_line = get_drive_line(qudit)
    readout_line = get_readout_line(qudit)
    flip = gaussian(flip_duration, flip_amplitude, flip_sigma)

    drive(drive_line, flip)
    sync(drive_line, readout_line)
    outcome = readout(readout_line, square(readout_duration, 0.05))

    sync(drive_line, readout_line)
    if outcome:
        drive(drive_line, flip)


scheduled = active_reset.lower(
    system.qudits[0],
    flip_duration=40 * pulse.ns,
    flip_sigma=10 * pulse.ns,
    flip_amplitude=0.5,
    readout_duration=200 * pulse.ns,
)
print("length:", scheduled.duration)
print(f"{'kind':8} {'line':>4} {'start':>6} {'end':>6}")
for event in scheduled.schedule:
    print(f"{event.kind:8} {event.line:>4} {event.start:>6} {event.end:>6}")

# Prints:
#   length: 480 ns
#   kind     line  start    end
#   drive       0      0     40
#   readout     1     40    240
#   drive       0    440    480


# %% What the compiler refuses
try:
    active_reset.lower(
        system.qudits[0],
        flip_duration=42 * pulse.ns,
        flip_sigma=10 * pulse.ns,
        flip_amplitude=0.5,
        readout_duration=200 * pulse.ns,
    )
except pulse.CompilationError as error:
    print(type(error).__name__)
    print(error)

# Prints:
#   ControllerLimitError
#   the program exceeds the controller's limits:
#     line d0 moves in timesteps of 4 cycles; 42 cycles isn't a whole number of timesteps (the drive at cycle 0; pulse.round_duration(line, 42) gives 44, or 40 rounding down)
#     line d0 moves in timesteps of 4 cycles; 42 cycles isn't a whole number of timesteps (the drive at cycle 444; pulse.round_duration(line, 42) gives 44, or 40 rounding down)


from cudaq_pulse import controller

slower = pulse.Controller(
    clock_ghz=1.0,
    cycles_per_timestep=4,
    min_pulse_cycles=64,
    feedback_latency_cycles=400,
)
for violation in controller.check(scheduled, slower):
    print("-", violation)

# Prints:
#   - line 0 (drive of qudit 0): the drive at 0 lasts 40 cycles; the controller plays none shorter than 64 (Controller.min_pulse_cycles)
#   - line 0 (drive of qudit 0): the drive at 440 lasts 40 cycles; the controller plays none shorter than 64 (Controller.min_pulse_cycles)
#   - line 0: the drive at 440 depends on the readout ending at 240; the controller needs 400 cycles of feedback latency (start at 640 or later; schedule with rcp and readout_latency_cycles >= feedback_latency_cycles)


# %% Read the scheduled program
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any

import cudaq_pulse as pulse
from cudaq_pulse import backends
from cudaq_pulse.backends import IncompatibleBackendError
from cudaq_pulse.controller import FORMAT, evaluate_expression, sample_waveform, shape_key


@dataclass(frozen=True)
class Step:
    """One timed operation, as the sequencer needs it."""

    index: int
    kind: str  # "drive", "readout", "wait", "submit" or "answer"
    channel: int  # its line; for a submit or an answer, its link
    start: int  # in clock cycles
    length: int
    segment: int = 0
    condition: tuple[int, bool] | None = None  # (the readout it tests, the arm)
    waveform: Mapping[str, Any] = field(default_factory=dict)  # of a drive or a readout
    amplitude: complex = 0j
    frequency_hz: float = 0.0
    phase_rad: float = 0.0
    max_length: int = 0  # of a wait whose length a register sets
    answer: int = -1  # the answer that sets it; -1 for any other step
    length_expression: Any = None  # of that length, in clock cycles
    function: str = ""
    measurements: tuple[int, ...] = ()


@dataclass(frozen=True)
class Program:
    """A scheduled program: its channels, links and steps in time order."""

    clock_ghz: float
    channels: Mapping[int, str]
    links: Mapping[int, str]
    steps: Sequence[Step]
    samples_per_cycle: float = 1.0  # of the converters, per clock cycle


def read_program(exported: Mapping[str, Any]) -> Program:
    """The records of an exported program. Nothing else reads the export."""
    if exported["format"] != FORMAT:
        raise IncompatibleBackendError(f"cannot read {exported['format']}")
    channels = {line["line"]: f"{line['role']}{line['qudit']}" for line in exported["lines"]}
    links = {int(key): link["name"] for key, link in exported["links"].items()}
    steps = []
    for event in exported["events"]:
        kind = event["kind"]
        if kind == "sync":
            continue  # the scheduler has placed what it ties together
        if kind not in ("drive", "readout", "wait", "submit", "answer"):
            raise IncompatibleBackendError(f"no instruction for a {kind}")
        step: dict[str, Any] = {}
        conditions = event["conditions"]
        if conditions:
            if len(conditions) > 1 or conditions[0]["test"] != "is_set":
                raise IncompatibleBackendError(
                    f"event {event['index']} tests more than one measurement register"
                )
            step["condition"] = (conditions[0]["readouts"][0], conditions[0]["arm"])
        if kind in ("drive", "readout"):
            if event["frequency_hz"] is None or "tone" in event:
                raise IncompatibleBackendError(f"event {event['index']} changes a tone at run time")
            amplitude = event["amplitude"]
            step.update(
                waveform=event["waveform"],
                amplitude=complex(amplitude["re"], amplitude["im"]),
                frequency_hz=event["frequency_hz"],
                phase_rad=event["phase_rad"],
            )
        elif kind == "wait" and "length" in event:
            answers = _answers(event["length"])
            if len(answers) != 1 or event["max_cycles"] is None:
                raise IncompatibleBackendError(
                    f"the wait {event['index']} needs one answer and an upper bound"
                )
            step.update(
                max_length=event["max_cycles"],
                answer=answers.pop(),
                length_expression=event["length"],
            )
        elif kind in ("submit", "answer"):
            step.update(
                function=event["function"],
                measurements=tuple(event.get("measurements", ())),
            )
        steps.append(
            Step(
                index=event["index"],
                kind=kind,
                channel=event["link"] if kind in ("submit", "answer") else event["line"],
                start=event["start_cycles"],
                length=event["duration_cycles"],
                segment=event["segment"],
                **step,
            )
        )
    steps.sort(key=lambda step: (step.start, step.index))
    # The converters' rate is the controller's, else one sample per cycle.
    rate = (exported.get("limits") or {}).get("sample_rate_ghz")
    samples_per_cycle = rate / exported["clock_ghz"] if rate else 1.0
    return Program(exported["clock_ghz"], channels, links, steps, samples_per_cycle)


def _answers(expression: Any) -> set[int]:
    """The answers a run-time expression reads."""
    if not isinstance(expression, Mapping):
        return set()
    found = {expression["answer"]} if "answer" in expression else set()
    for part in expression.get("of", ()):
        found |= _answers(part)
    return found


program = read_program(scheduled.export_to_controller())
print(dict(program.channels))
for step in program.steps:
    shape = step.waveform["shape"]
    print(step.kind, step.channel, step.start, step.length, shape, step.condition)

# Prints:
#   {0: 'drive0', 1: 'readout0'}
#   drive 0 0 40 gaussian None
#   readout 1 40 200 square None
#   drive 0 440 40 gaussian (2, True)


# %% Lower it to instructions
@dataclass
class Listing:
    """What the sequencers execute: a waveform table and, per channel, its
    instructions.

    On a line's channel every time is in timesteps of the controller; on a
    link's channel, in clock cycles. An instruction behind ``if m<k>:``
    lasts its length whether or not it plays: when the test fails the
    channel idles for that long. ``idle`` fills the time between two steps;
    ``wait`` is a wait the program asked for. A register ``m<k>`` holds the outcome
    of the acquisition that wrote it; a register ``r<k>`` holds an answer as
    the function returned it.
    """

    timestep: int
    waveforms: list[Any] = field(default_factory=list)
    channels: dict[str, list[str]] = field(default_factory=dict)
    lines: dict[str, int] = field(default_factory=dict)  # each channel's line or link

    def text(self) -> str:
        lines = [f"timestep: {self.timestep} cycles"]
        for number, samples in enumerate(self.waveforms):
            lines.append(f"w{number}: {len(samples)} samples")
        for name, instructions in self.channels.items():
            unit = "clock cycles" if name.startswith("link:") else "timesteps"
            lines.append(f"{name} (times in {unit}):")
            lines.extend(f"    {instruction}" for instruction in instructions)
        return "\n".join(lines)


def lower(program: Program, timestep: int = 1) -> Listing:
    """The instruction list of each channel of *program*."""
    listing = Listing(timestep)
    table: dict[Any, int] = {}
    names = {**program.channels}
    names.update({-1 - link: f"link:{name}" for link, name in program.links.items()})
    cursor = dict.fromkeys(names, 0)
    last: dict[int, Step] = {}
    frequency: dict[int, float] = {}
    for channel, name in names.items():
        listing.channels[name] = []
        listing.lines[name] = channel if channel >= 0 else -1 - channel

    for step in program.steps:
        channel = -1 - step.channel if step.kind in ("submit", "answer") else step.channel
        out = listing.channels[names[channel]]
        unit = 1 if channel < 0 else timestep
        if step.start % unit or step.length % unit:
            raise IncompatibleBackendError(f"step {step.index} is off the timestep")
        ticks = step.length // unit
        guard = ""
        if step.condition is not None:
            readout, arm = step.condition
            guard = f"if m{readout}: " if arm else f"if not m{readout}: "

        if step.kind in ("drive", "readout"):
            # One entry per shape: pulses that differ in amplitude share it.
            key = shape_key(step.waveform)
            if key not in table:
                table[key] = len(listing.waveforms)
                listing.waveforms.append(
                    sample_waveform(step.waveform, step.length, program.samples_per_cycle)
                    / step.amplitude
                )
            wave = f"w{table[key]} gain={abs(step.amplitude):g} phase={step.phase_rad:g}"
            if step.kind == "drive":
                instruction = f"drive {wave} for {ticks}"
            else:
                instruction = f"acquire {wave} for {ticks} into m{step.index}"
        elif step.kind == "wait" and step.answer >= 0:
            # The sequencer waits the register's value, so the length the
            # program computes must be that value in clock cycles and no more.
            low, high = step.length, step.max_length
            for value in (low, high):
                given = evaluate_expression(
                    step.length_expression, {}, {step.answer: [float(value)]}
                )
                if given != value:
                    raise IncompatibleBackendError(
                        f"the wait {step.index} is not its answer in clock cycles"
                    )
            instruction = f"wait_reg r{step.answer}/{unit} min={low // unit} max={high // unit}"
        elif step.kind == "wait":
            instruction = f"wait {ticks}"
        elif step.kind == "submit":
            sent = ", ".join(f"m{readout}" for readout in step.measurements)
            instruction = f"send {step.function}({sent}) for {ticks}"
        else:
            instruction = f"recv r{step.index}"

        before = last.get(channel)
        if step.start < cursor[channel]:
            # Two steps at once on one channel: the two arms of one branch
            # become one instruction; anything else this sequencer cannot do.
            if before is None or not _two_arms(before, step):
                raise IncompatibleBackendError(
                    f"step {step.index} starts at cycle {step.start} while its channel is busy "
                    f"until cycle {cursor[channel]}; a channel runs one instruction at a time"
                )
            # The second arm may start later than the first: it idles first.
            lead = (step.start - before.start) // unit
            out[-1] = f"{out[-1]} else: " + (f"idle {lead}; " if lead else "") + instruction
            cursor[channel] = max(cursor[channel], step.start + step.length)
            continue
        if step.start > cursor[channel]:
            out.append(f"idle {(step.start - cursor[channel]) // unit}")
        if step.kind in ("drive", "readout") and frequency.get(channel) != step.frequency_hz:
            frequency[channel] = step.frequency_hz
            out.append(f"set_freq {step.frequency_hz:.0f}")
        out.append(guard + instruction)
        cursor[channel] = step.start + step.length
        last[channel] = step
    return listing


def _two_arms(first: Step, second: Step) -> bool:
    """Whether the two steps are the two arms of one branch on a readout."""
    return (
        first.condition is not None
        and second.condition is not None
        and first.condition == (second.condition[0], not second.condition[1])
        and first.frequency_hz == second.frequency_hz
    )


listing = lower(program, timestep=box.cycles_per_timestep)
print(listing.text())

# Prints:
#   timestep: 4 cycles
#   w0: 40 samples
#   w1: 200 samples
#   drive0 (times in timesteps):
#       set_freq 5000000000
#       drive w0 gain=0.5 phase=0 for 10
#       idle 100
#       if m2: drive w0 gain=0.5 phase=0 for 10
#   readout0 (times in timesteps):
#       idle 10
#       set_freq 5000000000
#       acquire w1 gain=0.05 phase=0 for 50 into m2


# %% A wait of run-time length
@pulse.classical(link="controller", max_latency_ns=100)
def pick_wait(outcome: pulse.Bits) -> float:
    return 400.0 if outcome[0] else 80.0


@pulse.kernel
def measure_then_wait(qudit, flip_duration, flip_sigma, readout_duration):
    drive_line = get_drive_line(qudit)
    readout_line = get_readout_line(qudit)

    outcome = readout(readout_line, square(readout_duration, 0.05))
    request = pick_wait.submit([outcome])
    wait_ns = request.result()

    sync(drive_line, readout_line)
    wait(
        drive_line,
        wait_ns * pulse.ns,
        bounds=(80 * pulse.ns, 400 * pulse.ns),
    )
    drive(drive_line, gaussian(flip_duration, 0.5, flip_sigma))


links = {"controller": pulse.Link(fixed_ns=4, feedback_ns=8)}
with_link = pulse.quantum_system(
    name="one-qubit",
    qudits={0: qudit},
    clock_ghz=1.0,
    control_system=pulse.ControlSystem(controllers=[box], links=links),
)
waiting = measure_then_wait.lower(
    with_link.qudits[0],
    flip_duration=40 * pulse.ns,
    flip_sigma=10 * pulse.ns,
    readout_duration=200 * pulse.ns,
)
for segment in waiting.segments():
    print(
        segment.index,
        segment.opened_by,
        "starts at",
        segment.start_cycles,
        "and up to",
        segment.max_shift_cycles,
        "later",
    )

# Prints:
#   0 start starts at 0 and up to 0 later
#   1 wait starts at 592 and up to 320 later


wait_listing = lower(
    read_program(waiting.export_to_controller()),
    timestep=box.cycles_per_timestep,
)
print(wait_listing.text())

# Prints:
#   timestep: 4 cycles
#   w0: 200 samples
#   w1: 40 samples
#   drive0 (times in timesteps):
#       idle 128
#       wait_reg r2/4 min=20 max=100
#       set_freq 5000000000
#       drive w1 gain=0.5 phase=0 for 10
#   readout0 (times in timesteps):
#       set_freq 5000000000
#       acquire w0 gain=0.05 phase=0 for 50 into m0
#   link:controller (times in clock cycles):
#       idle 400
#       send pick_wait__1(m0) for 4
#       idle 108
#       recv r2


# %% Check the lowering against the schedule
_TIMED = re.compile(
    r"(?:if (?:not )?m\d+: )?(?P<kind>drive|acquire|wait|send)\b.*? (?:for )?(?P<ticks>\d+)(?: into m\d+)?$"
)
_KINDS = {"drive": "drive", "acquire": "readout", "wait": "wait", "send": "submit"}


def read_back(listing: Listing) -> list[dict[str, Any]]:
    """The timed events of an emitted listing, read from its instructions
    alone: what ``backends.validate`` compares with the schedule."""
    events = []
    for name, instructions in listing.channels.items():
        unit = 1 if name.startswith("link:") else listing.timestep
        line, cursor = listing.lines[name], 0
        for instruction in instructions:
            if instruction.startswith("set_freq"):
                continue
            if instruction.startswith("idle"):
                cursor += int(instruction.split()[1]) * unit
                continue
            if instruction.startswith("recv"):
                events.append((cursor, "answer", line, 0))
                continue
            if instruction.startswith("wait_reg"):
                # Placed at its lowest length, as the schedule places it.
                ticks = int(instruction.split("min=")[1].split()[0])
                events.append((cursor, "wait", line, ticks * unit))
                cursor += ticks * unit
                continue
            longest = 0
            for arm in instruction.split(" else: "):
                lead = 0
                if arm.startswith("idle "):
                    idle, arm = arm.split("; ", 1)
                    lead = int(idle.split()[1]) * unit
                found = _TIMED.match(arm)
                if found is None:
                    raise ValueError(f"cannot read back {arm!r}")
                length = int(found["ticks"]) * unit
                events.append((cursor + lead, _KINDS[found["kind"]], line, length))
                longest = max(longest, lead + length)
            cursor += longest
    events.sort(key=lambda event: event[0])
    return [
        {"kind": kind, "line": line, "start_cycles": start, "duration_cycles": length}
        for start, kind, line, length in events
    ]


for event in read_back(listing):
    print(event["kind"], event["line"], event["start_cycles"], event["duration_cycles"])

# Prints:
#   drive 0 0 40
#   readout 1 40 200
#   drive 0 440 40


# %% Run it: where your hardware plugs in
class DryRun:
    """Stands where the connection to the electronics goes. It takes a
    listing and gives every acquisition register the next outcome of
    *outcomes*, a list that is used again from its start when it runs out
    (0 without one)."""

    def __init__(self, outcomes: Sequence[int] = (0,)) -> None:
        self.outcomes = list(outcomes)

    def upload(self, listing: Listing) -> None:
        self.registers = re.findall(r"into (m\d+)", listing.text())

    def run(self, shots_count: int) -> list[dict[str, int]]:
        shots, drawn = [], 0
        for _ in range(shots_count):
            shot = {}
            for register in self.registers:
                shot[register] = self.outcomes[drawn % len(self.outcomes)]
                drawn += 1
            shots.append(shot)
        return shots


class SequencerBackend:
    name = "sequencer"
    formats = (FORMAT,)

    def __init__(self, hardware: Any = None) -> None:
        self.hardware = hardware if hardware is not None else DryRun()

    def control_system(self) -> pulse.Controller:
        return pulse.Controller(
            clock_ghz=1.0,
            cycles_per_timestep=4,
            sample_rate_ghz=1.0,
            min_pulse_cycles=16,
            waveform_memory_samples=16384,
            max_frequencies_per_line=4,
            max_amplitude=1.0,
            feedback_latency_cycles=200,
        )

    def emit(self, program: Mapping[str, Any]) -> Listing:
        timestep = self.control_system().cycles_per_timestep
        return lower(read_program(program), timestep)

    def run(self, artifact: Listing, *, shots_count: int = 1) -> list[dict[str, int]]:
        self.hardware.upload(artifact)
        return self.hardware.run(shots_count)

    def events(self, artifact: Listing) -> list[list[dict[str, Any]]]:
        """The emitted program read back, for ``backends.validate``."""
        return [read_back(artifact)]


backends.register("sequencer", SequencerBackend)
backend = SequencerBackend(hardware=DryRun(outcomes=[1, 0]))

artifact = backend.emit(scheduled.export_to_controller())
print(backend.run(artifact, shots_count=2))

# Prints:
#   [{'m2': 1}, {'m2': 0}]


report = backends.validate("sequencer")
print(report)

# Prints, wrapped here, with ... for text left out:
#   PASS play
#   PASS readout
#   PASS wait
#   PASS sync
#   PASS loop
#   PASS call
#   REFUSED answer: event 3 tests more than one measurement register
#   REFUSED frame_update: no instruction for a frame_update
#   PASS branch
#   REFUSED answer_timeout: event 3 tests more than one measurement register
#   REFUSED timeout_function: event 3 tests more than one measurement register
#   REFUSED runtime: event 3 changes a tone at run time
#   SKIP runtime_frequency: exceeds the controller's limits: line 0 (drive of qudit -1): the drive at 0 peaks at amplitude 2; the controller plays at most 1 (Controller.max_amplitude)
#   PASS shared_line
#   PASS shared_drive_line_two_tones
#   PASS shared_drive_line_one_tone
#   PASS several_controllers[0]
#   PASS several_controllers[1]
#   PASS unsupported_event
#   PASS newer_format
#   backend 'sequencer': 14 passed, 5 refused, 1 skipped


class EarlyBackend(SequencerBackend):
    name = "early"

    def emit(self, program):
        listing = super().emit(program)
        for instructions in listing.channels.values():
            for place, instruction in enumerate(instructions):
                if instruction.startswith("idle"):
                    ticks = int(instruction.split()[1]) - 1
                    instructions[place] = f"idle {ticks}"
        return listing


broken = backends.validate(EarlyBackend())
print("ok:", broken.ok)
for line in str(broken).splitlines():
    if line.startswith("FAIL branch"):
        print(line)
backends.unregister("sequencer")

# Prints, wrapped here, with ... for text left out:
#   ok: False
#   FAIL branch: line 0: event 1 is a play at 308 cycles; the controller program has a play at 312
