Skip to content

memq_dqc.partition

partition

Partitioning algorithms for interaction and network graphs.

PartitionSchedule module-attribute

PartitionSchedule: TypeAlias = list[dict[QPU, set[int]]]

Per-window placement mapping each QPU to its assigned logical qubits.

PartitionWindows module-attribute

PartitionWindows: TypeAlias = list[list[Op]]

Per-window operation groupings produced alongside a placement.

BenchmarkRandomPartitioner

BenchmarkRandomPartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
)

Bases: BasePartitioner

Partition qubits into static, randomly initialized assignments.

Initialize the benchmark random partitioner.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
window_length int | None

Number of two-qubit gates per window.

None
seed int | None

Optional RNG seed for reproducible random initialization.

None
Source code in src/memq_dqc/partition/benchmark_random/benchmark_random.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
) -> None:
    """Initialize the benchmark random partitioner.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        window_length: Number of two-qubit gates per window.
        seed: Optional RNG seed for reproducible random initialization.
    """
    super().__init__(network, program, seed=seed)
    self.window_length = window_length

run

run() -> None

Run the benchmark random partitioning algorithm.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/benchmark_random/benchmark_random.py
def run(self) -> None:
    """Run the benchmark random partitioning algorithm.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    overall_timer = StepTimer()
    num_qubits = count_total_qubits(self.circuit.mono.program)
    partition_sizes = _effective_partition_sizes(
        self.network.comp_qubits_per_qpu(),
        num_qubits,
    )
    circuit = self.circuit
    num_two_qubit_ops = circuit.mono.num_two_qubit_gates
    window_length_mode = "provided"
    if self.window_length is None:
        window_length_mode = "auto"
        if num_two_qubit_ops == 0:
            self.window_length = 1
        else:
            gate_density = num_two_qubit_ops / max(1, num_qubits)
            density_scale = max(0.5, min(math.sqrt(gate_density), 2.0))
            base_window = math.sqrt(num_two_qubit_ops) * density_scale
            min_window = 1 if num_two_qubit_ops < 10 else 10
            max_window = min(100, num_two_qubit_ops)
            self.window_length = max(
                min_window, min(int(round(base_window)), max_window)
            )
    logger.debug(
        "Benchmark random partitioning parameters: logical_qubits=%d "
        "two_qubit_ops=%d window_length=%d mode=%s partition_sizes=%s "
        "seed=%s.",
        num_qubits,
        num_two_qubit_ops,
        self.window_length,
        window_length_mode,
        partition_sizes,
        self.seed,
    )
    windows_timer = StepTimer()
    windows = get_windows(circuit, self.window_length)
    if not windows:
        raise ValueError(
            "No operation windows generated from the circuit."
        )
    logger.debug(
        "Generated %d partition windows in %.3fs.",
        len(windows),
        windows_timer.elapsed_seconds(),
    )
    network_qpu_ids = sorted(
        {qubit.qpu_id for qubit in self.network.qubit_type_map}
    )
    self.windows = windows

    qpus = [QPU(id=qpu_id) for qpu_id in network_qpu_ids]
    random_partition = _build_random_partition(
        partition_sizes,
        num_qubits,
        seed=self.seed,
    )
    logger.debug("Random partition assignment: %s.", random_partition)

    def _remote_ebit_multiplier(part_a: int, part_b: int) -> float:
        qpu_a = network_qpu_ids[part_a]
        qpu_b = network_qpu_ids[part_b]
        return float(self.network.remote_gate_ebit_cost(qpu_a, qpu_b))

    total_entanglement_cost = 0.0
    for window_idx, ops in enumerate(windows):
        window_timer = StepTimer()
        window_graph = create_initial_subcircuit_graph(num_qubits, ops)
        window_cost = partition_cost(
            window_graph,
            random_partition,
            edge_cost=_remote_ebit_multiplier,
        )
        total_entanglement_cost += window_cost
        logger.debug(
            "Window %d processed in %.3fs with cost=%.3f.",
            window_idx,
            window_timer.elapsed_seconds(),
            window_cost,
        )

    self.cost = total_entanglement_cost
    schedule_timer = StepTimer()
    self.schedule = _build_schedule(
        [random_partition] * len(windows),
        qpus,
    )
    logger.debug(
        "Built random schedule with %d windows in %.3fs. "
        "Total cost=%.3f overall_runtime=%.3fs.",
        len(self.schedule),
        schedule_timer.elapsed_seconds(),
        total_entanglement_cost,
        overall_timer.elapsed_seconds(),
    )

BenchmarkStaticPartitioner

BenchmarkStaticPartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
)

Bases: BasePartitioner

Partition qubits into static, capacity-bounded QPU assignments.

Initialize the benchmark static partitioner.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
window_length int | None

Number of two-qubit gates per window.

None
seed int | None

Optional seed, recorded but unused by this deterministic algorithm.

None
Source code in src/memq_dqc/partition/benchmark_static/benchmark_static.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
) -> None:
    """Initialize the benchmark static partitioner.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        window_length: Number of two-qubit gates per window.
        seed: Optional seed, recorded but unused by this deterministic
            algorithm.
    """
    super().__init__(network, program, seed=seed)
    self.window_length = window_length

run

run() -> None

Run the benchmark static partitioning algorithm.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/benchmark_static/benchmark_static.py
def run(self) -> None:
    """Run the benchmark static partitioning algorithm.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    overall_timer = StepTimer()
    num_qubits = count_total_qubits(self.circuit.mono.program)
    partition_sizes = _effective_partition_sizes(
        self.network.comp_qubits_per_qpu(),
        num_qubits,
    )
    circuit = self.circuit
    num_two_qubit_ops = circuit.mono.num_two_qubit_gates
    window_length_mode = "provided"
    if self.window_length is None:
        window_length_mode = "auto"
        if num_two_qubit_ops == 0:
            self.window_length = 1
        else:
            gate_density = num_two_qubit_ops / max(1, num_qubits)
            density_scale = max(0.5, min(math.sqrt(gate_density), 2.0))
            base_window = math.sqrt(num_two_qubit_ops) * density_scale
            min_window = 1 if num_two_qubit_ops < 10 else 10
            max_window = min(100, num_two_qubit_ops)
            self.window_length = max(
                min_window, min(int(round(base_window)), max_window)
            )
    logger.debug(
        "Benchmark static partitioning parameters: logical_qubits=%d "
        "two_qubit_ops=%d window_length=%d mode=%s partition_sizes=%s.",
        num_qubits,
        num_two_qubit_ops,
        self.window_length,
        window_length_mode,
        partition_sizes,
    )
    windows_timer = StepTimer()
    windows = get_windows(circuit, self.window_length)
    if not windows:
        raise ValueError(
            "No operation windows generated from the circuit."
        )
    logger.debug(
        "Generated %d partition windows in %.3fs.",
        len(windows),
        windows_timer.elapsed_seconds(),
    )
    network_qpu_ids = sorted(
        {qubit.qpu_id for qubit in self.network.qubit_type_map}
    )
    self.windows = windows

    qpus = [QPU(id=qpu_id) for qpu_id in network_qpu_ids]
    static_partition = _build_static_partition(partition_sizes, num_qubits)
    logger.debug("Static partition assignment: %s.", static_partition)

    def _remote_ebit_multiplier(part_a: int, part_b: int) -> float:
        qpu_a = network_qpu_ids[part_a]
        qpu_b = network_qpu_ids[part_b]
        return float(self.network.remote_gate_ebit_cost(qpu_a, qpu_b))

    total_entanglement_cost = 0.0
    for window_idx, ops in enumerate(windows):
        window_timer = StepTimer()
        window_graph = create_initial_subcircuit_graph(num_qubits, ops)
        window_cost = partition_cost(
            window_graph,
            static_partition,
            edge_cost=_remote_ebit_multiplier,
        )
        total_entanglement_cost += window_cost
        logger.debug(
            "Window %d processed in %.3fs with cost=%.3f.",
            window_idx,
            window_timer.elapsed_seconds(),
            window_cost,
        )

    self.cost = total_entanglement_cost
    schedule_timer = StepTimer()
    self.schedule = _build_schedule(
        [static_partition] * len(windows),
        qpus,
    )
    logger.debug(
        "Built static schedule with %d windows in %.3fs. "
        "Total cost=%.3f overall_runtime=%.3fs.",
        len(self.schedule),
        schedule_timer.elapsed_seconds(),
        total_entanglement_cost,
        overall_timer.elapsed_seconds(),
    )

HypergraphPartitioner

HypergraphPartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    config_path: str | PathLike[str] | None = None,
    epsilon: float = 0.03,
    max_group_size: int | None = None,
    window_length: int | None = None,
    respect_qpu_capacities: bool = True,
    seed: int | None = None,
)

Bases: BasePartitioner

Partition qubits once using a grouped-gate hypergraph.

Initialize the hypergraph partitioner.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
config_path str | PathLike[str] | None

Optional KahyPar INI configuration path. When omitted, the packaged hypergraph configuration is used.

None
epsilon float

Allowed KahyPar partition imbalance.

0.03
max_group_size int | None

Optional maximum two-qubit gates per group.

None
window_length int | None

Optional window length used only to adapt the static assignment to the existing schedule interface.

None
respect_qpu_capacities bool

When True, the real per-QPU computation capacities are passed to KahyPar as custom target block weights so it respects non-uniform, fully-packed networks. Set False to reproduce the prior behavior where KahyPar balances uniformly using only epsilon.

True
seed int | None

Optional KahyPar random seed. When omitted, the seed from the INI configuration is used.

None
Source code in src/memq_dqc/partition/hypergraph/hypergraph.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    config_path: str | PathLike[str] | None = None,
    epsilon: float = 0.03,
    max_group_size: int | None = None,
    window_length: int | None = None,
    respect_qpu_capacities: bool = True,
    seed: int | None = None,
) -> None:
    """Initialize the hypergraph partitioner.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        config_path: Optional KahyPar INI configuration path. When
            omitted, the packaged hypergraph configuration is used.
        epsilon: Allowed KahyPar partition imbalance.
        max_group_size: Optional maximum two-qubit gates per group.
        window_length: Optional window length used only to adapt the
            static assignment to the existing schedule interface.
        respect_qpu_capacities: When True, the real per-QPU computation
            capacities are passed to KahyPar as custom target block
            weights so it respects non-uniform, fully-packed networks.
            Set False to reproduce the prior behavior where KahyPar
            balances uniformly using only ``epsilon``.
        seed: Optional KahyPar random seed. When omitted, the seed
            from the INI configuration is used.
    """
    super().__init__(network, program, seed=seed)
    self.config_path = config_path
    self.epsilon = epsilon
    self.max_group_size = max_group_size
    self.window_length = window_length
    self.respect_qpu_capacities = respect_qpu_capacities

run

run() -> None

Run grouped-gate hypergraph partitioning.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/hypergraph/hypergraph.py
def run(self) -> None:
    """Run grouped-gate hypergraph partitioning.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    timer = StepTimer()
    num_qubits = count_total_qubits(self.circuit.mono.program)
    qpu_ids = _network_qpu_ids(self.network)
    qpu_capacities = dict(
        zip(qpu_ids, self.network.comp_qubits_per_qpu(), strict=True)
    )

    gate_packets = build_gate_packets(
        self.circuit.mono.ops,
        max_size=self.max_group_size,
    )
    packet_counter = packets_to_hypergraph(gate_packets)
    partition_result = partition_hypergraph(
        packet_counter,
        k=len(qpu_ids),
        config_path=resolve_kahypar_config_path(self.config_path),
        epsilon=self.epsilon,
        seed=self.seed,
        block_capacities=(
            [qpu_capacities[qpu_id] for qpu_id in qpu_ids]
            if self.respect_qpu_capacities
            else None
        ),
    )
    assignment = partition_result_to_assignment(partition_result, qpu_ids)
    _assign_missing_qubits(
        assignment,
        logical_qubits=set(range(num_qubits)),
        qpu_capacities=qpu_capacities,
    )
    _validate_assignment(
        assignment,
        logical_qubits=set(range(num_qubits)),
        qpu_capacities=qpu_capacities,
    )

    if self.window_length is None:
        self.windows = [self.circuit.mono.ops]
    else:
        self.windows = get_windows(self.circuit, self.window_length)
    if not self.windows:
        raise ValueError(
            "No operation windows generated from the circuit."
        )
    self.schedule = [
        {QPU(id=qpu_id): set(assignment[qpu_id]) for qpu_id in qpu_ids}
        for _ in self.windows
    ]
    self.cost = 0.0
    logger.debug(
        "Hypergraph partitioning completed in %.3fs: groups=%d "
        "hyperedges=%d qpus=%d.",
        timer.elapsed_seconds(),
        len(gate_packets),
        len(packet_counter),
        len(qpu_ids),
    )

    logger.debug("Hypergraph partition assignment: %s", assignment)

InteractionPartitioner

InteractionPartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
)

Bases: BasePartitioner

Partition qubits using the Interaction (TODO: cite) algorithm.

Initialize the Interaction partitioner.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
window_length int | None

Number of two-qubit gates per window.

None
seed int | None

Optional seed for the randomized initial partitioning. When omitted the historical default seed is used, preserving prior behavior.

None
Source code in src/memq_dqc/partition/interaction/interaction.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    window_length: int | None = None,
    seed: int | None = None,
) -> None:
    """Initialize the Interaction partitioner.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        window_length: Number of two-qubit gates per window.
        seed: Optional seed for the randomized initial partitioning. When
            omitted the historical default seed is used, preserving prior
            behavior.
    """
    super().__init__(network, program, seed=seed)
    self.window_length = window_length

run

run() -> None

Run the Interaction partitioning algorithm.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/interaction/interaction.py
def run(self) -> None:
    """Run the Interaction partitioning algorithm.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    overall_timer = StepTimer()
    num_qubits = count_total_qubits(self.circuit.mono.program)
    partition_sizes = _effective_partition_sizes(
        self.network.comp_qubits_per_qpu(),
        num_qubits,
    )
    circuit = self.circuit
    num_two_qubit_ops = circuit.mono.num_two_qubit_gates
    window_length_mode = "provided"
    # Determining optimal window size
    if self.window_length is None:
        window_length_mode = "auto"
        if num_two_qubit_ops == 0:
            self.window_length = 1
        else:
            # Default segment length: 2*sqrt(g), bounded. The sqrt keeps
            # the segment count and the segment size growing at the same
            # rate as the circuit; the bounds keep a segment's interaction
            # graph large enough to be informative and small enough to keep
            # the per-segment KL pass inexpensive. This is a starting point,
            # not an optimum -- window_length is an explicit input and
            # is worth sweeping for a given circuit and network.
            base_window = 2.0 * math.sqrt(num_two_qubit_ops)
            min_window = 1 if num_two_qubit_ops < 10 else 10
            max_window = min(100, num_two_qubit_ops)
            self.window_length = max(
                min_window, min(int(round(base_window)), max_window)
            )

    logger.debug(
        "Interaction partitioning parameters: logical_qubits=%d "
        "two_qubit_ops=%d window_length=%d mode=%s partition_sizes=%s.",
        num_qubits,
        num_two_qubit_ops,
        self.window_length,
        window_length_mode,
        partition_sizes,
    )

    windows_timer = StepTimer()
    windows = get_windows(circuit, self.window_length)
    if not windows:
        raise ValueError(
            "No operation windows generated from the circuit."
        )
    logger.debug(
        "Generated %d partition windows in %.3fs.",
        len(windows),
        windows_timer.elapsed_seconds(),
    )
    # QPU IDs must share the ordering of ``partition_sizes`` (both come
    # from the network's processor order) so a partition index maps to
    # the correct QPU when scoring crossing edges below.
    network_qpu_ids = self.network.qpu_ids()
    if len(network_qpu_ids) != len(partition_sizes):
        raise ValueError(
            "Network QPU count does not match partition count: "
            f"{len(network_qpu_ids)} QPUs vs "
            f"{len(partition_sizes)} partitions."
        )

    def _remote_ebit_multiplier(part_a: int, part_b: int) -> float:
        qpu_a = network_qpu_ids[part_a]
        qpu_b = network_qpu_ids[part_b]
        return float(self.network.remote_gate_ebit_cost(qpu_a, qpu_b))

    self.windows = windows
    qpus = [QPU(id=qpu_id) for qpu_id in network_qpu_ids]
    initial_partition_timer = StepTimer()
    initial_subcircuit = create_initial_subcircuit_graph(
        num_qubits, windows[0]
    )
    kl_seed = self.seed if self.seed is not None else _DEFAULT_KL_SEED
    partition_result = kl_partition(
        initial_subcircuit, partitions=partition_sizes, seed=kl_seed
    )

    total_entanglement_cost = partition_cost(
        initial_subcircuit,
        partition_result,
        edge_cost=_remote_ebit_multiplier,
    )
    logger.debug(
        "Initial partition computed in %.3fs with cost=%.3f.",
        initial_partition_timer.elapsed_seconds(),
        total_entanglement_cost,
    )
    window_partitions = [partition_result]

    follow_on_timer = StepTimer()
    for window_idx, ops in enumerate(windows[1:], start=1):
        window_timer = StepTimer()
        previous_partition = window_partitions[-1]
        partition_map = qubit_partition_map(previous_partition)
        window_graph, active_qubits = build_window_interaction_graph(
            ops, partition_map
        )
        if not active_qubits:
            window_partitions.append(previous_partition)
            logger.debug(
                "Window %d reused previous partition in %.3fs: "
                "no active qubits.",
                window_idx,
                window_timer.elapsed_seconds(),
            )
            continue

        active_partition_sizes = [
            len(partition & active_qubits)
            for partition in previous_partition
        ]
        active_partition = kl_partition(
            window_graph,
            partitions=active_partition_sizes,
            seed=kl_seed,
        )
        candidate_partition = _merge_partitions_with_active(
            previous_partition, active_partition, active_qubits
        )

        previous_cost = partition_cost(
            window_graph,
            previous_partition,
            edge_cost=_remote_ebit_multiplier,
        )
        candidate_cost = partition_cost(
            window_graph,
            candidate_partition,
            edge_cost=_remote_ebit_multiplier,
        ) + movement_cost(
            candidate_partition,
            previous_partition,
            network=self.network,
            qpu_ids=network_qpu_ids,
        )
        if candidate_cost <= previous_cost:
            window_partitions.append(candidate_partition)
            total_entanglement_cost += candidate_cost
            decision = "accepted"
        else:
            window_partitions.append(previous_partition)
            total_entanglement_cost += previous_cost
            decision = "reused_previous"

        logger.debug(
            "Window %d processed in %.3fs: active_qubits=%d "
            "previous_cost=%.3f candidate_cost=%.3f decision=%s.",
            window_idx,
            window_timer.elapsed_seconds(),
            len(active_qubits),
            previous_cost,
            candidate_cost,
            decision,
        )

    logger.debug(
        "Processed %d follow-on windows in %.3fs.",
        max(0, len(windows) - 1),
        follow_on_timer.elapsed_seconds(),
    )

    self.cost = total_entanglement_cost
    schedule_timer = StepTimer()
    self.schedule = _build_schedule(window_partitions, qpus)
    logger.debug(
        "Built schedule with %d windows in %.3fs. Total cost=%.3f "
        "overall_runtime=%.3fs.",
        len(self.schedule),
        schedule_timer.elapsed_seconds(),
        total_entanglement_cost,
        overall_timer.elapsed_seconds(),
    )

InteractionStaticPartitioner

InteractionStaticPartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    window_length: int | None = None,
)

Bases: BasePartitioner

Partition qubits once using the whole-circuit interaction graph.

Initialize the static interaction partitioner.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
window_length int | None

Number of two-qubit gates per reporting window.

None
Source code in src/memq_dqc/partition/interaction_static/interaction_static.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    window_length: int | None = None,
) -> None:
    """Initialize the static interaction partitioner.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        window_length: Number of two-qubit gates per reporting window.
    """
    super().__init__(network, program)
    self.window_length = window_length

run

run() -> None

Run static whole-circuit interaction partitioning.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/interaction_static/interaction_static.py
def run(self) -> None:
    """Run static whole-circuit interaction partitioning.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    overall_timer = StepTimer()
    num_qubits = count_total_qubits(self.circuit.mono.program)
    partition_sizes = _effective_partition_sizes(
        self.network.comp_qubits_per_qpu(),
        num_qubits,
    )
    circuit = self.circuit
    num_two_qubit_ops = circuit.mono.num_two_qubit_gates
    window_length_mode = "provided"
    if self.window_length is not None and self.window_length < 1:
        raise ValueError("window_length must be positive when provided.")
    if self.window_length is None:
        window_length_mode = "auto"
        if num_two_qubit_ops == 0:
            self.window_length = 1
            gate_density = num_two_qubit_ops / max(1, num_qubits)
            density_scale = max(0.5, min(math.sqrt(gate_density), 2.0))
            base_window = math.sqrt(num_two_qubit_ops) * density_scale
            min_window = 1 if num_two_qubit_ops < 10 else 10
            max_window = min(100, num_two_qubit_ops)
            self.window_length = max(
                min_window, min(int(round(base_window)), max_window)
            )

    logger.debug(
        "Interaction-static partitioning parameters: logical_qubits=%d "
        "two_qubit_ops=%d window_length=%d mode=%s partition_sizes=%s.",
        num_qubits,
        num_two_qubit_ops,
        self.window_length,
        window_length_mode,
        partition_sizes,
    )
    windows_timer = StepTimer()
    windows = get_windows(circuit, self.window_length)
    if not windows:
        raise ValueError(
            "No operation windows generated from the circuit."
        )
    logger.debug(
        "Generated %d reporting windows in %.3fs.",
        len(windows),
        windows_timer.elapsed_seconds(),
    )
    self.windows = windows

    network_qpu_ids = sorted(
        {qubit.qpu_id for qubit in self.network.qubit_type_map}
    )

    def _remote_ebit_multiplier(part_a: int, part_b: int) -> float:
        qpu_a = network_qpu_ids[part_a]
        qpu_b = network_qpu_ids[part_b]
        return float(self.network.remote_gate_ebit_cost(qpu_a, qpu_b))

    graph_timer = StepTimer()
    interaction_graph = create_initial_subcircuit_graph(
        num_qubits,
        circuit.mono.ops,
    )
    logger.debug(
        "Built whole-circuit interaction graph in %.3fs: nodes=%d "
        "edges=%d.",
        graph_timer.elapsed_seconds(),
        interaction_graph.number_of_nodes(),
        interaction_graph.number_of_edges(),
    )

    partition_timer = StepTimer()
    static_partition = kl_partition(
        interaction_graph,
        partitions=partition_sizes,
    )
    reported_cost = partition_cost(
        interaction_graph,
        static_partition,
        edge_cost=_remote_ebit_multiplier,
    )
    logger.debug(
        "Static interaction partition computed in %.3fs with cost=%.3f: "
        "%s.",
        partition_timer.elapsed_seconds(),
        reported_cost,
        static_partition,
    )

    qpus = [QPU(id=qpu_id) for qpu_id in network_qpu_ids]
    schedule_timer = StepTimer()
    self.schedule = _build_schedule(
        [static_partition] * len(windows),
        qpus,
    )
    self.cost = reported_cost
    logger.debug(
        "Built interaction-static schedule with %d windows in %.3fs. "
        "Total cost=%.3f overall_runtime=%.3fs.",
        len(self.schedule),
        schedule_timer.elapsed_seconds(),
        reported_cost,
        overall_timer.elapsed_seconds(),
    )

QPU dataclass

QPU(id: int)

Represents a QPU identifier for partition assignments.

BasePartitioner

BasePartitioner(
    network: NetworkGraph,
    program: Program,
    *,
    seed: int | None = None,
)

Bases: ABC

Base class for partitioning algorithm implementations.

Initialize the partitioner with circuit and network inputs.

Parameters:

Name Type Description Default
network NetworkGraph

Network graph describing available resources.

required
program Program

Parsed OpenQASM 3 program.

required
seed int | None

Optional seed for algorithms with random components. Deterministic algorithms record it but may ignore it.

None
Source code in src/memq_dqc/partition/partitioner.py
def __init__(
    self,
    network: NetworkGraph,
    program: ast.Program,
    *,
    seed: int | None = None,
) -> None:
    """Initialize the partitioner with circuit and network inputs.

    Args:
        network: Network graph describing available resources.
        program: Parsed OpenQASM 3 program.
        seed: Optional seed for algorithms with random components.
            Deterministic algorithms record it but may ignore it.
    """
    self.network = network
    self.circuit = Circuit(program)
    self.seed = seed
    self._reported_cost: float | None = None
    self._exact_cost: float | None = None
    self.schedule: PartitionSchedule | None = None
    self.windows: PartitionWindows | None = None

cost property writable

cost: float | None

Return the latest entanglement cost, if available.

When a schedule and windowing are available, cost is derived from the total routed e-bit usage implied by remote gates and inter-window qubit movement.

run abstractmethod

run() -> None

Run the partitioning algorithm.

Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/partitioner.py
@abstractmethod
def run(self) -> None:
    """Run the partitioning algorithm.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    raise NotImplementedError

Partitioner

Partitioner(
    network: NetworkInput | ProgramInput,
    program: ProgramInput | NetworkInput,
    *,
    algo: str
    | type[_Algorithm]
    | _Algorithm = "interaction",
    algo_kwargs: dict[str, Any] | None = None,
)

Orchestrate a partitioning algorithm implementation.

Initialize the partitioner and select the algorithm.

Parameters:

Name Type Description Default
network NetworkInput | ProgramInput

Network graph or parsed OpenQASM 3 program, or a path to either input type. When both positional inputs are file paths or in-memory objects, the constructor infers which one is the network and which one is the program.

required
program ProgramInput | NetworkInput

Parsed OpenQASM 3 program or network graph, or a path to either input type. When both positional inputs are file paths or in-memory objects, the constructor infers which one is the network and which one is the program.

required
algo str | type[_Algorithm] | _Algorithm

Algorithm name, class, or preconfigured instance.

'interaction'
algo_kwargs dict[str, Any] | None

Keyword arguments forwarded to the algorithm.

None
Source code in src/memq_dqc/partition/partitioner.py
def __init__(
    self,
    network: NetworkInput | ProgramInput,
    program: ProgramInput | NetworkInput,
    *,
    algo: str | type[_Algorithm] | _Algorithm = "interaction",
    algo_kwargs: dict[str, Any] | None = None,
) -> None:
    """Initialize the partitioner and select the algorithm.

    Args:
        network: Network graph or parsed OpenQASM 3 program, or a path
            to either input type. When both positional inputs are file
            paths or in-memory objects, the constructor infers which one
            is the network and which one is the program.
        program: Parsed OpenQASM 3 program or network graph, or a path to
            either input type. When both positional inputs are file paths
            or in-memory objects, the constructor infers which one is the
            network and which one is the program.
        algo: Algorithm name, class, or preconfigured instance.
        algo_kwargs: Keyword arguments forwarded to the algorithm.
    """
    resolved_network, resolved_program = _resolve_partitioner_inputs(
        network, program
    )
    self._algorithm = self._resolve_algorithm(
        resolved_network, resolved_program, algo, algo_kwargs
    )
    self._distributed_ebit_assignment = True
    self._distributed_group_gates = True
    self._distributed_max_group_size: int | None = None
    self._distributed_group_size_profile: (
        SchedulerHardwareProfile | None
    ) = None

cost property

cost: float | None

Return the exact entanglement cost, if available.

The true e-bit usage is only known once the distributed circuit has been extracted, because that is where routing, link selection, and state-teleportation swaps are actually resolved. This property therefore extracts the distributed circuit on first access rather than reporting the cheaper partition-time approximation, so the reported cost does not depend on whether the caller happened to touch the distributed circuit first.

If the distributed circuit cannot be extracted at all -- for example on a network whose computation qubits cannot reach any communication qubit -- there is no measured cost to report, so the partition-time approximation is returned and a warning is logged.

schedule property

schedule: PartitionSchedule | None

Return the latest partition schedule, if available.

windows property

windows: PartitionWindows | None

Return the latest operation windows, if available.

circuit property

circuit: Circuit

Return the circuit for the configured program.

network property

network: NetworkGraph

Return the network graph used by the configured algorithm.

distributed_circuit property

distributed_circuit: DistributedCircuit

Return the distributed circuit, extracting it on first access.

Raises:

Type Description
ValueError

If partitioning has not been run yet.

RuntimeError

If extraction does not populate the circuit.

distributed_program property

distributed_program: Program

Return the distributed OpenQASM program for this partitioner.

distributed_qasm property

distributed_qasm: str

Return the distributed circuit as OpenQASM 3 source text.

Extracts the distributed circuit on first access if needed.

run

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

Run the configured partitioning algorithm.

Parameters:

Name Type Description Default
ebit_assignment bool | None

Whether to also extract the distributed circuit during this call, and if so whether the compiler assigns concrete e-bit pairs into the scheduler DAG. When omitted, this method only runs partitioning and lazy extraction defaults to explicit e-bit assignment.

None
group_gates bool

Whether distributed extraction should keep compatible remote gate groups inside a shared cat-entanglement region.

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'
Updates

cost, schedule, and windows with the latest partitioning results.

Source code in src/memq_dqc/partition/partitioner.py
def run(
    self,
    *,
    ebit_assignment: bool | None = None,
    group_gates: bool = True,
    max_group_size: int | None = None,
    group_size_profile: SchedulerHardwareProfile | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> None:
    """Run the configured partitioning algorithm.

    Args:
        ebit_assignment: Whether to also extract the distributed circuit
            during this call, and if so whether the compiler assigns
            concrete e-bit pairs into the scheduler DAG. When omitted,
            this method only runs partitioning and lazy extraction
            defaults to explicit e-bit assignment.
        group_gates: Whether distributed extraction should keep compatible
            remote gate groups inside a shared cat-entanglement region.
        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.

    Updates:
        cost, schedule, and windows with the latest partitioning results.
    """
    if max_group_size is not None and max_group_size < 1:
        raise ValueError("max_group_size must be positive when provided.")
    self.circuit.distributed = None
    self._distributed_ebit_assignment = (
        True if ebit_assignment is None else ebit_assignment
    )
    self._distributed_group_gates = group_gates
    self._distributed_max_group_size = max_group_size
    self._distributed_group_size_profile = group_size_profile
    with workflow_logging(verbosity):
        timer = StepTimer()
        logger.info(
            "Starting partitioning with %s.",
            type(self._algorithm).__name__,
        )
        self._algorithm.run()
        schedule = self._algorithm.schedule
        if not schedule:
            logger.warning(
                "Partitioning finished without a partition schedule "
                "after %.3fs.",
                timer.elapsed_seconds(),
            )
            return

        initial_mapping = _circuit_qubit_physical_map(schedule[0])
        final_mapping = _circuit_qubit_physical_map(schedule[-1])
        final_window_idx = len(schedule) - 1
        logger.info(
            "Partitioning completed in %.3fs: windows=%d cost=%s.",
            timer.elapsed_seconds(),
            len(schedule),
            self._algorithm.cost,
        )
        logger.debug(
            "Initial logical->physical mapping (window 0): %s",
            initial_mapping,
        )
        logger.debug(
            "Final logical->physical mapping (window %d): %s",
            final_window_idx,
            final_mapping,
        )
        if ebit_assignment is not None:
            self._ensure_distributed_circuit(verbosity=verbosity)

save_distributed_circuit

save_distributed_circuit(path: str | PathLike[str]) -> Path

Write the distributed circuit to an OpenQASM 3 file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Destination file path.

required

Returns:

Type Description
Path

The path the circuit was written to.

Source code in src/memq_dqc/partition/partitioner.py
def save_distributed_circuit(self, path: str | PathLike[str]) -> Path:
    """Write the distributed circuit to an OpenQASM 3 file.

    Args:
        path: Destination file path.

    Returns:
        The path the circuit was written to.
    """
    destination = Path(path)
    destination.write_text(self.distributed_qasm)
    return destination

annotated_dag

annotated_dag() -> DiGraph

Build an annotated distributed-DAG graph for the circuit.

Opt-in export; compilation never builds this automatically. A fresh graph is constructed on each call. Extracts the distributed circuit on first access if needed.

Returns:

Type Description
DiGraph

An annotated networkx.DiGraph of the distributed circuit.

Source code in src/memq_dqc/partition/partitioner.py
def annotated_dag(self) -> nx.DiGraph:
    """Build an annotated distributed-DAG graph for the circuit.

    Opt-in export; compilation never builds this automatically. A fresh
    graph is constructed on each call. Extracts the distributed circuit on
    first access if needed.

    Returns:
        An annotated `networkx.DiGraph` of the distributed circuit.
    """
    from memq_dqc.circuit.dag import build_annotated_dag

    return build_annotated_dag(self.distributed_circuit)

to_dag_json

to_dag_json(
    path: str | PathLike[str] | None = None,
    *,
    indent: int | None = 2,
) -> str

Serialize the annotated distributed DAG to a JSON document.

Opt-in export; compilation never serializes automatically. See memq_dqc.circuit.dag.annotated_dag_to_json for the document layout. Extracts the distributed circuit on first access if needed.

Parameters:

Name Type Description Default
path str | PathLike[str] | None

Optional destination file. When given, the JSON document is written there in addition to being returned.

None
indent int | None

Indentation forwarded to the underlying serializer. Pass None for the most compact single-line output.

2

Returns:

Type Description
str

The JSON document as a string.

Source code in src/memq_dqc/partition/partitioner.py
def to_dag_json(
    self,
    path: str | PathLike[str] | None = None,
    *,
    indent: int | None = 2,
) -> str:
    """Serialize the annotated distributed DAG to a JSON document.

    Opt-in export; compilation never serializes automatically. See
    [memq_dqc.circuit.dag.annotated_dag_to_json][memq_dqc.circuit.dag.annotated.annotated_dag_to_json] for the document
    layout. Extracts the distributed circuit on first access if needed.

    Args:
        path: Optional destination file. When given, the JSON document is
            written there in addition to being returned.
        indent: Indentation forwarded to the underlying serializer. Pass
            ``None`` for the most compact single-line output.

    Returns:
        The JSON document as a string.
    """
    from memq_dqc.circuit.dag import (
        annotated_dag_to_json,
        build_annotated_dag,
    )

    graph = build_annotated_dag(self.distributed_circuit)
    return annotated_dag_to_json(graph, path, indent=indent)

verify

verify(
    *,
    shots: int = 50000000,
    fidelity_threshold: float = 0.9,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> bool

Verify that the distributed circuit matches the original circuit.

Treats the distributed circuit as a single monolithic circuit in which remote operations act perfectly, then compares its measurement distribution against the original (pre-partition) circuit via Hellinger fidelity. The original circuit is taken from this partitioner, so it does not need to be supplied again. Extracts the distributed circuit on first access if needed.

Parameters:

Name Type Description Default
shots int

Number of shots to execute each circuit for.

50000000
fidelity_threshold float

Minimum Hellinger fidelity required for the distributed circuit to be considered correct.

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

Logging verbosity for this workflow call.

'quiet'

Returns:

Type Description
bool

True if the distributed circuit reproduces the original circuit's

bool

output distribution within the fidelity threshold, False otherwise.

Source code in src/memq_dqc/partition/partitioner.py
def verify(
    self,
    *,
    shots: int = 50000000,
    fidelity_threshold: float = 0.90,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> bool:
    """Verify that the distributed circuit matches the original circuit.

    Treats the distributed circuit as a single monolithic circuit in which
    remote operations act perfectly, then compares its measurement
    distribution against the original (pre-partition) circuit via Hellinger
    fidelity. The original circuit is taken from this partitioner, so it
    does not need to be supplied again. Extracts the distributed circuit on
    first access if needed.

    Args:
        shots: Number of shots to execute each circuit for.
        fidelity_threshold: Minimum Hellinger fidelity required for the
            distributed circuit to be considered correct.
        verbosity: Logging verbosity for this workflow call.

    Returns:
        True if the distributed circuit reproduces the original circuit's
        output distribution within the fidelity threshold, False otherwise.
    """
    from memq_dqc.verify import verify_distributed_circuit

    return verify_distributed_circuit(
        self.circuit.mono.program,
        self.distributed_program,
        shots=shots,
        fidelity_threshold=fidelity_threshold,
        verbosity=verbosity,
    )