Skip to content

memq_dqc.builder

builder

Circuit builder utilities.

circuit_qubit_physical_map

circuit_qubit_physical_map(
    schedule: list[PartitionAssignment],
    swaps: list[list[SwapOp]],
) -> list[dict[int, tuple[int, int]]]

Create circuit-to-physical qubit maps for each time interval.

A physical qubit is characterized by an (int, int) tuple, where first element represents QPU index, second element represents qubit index for that given QPU. A circuit qubit is the qubit index as defined in the original input circuit.

Source code in src/memq_dqc/builder/extract_utils.py
def circuit_qubit_physical_map(
    schedule: list[PartitionAssignment],
    swaps: list[list[SwapOp]],
) -> list[dict[int, tuple[int, int]]]:
    """Create circuit-to-physical qubit maps for each time interval.

    A physical qubit is characterized by an (int, int) tuple, where first
    element represents QPU index, second element represents qubit index for
    that given QPU. A circuit qubit is the qubit index as defined in the
    original input circuit.

    """
    if not schedule:
        raise ValueError("schedule must contain at least one window.")

    current_map = _assignment_initial_positions(schedule[0])
    interval_maps: list[dict[int, tuple[int, int]]] = [current_map.copy()]

    # Each interval snapshot reflects the layout after the swaps for that
    # boundary have been applied.
    for interval in swaps:
        for swap in interval:
            q0 = swap.q0
            q1 = swap.q1
            pos0 = current_map[q0]
            pos1 = current_map[q1]
            current_map[q0] = pos1
            current_map[q1] = pos0
        interval_maps.append(current_map.copy())

    return interval_maps

identify_remote_gates

identify_remote_gates(
    circuit: Circuit, partition: Partitioner
) -> list[tuple[Op, dict[str, int]]]

Identify remote gates in the scheduled circuit.

Parameters:

Name Type Description Default
circuit Circuit

The circuit representing the quantum circuit.

required
partition Partitioner

The Partitioner object containing the partitioning schedule.

required

Returns:

Type Description
list[tuple[Op, dict[str, int]]]

Augmented list of operations with two-qubit gates replaced with remote

list[tuple[Op, dict[str, int]]]

variants where applicable.

Source code in src/memq_dqc/builder/extract_utils.py
def identify_remote_gates(
    circuit: Circuit,
    partition: Partitioner,
) -> list[tuple[Op, dict[str, int]]]:
    """Identify remote gates in the scheduled circuit.

    Args:
        circuit: The circuit representing the quantum circuit.
        partition: The Partitioner object containing the partitioning schedule.

    Returns:
        Augmented list of operations with two-qubit gates replaced with remote
        variants where applicable.
    """
    ops = circuit.mono.ops
    windows = partition.windows
    schedule = partition.schedule
    if windows is None or schedule is None:
        raise ValueError(
            "partition.run() must be called before identifying remote gates."
        )
    window_op_mapping = window_op_map(windows)

    # Iterate through 2-qubit gates; mark remote if they use distinct QPUs
    remote_gates: list[tuple[Op, dict[str, int]]] = []
    for op in ops:
        num_qubits = len(op.qubits)
        if num_qubits == 1:
            continue
        if num_qubits > 2:
            raise ValueError(
                "Only single- and two-qubit gates are supported currently."
            )
        if num_qubits != 2:
            raise ValueError("Expected a two-qubit operation.")
        q1, q2 = op.qubits
        op_window_idx = window_op_mapping[op.op_id]
        qubit_map = qubit_partition_map(schedule[op_window_idx])
        q1_qpu = qubit_map[q1.index]
        q2_qpu = qubit_map[q2.index]
        if q1_qpu == q2_qpu:
            continue
        remote_gates.append((op, {"q1_qpu": q1_qpu, "q2_qpu": q2_qpu}))

    return remote_gates

synthesize_state_teleportation_swaps

synthesize_state_teleportation_swaps(
    schedule: list[PartitionAssignment],
) -> list[list[SwapOp]]

Synthesize swaps to realize the state teleportation schedule.

Parameters:

Name Type Description Default
schedule list[PartitionAssignment]

A list of time steps, each mapping QPUs to logical qubits.

required

Returns:

Type Description
list[list[SwapOp]]

Swap operations per timestep that transform each assignment into the

list[list[SwapOp]]

next. The returned list has length len(schedule) - 1.

Raises:

Type Description
ValueError

If the schedule changes QPU counts or partition sizes.

RuntimeError

If swap synthesis fails to reach a target assignment.

Source code in src/memq_dqc/builder/extract_utils.py
def synthesize_state_teleportation_swaps(
    schedule: list[PartitionAssignment],
) -> list[list[SwapOp]]:
    """Synthesize swaps to realize the state teleportation schedule.

    Args:
        schedule: A list of time steps, each mapping QPUs to logical qubits.

    Returns:
        Swap operations per timestep that transform each assignment into the
        next. The returned list has length ``len(schedule) - 1``.

    Raises:
        ValueError: If the schedule changes QPU counts or partition sizes.
        RuntimeError: If swap synthesis fails to reach a target assignment.
    """
    swaps_per_timestep = [
        _synthesize_swaps_for_timestep(prev_assignment, curr_assignment)
        for prev_assignment, curr_assignment in zip(
            schedule,
            schedule[1:],
            strict=False,
        )
    ]

    # Rebase swap positions across timesteps so each swap references the
    # current physical positions resulting from previously emitted swaps.
    current_pos_by_qubit = _assignment_initial_positions(schedule[0])
    rebased_swaps_per_timestep: list[list[SwapOp]] = []
    for timestep_swaps in swaps_per_timestep:
        rebased_timestep_swaps: list[SwapOp] = []
        for swap in timestep_swaps:
            pos0 = current_pos_by_qubit[swap.q0]
            pos1 = current_pos_by_qubit[swap.q1]
            rebased_swap = SwapOp(
                q0=swap.q0,
                q1=swap.q1,
                pos0=pos0,
                pos1=pos1,
            )
            rebased_timestep_swaps.append(rebased_swap)
            current_pos_by_qubit[swap.q0], current_pos_by_qubit[swap.q1] = (
                pos1,
                pos0,
            )
        rebased_swaps_per_timestep.append(rebased_timestep_swaps)

    return rebased_swaps_per_timestep

window_final_op_id_map

window_final_op_id_map(
    windows: list[list[Op]],
) -> dict[int, int]

Create a map from window index to final operation ID.

This is useful to determine when we have reached the end of a given window, in order to insert swaps to prepare the correct partition for the next window. NOTE: does not include the final window, since no swaps need to be inserted after it.

Parameters:

Name Type Description Default
windows list[list[Op]]

List of operation windows.

required

Returns:

Type Description
dict[int, int]

A dictionary mapping window indices to the final operation ID.

Source code in src/memq_dqc/builder/extract_utils.py
def window_final_op_id_map(windows: list[list[Op]]) -> dict[int, int]:
    """Create a map from window index to final operation ID.

    This is useful to determine when we have reached the end of a given window,
    in order to insert swaps to prepare the correct partition for the next
    window. NOTE: does not include the final window, since no swaps need to be
    inserted after it.

    Args:
        windows: List of operation windows.

    Returns:
        A dictionary mapping window indices to the final operation ID.
    """
    return {
        window_idx: window[-1].op_id
        for window_idx, window in enumerate(windows[:-1])
    }

extract_distributed_circuit

extract_distributed_circuit(
    partitioner: Partitioner,
    *,
    ebit_assignment: bool = True,
    group_gates: bool = True,
    max_group_size: int | None = None,
    group_size_profile: SchedulerHardwareProfile
    | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> Program

Extract a distributed OpenQASM program from a completed partitioner.

Parameters:

Name Type Description Default
partitioner Partitioner

Partitioner with a completed partitioning run.

required
ebit_assignment bool

Whether the compiler assigns concrete e-bit pairs into the scheduler DAG. If false, schedulers choose from viable e-bit pair candidates.

True
group_gates bool

Whether compatible remote gate groups should share one cat-entanglement region in the emitted program.

True
max_group_size int | None

Optional maximum number of two-qubit gates per emitted gate group.

None
group_size_profile SchedulerHardwareProfile | None

Scheduler hardware profile whose timing bounds each gate group's duration to the EPR lifetime. When omitted the EPR-lifetime cap is disabled.

None
verbosity Literal['quiet', 'info', 'debug']

Logging verbosity for this workflow call.

'quiet'

Returns:

Type Description
Program

Distributed OpenQASM program with communication operations inserted.

Source code in src/memq_dqc/builder/__init__.py
def extract_distributed_circuit(
    partitioner: Partitioner,
    *,
    ebit_assignment: bool = True,
    group_gates: bool = True,
    max_group_size: int | None = None,
    group_size_profile: SchedulerHardwareProfile | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> ast.Program:
    """Extract a distributed OpenQASM program from a completed partitioner.

    Args:
        partitioner: Partitioner with a completed partitioning run.
        ebit_assignment: Whether the compiler assigns concrete e-bit pairs
            into the scheduler DAG. If false, schedulers choose from viable
            e-bit pair candidates.
        group_gates: Whether compatible remote gate groups should share one
            cat-entanglement region in the emitted program.
        max_group_size: Optional maximum number of two-qubit gates per emitted
            gate group.
        group_size_profile: Scheduler hardware profile whose timing bounds
            each gate group's duration to the EPR lifetime. When omitted the
            EPR-lifetime cap is disabled.
        verbosity: Logging verbosity for this workflow call.

    Returns:
        Distributed OpenQASM program with communication operations inserted.
    """
    from .circuit_extractor import (
        extract_distributed_circuit as _extract_distributed_circuit,
    )

    return _extract_distributed_circuit(
        partitioner,
        ebit_assignment=ebit_assignment,
        group_gates=group_gates,
        max_group_size=max_group_size,
        group_size_profile=group_size_profile,
        verbosity=verbosity,
    )