Skip to content

memq_dqc.network

network

Network graph data structures, loaders, generators, and config helpers.

CanonicalNetworkConfigBuilder dataclass

CanonicalNetworkConfigBuilder(
    version: str = "1.0",
    units: JsonObject = (
        lambda: deepcopy(DEFAULT_CANONICAL_NETWORK_UNITS)
    )(),
    metadata: JsonObject = dict(),
    initial_state: JsonObject = dict(),
    simulation: JsonObject = dict(),
    mapping_hints: JsonObject = dict(),
)

Builder for canonical quantum network JSON configurations.

add_object

add_object(
    section: str, obj: dict[str, Any]
) -> CanonicalNetworkConfigBuilder

Add an object to one of the canonical list sections.

Parameters:

Name Type Description Default
section str

Canonical top-level list section name.

required
obj dict[str, Any]

Object to add to the section.

required

Returns:

Type Description
CanonicalNetworkConfigBuilder

The builder instance for chaining.

Raises:

Type Description
CanonicalNetworkConfigError

If the section name is unsupported.

Source code in src/memq_dqc/network/canonical_config.py
def add_object(
    self,
    section: str,
    obj: dict[str, Any],
) -> CanonicalNetworkConfigBuilder:
    """Add an object to one of the canonical list sections.

    Args:
        section: Canonical top-level list section name.
        obj: Object to add to the section.

    Returns:
        The builder instance for chaining.

    Raises:
        CanonicalNetworkConfigError: If the section name is unsupported.
    """
    if section not in self._sections:
        raise CanonicalNetworkConfigError(
            f"Unsupported canonical section {section!r}."
        )
    self._sections[section].append(_normalize_object(section, obj))
    return self

add_node

add_node(
    *,
    id: str,
    type: str,
    label: str | None = None,
    role: str | None = None,
    position: dict[str, Any] | None = None,
    ports: list[dict[str, Any]] | None = None,
    memory_ids: list[str] | None = None,
    processor_ids: list[str] | None = None,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a node definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_node(
    self,
    *,
    id: str,
    type: str,
    label: str | None = None,
    role: str | None = None,
    position: dict[str, Any] | None = None,
    ports: list[dict[str, Any]] | None = None,
    memory_ids: list[str] | None = None,
    processor_ids: list[str] | None = None,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a node definition."""
    node = _object_with_optional_fields(
        id=id,
        type=type,
        label=label,
        role=role,
        position=position,
        ports=ports,
        memory_ids=memory_ids,
        processor_ids=processor_ids,
        parameters=parameters,
        custom=custom,
    )
    return self.add_object("nodes", node)

add_channel

add_channel(
    *,
    id: str,
    type: str,
    channel_type: str,
    source: str,
    target: str,
    bidirectional: bool | None = None,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    delay_model: dict[str, Any] | None = None,
    loss_model: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a channel definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_channel(
    self,
    *,
    id: str,
    type: str,
    channel_type: str,
    source: str,
    target: str,
    bidirectional: bool | None = None,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    delay_model: dict[str, Any] | None = None,
    loss_model: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a channel definition."""
    channel = _object_with_optional_fields(
        id=id,
        type=type,
        channel_type=channel_type,
        source=source,
        target=target,
        bidirectional=bidirectional,
        parameters=parameters,
        noise_model_id=noise_model_id,
        delay_model=delay_model,
        loss_model=loss_model,
        custom=custom,
    )
    return self.add_object("channels", channel)
add_link(
    *,
    id: str,
    type: str,
    channel_ids: list[str] | None = None,
    node_ids: list[str] | None = None,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a logical link definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_link(
    self,
    *,
    id: str,
    type: str,
    channel_ids: list[str] | None = None,
    node_ids: list[str] | None = None,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a logical link definition."""
    link = _object_with_optional_fields(
        id=id,
        type=type,
        channel_ids=channel_ids,
        node_ids=node_ids,
        parameters=parameters,
        custom=custom,
    )
    return self.add_object("links", link)

add_memory

add_memory(
    *,
    id: str,
    type: str,
    node_id: str,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a quantum memory definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_memory(
    self,
    *,
    id: str,
    type: str,
    node_id: str,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a quantum memory definition."""
    memory = _object_with_optional_fields(
        id=id,
        type=type,
        node_id=node_id,
        parameters=parameters,
        noise_model_id=noise_model_id,
        custom=custom,
    )
    return self.add_object("memories", memory)

add_processor

add_processor(
    *,
    id: str,
    type: str,
    node_id: str,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a processor definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_processor(
    self,
    *,
    id: str,
    type: str,
    node_id: str,
    parameters: dict[str, Any] | None = None,
    noise_model_id: str | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a processor definition."""
    processor = _object_with_optional_fields(
        id=id,
        type=type,
        node_id=node_id,
        parameters=parameters,
        noise_model_id=noise_model_id,
        custom=custom,
    )
    return self.add_object("processors", processor)

add_noise_model

add_noise_model(
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a reusable noise model definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_noise_model(
    self,
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a reusable noise model definition."""
    noise_model = _object_with_optional_fields(
        id=id,
        type=type,
        parameters=parameters,
        custom=custom,
    )
    return self.add_object("noise_models", noise_model)

add_protocol

add_protocol(
    *,
    id: str,
    type: str,
    participants: list[str] | None = None,
    trigger: JsonValue | None = None,
    requirements: JsonValue | None = None,
    parameters: dict[str, Any] | None = None,
    success_conditions: JsonValue | None = None,
    failure_policy: JsonValue | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a protocol definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_protocol(
    self,
    *,
    id: str,
    type: str,
    participants: list[str] | None = None,
    trigger: JsonValue | None = None,
    requirements: JsonValue | None = None,
    parameters: dict[str, Any] | None = None,
    success_conditions: JsonValue | None = None,
    failure_policy: JsonValue | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a protocol definition."""
    protocol = _object_with_optional_fields(
        id=id,
        type=type,
        participants=participants,
        trigger=trigger,
        requirements=requirements,
        parameters=parameters,
        success_conditions=success_conditions,
        failure_policy=failure_policy,
        custom=custom,
    )
    return self.add_object("protocols", protocol)

add_constraint

add_constraint(
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add a constraint definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_constraint(
    self,
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add a constraint definition."""
    constraint = _object_with_optional_fields(
        id=id,
        type=type,
        parameters=parameters,
        custom=custom,
    )
    return self.add_object("constraints", constraint)

add_observable

add_observable(
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder

Add an observable definition.

Source code in src/memq_dqc/network/canonical_config.py
def add_observable(
    self,
    *,
    id: str,
    type: str,
    parameters: dict[str, Any] | None = None,
    custom: JsonValue | None = None,
) -> CanonicalNetworkConfigBuilder:
    """Add an observable definition."""
    observable = _object_with_optional_fields(
        id=id,
        type=type,
        parameters=parameters,
        custom=custom,
    )
    return self.add_object("observables", observable)

set_initial_state

set_initial_state(
    initial_state: dict[str, Any],
) -> CanonicalNetworkConfigBuilder

Set initial network state assumptions.

Source code in src/memq_dqc/network/canonical_config.py
def set_initial_state(
    self,
    initial_state: dict[str, Any],
) -> CanonicalNetworkConfigBuilder:
    """Set initial network state assumptions."""
    self.initial_state = _normalize_top_level_mapping(
        "initial_state",
        initial_state,
    )
    return self

set_simulation

set_simulation(
    simulation: dict[str, Any],
) -> CanonicalNetworkConfigBuilder

Set simulation settings.

Source code in src/memq_dqc/network/canonical_config.py
def set_simulation(
    self,
    simulation: dict[str, Any],
) -> CanonicalNetworkConfigBuilder:
    """Set simulation settings."""
    self.simulation = _normalize_top_level_mapping(
        "simulation",
        simulation,
    )
    return self

set_mapping_hints

set_mapping_hints(
    mapping_hints: dict[str, Any],
) -> CanonicalNetworkConfigBuilder

Set mapping hints for downstream translators.

Source code in src/memq_dqc/network/canonical_config.py
def set_mapping_hints(
    self,
    mapping_hints: dict[str, Any],
) -> CanonicalNetworkConfigBuilder:
    """Set mapping hints for downstream translators."""
    self.mapping_hints = _normalize_top_level_mapping(
        "mapping_hints",
        mapping_hints,
    )
    return self

to_definition

to_definition() -> JsonObject

Return the builder state as a plain definition dictionary.

Source code in src/memq_dqc/network/canonical_config.py
def to_definition(self) -> JsonObject:
    """Return the builder state as a plain definition dictionary."""
    definition: JsonObject = {
        "version": self.version,
        "units": deepcopy(self.units),
        "metadata": deepcopy(self.metadata),
        "initial_state": deepcopy(self.initial_state),
        "simulation": deepcopy(self.simulation),
        "mapping_hints": deepcopy(self.mapping_hints),
    }
    for section, objects in self._sections.items():
        definition[section] = cast(JsonValue, deepcopy(objects))
    return definition

build

build() -> JsonObject

Build, normalize, and validate the current configuration.

Source code in src/memq_dqc/network/canonical_config.py
def build(self) -> JsonObject:
    """Build, normalize, and validate the current configuration."""
    return build_canonical_network_config(self.to_definition())

dumps

dumps(*, indent: int = 2) -> str

Serialize the current configuration to deterministic JSON.

Source code in src/memq_dqc/network/canonical_config.py
def dumps(self, *, indent: int = 2) -> str:
    """Serialize the current configuration to deterministic JSON."""
    return dumps_canonical_network_config(
        self.to_definition(), indent=indent
    )

write

write(output_path: str | Path, *, indent: int = 2) -> Path

Write the current configuration to disk.

Source code in src/memq_dqc/network/canonical_config.py
def write(
    self,
    output_path: str | Path,
    *,
    indent: int = 2,
) -> Path:
    """Write the current configuration to disk."""
    return write_canonical_network_config(
        self.to_definition(),
        output_path,
        indent=indent,
    )

CanonicalNetworkConfigError

Bases: ValueError

Raised when a canonical network configuration is invalid.

NetworkGraph

NetworkGraph(network_json_filename: str)

Represents a quantum network constructed from a JSON specification.

This class parses a network description JSON file and builds a networkx.Graph instance whose nodes represent qubits and whose edges represent local and remote connections between those qubits.

The resulting graph and associated metadata can be accessed via the graph and qubit_type_map properties and are used to derive summary information such as qubit counts per QPU.

Initialize a NetworkGraph from a JSON specification file.

Parameters:

Name Type Description Default
network_json_filename str

The filename of the network specification JSON file.

required
Source code in src/memq_dqc/network/network_graph.py
def __init__(self, network_json_filename: str) -> None:
    """Initialize a NetworkGraph from a JSON specification file.

    Args:
        network_json_filename: The filename of the network specification
            JSON file.
    """
    # Load network specification JSON file
    with open(network_json_filename) as f:
        self._network_data = json.load(f)

    self._graph = nx.Graph()
    self._qubit_type_map: dict[PhysicalQubit, str] = {}
    self._raw_id_to_qubit: dict[int | str, PhysicalQubit] = {}
    self._build_network_graph()

graph property

graph: Graph

Return the underlying NetworkX graph.

qubit_type_map property

qubit_type_map: dict[PhysicalQubit, str]

Return the mapping of qubit IDs to their types.

num_qpus property

num_qpus: int

Return the number of QPUs in the network.

num_total_qubits property

num_total_qubits: int

Return the total number of qubits in the network.

num_comp_qubits property

num_comp_qubits: int

Return the number of computation qubits in the network.

num_comm_qubits property

num_comm_qubits: int

Return the number of communication qubits in the network.

local_swap_dict property

local_swap_dict: dict[
    PhysicalQubit, tuple[float, list[PhysicalQubit]]
]

Return map from comp qubits to swaps toward nearest comm qubit.

is_homogeneous property

is_homogeneous: bool

Return True if all QPUs have identical comp and comm qubit counts.

Returns:

Type Description
bool

True when computation and communication qubit counts match across

bool

all QPUs.

computation_qubits

computation_qubits() -> list[PhysicalQubit]

Return all computation qubit nodes in deterministic order.

Source code in src/memq_dqc/network/network_graph.py
def computation_qubits(self) -> list[PhysicalQubit]:
    """Return all computation qubit nodes in deterministic order."""
    return sorted(
        (
            qubit
            for qubit, qubit_type in self._qubit_type_map.items()
            if qubit_type == "computation"
        ),
        key=_network_qubit_sort_key,
    )

communication_qubits

communication_qubits() -> list[PhysicalQubit]

Return all communication qubit nodes in deterministic order.

Source code in src/memq_dqc/network/network_graph.py
def communication_qubits(self) -> list[PhysicalQubit]:
    """Return all communication qubit nodes in deterministic order."""
    return sorted(
        (
            qubit
            for qubit, qubit_type in self._qubit_type_map.items()
            if qubit_type == "communication"
        ),
        key=_network_qubit_sort_key,
    )

comp_qubits_per_qpu

comp_qubits_per_qpu() -> list[int]

Return the number of computation qubits for each QPU.

Returns:

Type Description
list[int]

Counts of computation qubits per QPU, ordered by processor ID.

Source code in src/memq_dqc/network/network_graph.py
def comp_qubits_per_qpu(self) -> list[int]:
    """Return the number of computation qubits for each QPU.

    Returns:
        Counts of computation qubits per QPU, ordered by processor ID.
    """
    return [
        len(qubit_groups["computation"])
        for qubit_groups in self._processor_qubit_groups()
    ]

comm_qubits_per_qpu

comm_qubits_per_qpu() -> list[int]

Return the number of communication qubits for each QPU.

Returns:

Type Description
list[int]

Counts of communication qubits per QPU, ordered by processor ID.

Source code in src/memq_dqc/network/network_graph.py
def comm_qubits_per_qpu(self) -> list[int]:
    """Return the number of communication qubits for each QPU.

    Returns:
        Counts of communication qubits per QPU, ordered by processor ID.
    """
    return [
        len(qubit_groups["communication"])
        for qubit_groups in self._processor_qubit_groups()
    ]

qpu_ids

qpu_ids() -> list[int]

Return the QPU IDs ordered to match the per-QPU count helpers.

The ordering is identical to comp_qubits_per_qpu and comm_qubits_per_qpu (sorted numerically by processor ID), so a positional index into any of those lists refers to the QPU ID at the same position here. Unlike deriving IDs from the qubit set, this includes every declared processor even one with no qubits, keeping the index-to-QPU mapping stable.

Returns:

Type Description
list[int]

QPU IDs ordered by processor ID.

Source code in src/memq_dqc/network/network_graph.py
def qpu_ids(self) -> list[int]:
    """Return the QPU IDs ordered to match the per-QPU count helpers.

    The ordering is identical to ``comp_qubits_per_qpu`` and
    ``comm_qubits_per_qpu`` (sorted numerically by processor ID), so a
    positional index into any of those lists refers to the QPU ID at the
    same position here. Unlike deriving IDs from the qubit set, this
    includes every declared processor even one with no qubits, keeping
    the index-to-QPU mapping stable.

    Returns:
        QPU IDs ordered by processor ID.
    """
    processors = self._network_data["processors"]
    return [
        _normalize_processor_id(processor_id)
        for processor_id in sorted(
            processors.keys(), key=_processor_sort_key
        )
    ]

get_comm_pair_options

get_comm_pair_options(
    qubit_a: PhysicalQubit, qubit_b: PhysicalQubit
) -> list[
    tuple[
        int,
        tuple[PhysicalQubit, PhysicalQubit],
        tuple[list[PhysicalQubit], list[PhysicalQubit]],
    ]
]

Return reachable communication-pair options sorted by cost.

Parameters:

Name Type Description Default
qubit_a PhysicalQubit

The first computation qubit.

required
qubit_b PhysicalQubit

The second computation qubit.

required

Returns:

Type Description
list[tuple[int, tuple[PhysicalQubit, PhysicalQubit], tuple[list[PhysicalQubit], list[PhysicalQubit]]]]

Ranked communication-pair options sorted by increasing cost and

list[tuple[int, tuple[PhysicalQubit, PhysicalQubit], tuple[list[PhysicalQubit], list[PhysicalQubit]]]]

deterministic label tie-breakers.

Raises:

Type Description
ValueError

If no valid communication pairs exist or no pair is reachable via local paths.

Source code in src/memq_dqc/network/network_graph.py
def get_comm_pair_options(
    self, qubit_a: PhysicalQubit, qubit_b: PhysicalQubit
) -> list[
    tuple[
        int,
        tuple[PhysicalQubit, PhysicalQubit],
        tuple[list[PhysicalQubit], list[PhysicalQubit]],
    ]
]:
    """Return reachable communication-pair options sorted by cost.

    Args:
        qubit_a: The first computation qubit.
        qubit_b: The second computation qubit.

    Returns:
        Ranked communication-pair options sorted by increasing cost and
        deterministic label tie-breakers.

    Raises:
        ValueError: If no valid communication pairs exist or no pair is
            reachable via local paths.
    """
    potential_pairs = self._valid_comm_pairs(qubit_a, qubit_b)
    if not potential_pairs:
        raise ValueError(
            f"No communication pairs found to connect {qubit_a!r} and "
            f"{qubit_b!r}."
        )

    local_graph = self._local_only_graph()
    data_paths_a = self._data_paths_to_comm_qubits(qubit_a, local_graph)
    data_paths_b = self._data_paths_to_comm_qubits(qubit_b, local_graph)

    # Iterate through each set of comm qubit pairs, assemble path options
    pair_options: list[
        tuple[
            int,
            tuple[PhysicalQubit, PhysicalQubit],
            tuple[list[PhysicalQubit], list[PhysicalQubit]],
        ]
    ] = []
    for comm_a, comm_b in potential_pairs:
        option_a = data_paths_a.get(comm_a)
        option_b = data_paths_b.get(comm_b)
        if option_a is None or option_b is None:
            continue
        cost_a, path_a = option_a
        cost_b, path_b = option_b
        pair_options.append(
            (
                cost_a + cost_b,
                (comm_a, comm_b),
                (path_a, path_b),
            )
        )
    if not pair_options:
        raise ValueError(
            f"No reachable communication pairs found to connect {qubit_a!r} "
            f"and {qubit_b!r}."
        )
    # Sort by increasing cost (then by qpu / qubit labels)
    return sorted(
        pair_options,
        key=lambda item: (
            item[0],
            item[1][0].label,
            item[1][1].label,
        ),
    )

get_qpu_route

get_qpu_route(
    source_qpu_id: int, target_qpu_id: int
) -> list[int]

Return a directional QPU route for a routed remote gate.

The route moves the source operand through rswap hops until it is on a QPU adjacent to the target operand. Internal hops must support rswap (2 e-bit pairs), while the final hop to the target side must support a remote gate (1 e-bit pair).

Parameters:

Name Type Description Default
source_qpu_id int

QPU ID of the operand selected to move.

required
target_qpu_id int

QPU ID of the operand kept in place.

required

Returns:

Type Description
list[int]

Ordered QPU IDs from source to target.

Raises:

Type Description
ValueError

If no directional route is available.

Source code in src/memq_dqc/network/network_graph.py
def get_qpu_route(
    self,
    source_qpu_id: int,
    target_qpu_id: int,
) -> list[int]:
    """Return a directional QPU route for a routed remote gate.

    The route moves the source operand through ``rswap`` hops until it is
    on a QPU adjacent to the target operand. Internal hops must support
    ``rswap`` (2 e-bit pairs), while the final hop to the target side
    must support a remote gate (1 e-bit pair).

    Args:
        source_qpu_id: QPU ID of the operand selected to move.
        target_qpu_id: QPU ID of the operand kept in place.

    Returns:
        Ordered QPU IDs from source to target.

    Raises:
        ValueError: If no directional route is available.
    """
    # TODO: right now this is for 'RSWAP' based routing - generalize
    if source_qpu_id == target_qpu_id:
        return [source_qpu_id]

    # Count how many direct remote communication pairs exist between QPUs.
    pair_counts = self._remote_comm_pair_counts()
    direct_key = _ordered_qpu_pair(source_qpu_id, target_qpu_id)
    candidates: list[list[int]] = []

    # A direct remote edge is already a valid route.
    if pair_counts.get(direct_key, 0) >= 1:
        candidates.append([source_qpu_id, target_qpu_id])

    # Otherwise, route to a QPU that can perform the final remote gate
    # into the target, while requiring swap-capable hops beforehand.
    for neighbor_qpu in self._qpu_neighbors_with_min_pairs(
        target_qpu_id,
        min_pairs=1,
        pair_counts=pair_counts,
    ):
        if neighbor_qpu == source_qpu_id:
            continue
        try:
            path_to_neighbor = self._shortest_qpu_path_with_min_pairs(
                source_qpu_id,
                neighbor_qpu,
                min_pairs=2,
                pair_counts=pair_counts,
            )
        except ValueError:
            continue
        # Reject routes that overshoot through the target before the end.
        if target_qpu_id in path_to_neighbor[:-1]:
            continue
        candidates.append(path_to_neighbor + [target_qpu_id])
    if not candidates:
        raise ValueError(
            "No routed remote-gate path found for directional movement: "
            f"{source_qpu_id} -> {target_qpu_id}."
        )

    # Prefer the shortest routed path, then fall back to deterministic ID
    # ordering if multiple candidates have the same length.
    return min(
        candidates,
        key=lambda path: (
            _route_length(path),
            tuple(path),
        ),
    )

remote_gate_ebit_cost

remote_gate_ebit_cost(qpu_a: int, qpu_b: int) -> int

Return minimum raw e-bit pairs for a remote gate between two QPUs.

The gate itself costs one e-bit pair. Reaching an adjacent QPU first costs a remote swap per intermediary, and a remote swap is two pairs, so a route through k intermediaries costs 1 + 2k.

Parameters:

Name Type Description Default
qpu_a int

First QPU ID.

required
qpu_b int

Second QPU ID.

required

Returns:

Type Description
int

Minimum required e-bit pairs.

Raises:

Type Description
ValueError

If no routed remote-gate path is available.

Source code in src/memq_dqc/network/network_graph.py
def remote_gate_ebit_cost(
    self,
    qpu_a: int,
    qpu_b: int,
) -> int:
    """Return minimum raw e-bit pairs for a remote gate between two QPUs.

    The gate itself costs one e-bit pair. Reaching an adjacent QPU first
    costs a remote swap per intermediary, and a remote swap is two pairs,
    so a route through ``k`` intermediaries costs ``1 + 2k``.

    Args:
        qpu_a: First QPU ID.
        qpu_b: Second QPU ID.

    Returns:
        Minimum required e-bit pairs.

    Raises:
        ValueError: If no routed remote-gate path is available.
    """
    if qpu_a == qpu_b:
        return 0

    route_options: list[list[int]] = []
    for source, target in ((qpu_a, qpu_b), (qpu_b, qpu_a)):
        try:
            route_options.append(self.get_qpu_route(source, target))
        except ValueError:
            continue

    if not route_options:
        raise ValueError(
            "No routed remote-gate path found between QPUs "
            f"{qpu_a} and {qpu_b}."
        )

    return min(
        REMOTE_GATE_EBIT_COST
        + (REMOTE_SWAP_EBIT_COST * _route_length(path))
        for path in route_options
    )

remote_swap_ebit_cost

remote_swap_ebit_cost(qpu_a: int, qpu_b: int) -> int

Return routed swap cost between two QPUs.

Every remote swap costs two e-bit pairs, and a route of h hops lowers to h adjacent remote swaps, so the cost is 2h. A swap onto a directly linked QPU is one hop and costs 2; a swap onto a QPU one further along the chain is two hops and costs 4.

Parameters:

Name Type Description Default
qpu_a int

First QPU ID.

required
qpu_b int

Second QPU ID.

required

Returns:

Type Description
int

Routed swap cost in e-bit pairs.

Raises:

Type Description
ValueError

If no swap-capable QPU route is available.

Source code in src/memq_dqc/network/network_graph.py
def remote_swap_ebit_cost(
    self,
    qpu_a: int,
    qpu_b: int,
) -> int:
    """Return routed swap cost between two QPUs.

    Every remote swap costs two e-bit pairs, and a route of ``h`` hops
    lowers to ``h`` adjacent remote swaps, so the cost is ``2h``. A swap
    onto a directly linked QPU is one hop and costs 2; a swap onto a QPU
    one further along the chain is two hops and costs 4.

    Args:
        qpu_a: First QPU ID.
        qpu_b: Second QPU ID.

    Returns:
        Routed swap cost in e-bit pairs.

    Raises:
        ValueError: If no swap-capable QPU route is available.
    """
    if qpu_a == qpu_b:
        return 0

    pair_counts = self._remote_comm_pair_counts()
    path = self._shortest_qpu_path_with_min_pairs(
        source_qpu_id=qpu_a,
        target_qpu_id=qpu_b,
        min_pairs=2,
        pair_counts=pair_counts,
    )
    hops = len(path) - 1
    return REMOTE_SWAP_EBIT_COST * hops

supports_remote_swap

supports_remote_swap(qpu_a: int, qpu_b: int) -> bool

Return whether two QPUs can perform a direct remote swap.

A remote swap teleports both states, so it needs two disjoint communication pairs on a direct link between the two QPUs. A False result rules out a single remote swap only; the two QPUs may still be swappable as a routed chain of adjacent remote swaps, which remote_swap_ebit_cost prices and rejects when unroutable.

Parameters:

Name Type Description Default
qpu_a int

First QPU ID.

required
qpu_b int

Second QPU ID.

required

Returns:

Type Description
bool

True when a direct remote swap is possible.

Source code in src/memq_dqc/network/network_graph.py
def supports_remote_swap(self, qpu_a: int, qpu_b: int) -> bool:
    """Return whether two QPUs can perform a direct remote swap.

    A remote swap teleports both states, so it needs two disjoint
    communication pairs on a direct link between the two QPUs. A False
    result rules out a *single* remote swap only; the two QPUs may still
    be swappable as a routed chain of adjacent remote swaps, which
    [remote_swap_ebit_cost][memq_dqc.network.network_graph.NetworkGraph.remote_swap_ebit_cost] prices and rejects when unroutable.

    Args:
        qpu_a: First QPU ID.
        qpu_b: Second QPU ID.

    Returns:
        True when a direct remote swap is possible.
    """
    if qpu_a == qpu_b:
        return True
    pair_counts = self._remote_comm_pair_counts()
    return pair_counts.get(_ordered_qpu_pair(qpu_a, qpu_b), 0) >= 2

display

display() -> None

Display the network graph using Matplotlib.

Source code in src/memq_dqc/network/network_graph.py
def display(self) -> None:
    """Display the network graph using Matplotlib."""
    local_edges = self._get_local_edges()
    remote_edges = self._get_remote_edges()

    pos = nx.spring_layout(self._graph)
    nx.draw_networkx_nodes(self._graph, pos, node_size=700)
    labels = {node: node.label for node in self._graph.nodes}
    nx.draw_networkx_labels(
        self._graph,
        pos,
        labels=labels,
        font_size=12,
        font_family="sans-serif",
    )
    nx.draw_networkx_edges(
        self._graph,
        pos,
        edgelist=local_edges,
        width=2,
        edge_color="blue",
        label="Local",
        style="solid",
    )

    nx.draw_networkx_edges(
        self._graph,
        pos,
        edgelist=remote_edges,
        width=2,
        edge_color="red",
        label="Remote",
        style="dashed",
    )

    plt.show()

PhysicalQubit dataclass

PhysicalQubit(qpu_id: int, qubit_id: int, qubit_type: str)

Structured identifier for a qubit in a network graph.

is_communication property

is_communication: bool

Return True when this is a communication qubit.

is_computation property

is_computation: bool

Return True when this is a computation qubit.

label property

label: str

Return display label in q/c__ format.

build_canonical_network_config

build_canonical_network_config(
    definition: dict[str, Any],
) -> JsonObject

Normalize and validate a canonical network configuration.

Parameters:

Name Type Description Default
definition dict[str, Any]

In-memory network definition to normalize into the canonical JSON structure.

required

Returns:

Type Description
JsonObject

A validated configuration dictionary with deterministic section

JsonObject

ordering and defaulted top-level sections.

Raises:

Type Description
CanonicalNetworkConfigError

If the definition has invalid structure, unsupported JSON values, or broken cross-references.

Source code in src/memq_dqc/network/canonical_config.py
def build_canonical_network_config(
    definition: dict[str, Any],
) -> JsonObject:
    """Normalize and validate a canonical network configuration.

    Args:
        definition: In-memory network definition to normalize into the
            canonical JSON structure.

    Returns:
        A validated configuration dictionary with deterministic section
        ordering and defaulted top-level sections.

    Raises:
        CanonicalNetworkConfigError: If the definition has invalid structure,
            unsupported JSON values, or broken cross-references.
    """
    if not isinstance(definition, dict):
        raise CanonicalNetworkConfigError(
            "Canonical network definitions must be dictionaries."
        )

    version = definition.get("version", "1.0")
    if not isinstance(version, str) or not version:
        raise CanonicalNetworkConfigError(
            "The top-level 'version' field must be a non-empty string."
        )

    units = _normalize_top_level_mapping(
        "units",
        definition.get("units", DEFAULT_CANONICAL_NETWORK_UNITS),
    )
    normalized_units = dict(DEFAULT_CANONICAL_NETWORK_UNITS)
    normalized_units.update(units)

    metadata = _normalize_top_level_mapping(
        "metadata",
        definition.get("metadata", {}),
    )
    initial_state = _normalize_top_level_mapping(
        "initial_state",
        definition.get("initial_state", {}),
    )
    simulation = _normalize_top_level_mapping(
        "simulation",
        definition.get("simulation", {}),
    )
    mapping_hints = _normalize_top_level_mapping(
        "mapping_hints",
        definition.get("mapping_hints", {}),
    )

    config: JsonObject = {
        "version": version,
        "units": normalized_units,
        "metadata": metadata,
        "initial_state": initial_state,
        "simulation": simulation,
        "mapping_hints": mapping_hints,
    }

    for section in _LIST_SECTIONS:
        config[section] = cast(
            JsonValue,
            _normalize_object_list(
                section,
                definition.get(section, _DEFAULT_TOP_LEVEL_VALUES[section]),
            ),
        )

    validate_canonical_network_config(config)
    return _sorted_config(config)

dumps_canonical_network_config

dumps_canonical_network_config(
    definition: dict[str, Any], *, indent: int = 2
) -> str

Return deterministic JSON for a canonical network configuration.

Parameters:

Name Type Description Default
definition dict[str, Any]

In-memory network definition or already normalized config.

required
indent int

Number of spaces used for indentation.

2

Returns:

Type Description
str

Deterministic JSON with sorted keys.

Source code in src/memq_dqc/network/canonical_config.py
def dumps_canonical_network_config(
    definition: dict[str, Any],
    *,
    indent: int = 2,
) -> str:
    """Return deterministic JSON for a canonical network configuration.

    Args:
        definition: In-memory network definition or already normalized config.
        indent: Number of spaces used for indentation.

    Returns:
        Deterministic JSON with sorted keys.
    """
    config = build_canonical_network_config(definition)
    ordered_config = _ordered_top_level_config(config)
    return json.dumps(ordered_config, indent=indent)

validate_canonical_network_config

validate_canonical_network_config(
    config: dict[str, Any],
) -> None

Validate a canonical network configuration in-place.

Parameters:

Name Type Description Default
config dict[str, Any]

Canonical network configuration to validate.

required

Raises:

Type Description
CanonicalNetworkConfigError

If the configuration is invalid.

Source code in src/memq_dqc/network/canonical_config.py
def validate_canonical_network_config(config: dict[str, Any]) -> None:
    """Validate a canonical network configuration in-place.

    Args:
        config: Canonical network configuration to validate.

    Raises:
        CanonicalNetworkConfigError: If the configuration is invalid.
    """
    _ensure_json_compatible(config, "config")

    ids_by_section: dict[str, set[str]] = {}
    all_ids: set[str] = set()
    for section in _LIST_SECTIONS:
        section_value = config.get(section, [])
        if not isinstance(section_value, list):
            raise CanonicalNetworkConfigError(
                f"The top-level '{section}' section must be a list."
            )
        section_ids: set[str] = set()
        for obj in section_value:
            if not isinstance(obj, dict):
                raise CanonicalNetworkConfigError(
                    f"Entries in '{section}' must be objects."
                )
            object_id = obj["id"]
            if object_id in section_ids:
                raise CanonicalNetworkConfigError(
                    f"Duplicate ID {object_id!r} found in section '{section}'."
                )
            if object_id in all_ids:
                raise CanonicalNetworkConfigError(
                    f"Duplicate ID {object_id!r} found across canonical "
                    "network sections."
                )
            section_ids.add(object_id)
            all_ids.add(object_id)
        ids_by_section[section] = section_ids

    for obj in cast(list[JsonObject], config["nodes"]):
        _validate_reference_list(
            obj,
            field_name="memory_ids",
            target_ids=ids_by_section["memories"],
        )
        _validate_reference_list(
            obj,
            field_name="processor_ids",
            target_ids=ids_by_section["processors"],
        )
        _validate_ports(obj)

    for obj in cast(list[JsonObject], config["channels"]):
        _validate_reference_scalar(
            obj,
            field_name="source",
            target_ids=ids_by_section["nodes"],
        )
        _validate_reference_scalar(
            obj,
            field_name="target",
            target_ids=ids_by_section["nodes"],
        )
        _validate_optional_bool(obj, "bidirectional")

    for obj in cast(list[JsonObject], config["links"]):
        _validate_reference_list(
            obj,
            field_name="channel_ids",
            target_ids=ids_by_section["channels"],
        )
        _validate_reference_list(
            obj,
            field_name="node_ids",
            target_ids=ids_by_section["nodes"],
        )

    for section, field_name in (
        ("memories", "node_id"),
        ("processors", "node_id"),
    ):
        for obj in cast(list[JsonObject], config[section]):
            _validate_reference_scalar(
                obj,
                field_name=field_name,
                target_ids=ids_by_section["nodes"],
            )

    for section in ("memories", "channels", "processors"):
        for obj in cast(list[JsonObject], config[section]):
            _validate_reference_scalar(
                obj,
                field_name="noise_model_id",
                target_ids=ids_by_section["noise_models"],
            )
            _validate_reference_list(
                obj,
                field_name="noise_model_ids",
                target_ids=ids_by_section["noise_models"],
            )

    for obj in cast(list[JsonObject], config["protocols"]):
        _validate_reference_list(
            obj,
            field_name="participants",
            target_ids=all_ids,
        )

    for section in ("units", "metadata", "initial_state", "simulation"):
        if not isinstance(config.get(section, {}), dict):
            raise CanonicalNetworkConfigError(
                f"The top-level '{section}' field must be an object."
            )

    if not isinstance(config.get("mapping_hints", {}), dict):
        raise CanonicalNetworkConfigError(
            "The top-level 'mapping_hints' field must be an object."
        )

write_canonical_network_config

write_canonical_network_config(
    definition: dict[str, Any],
    output_path: str | Path,
    *,
    indent: int = 2,
) -> Path

Write a canonical network configuration to disk.

Parameters:

Name Type Description Default
definition dict[str, Any]

In-memory network definition to serialize.

required
output_path str | Path

Destination file path.

required
indent int

Number of spaces used for indentation.

2

Returns:

Type Description
Path

The resolved path written to disk.

Source code in src/memq_dqc/network/canonical_config.py
def write_canonical_network_config(
    definition: dict[str, Any],
    output_path: str | Path,
    *,
    indent: int = 2,
) -> Path:
    """Write a canonical network configuration to disk.

    Args:
        definition: In-memory network definition to serialize.
        output_path: Destination file path.
        indent: Number of spaces used for indentation.

    Returns:
        The resolved path written to disk.
    """
    resolved_path = Path(output_path)
    resolved_path.write_text(
        dumps_canonical_network_config(definition, indent=indent) + "\n",
        encoding="utf-8",
    )
    return resolved_path

generate_network

generate_network(
    num_qpus: int,
    computation_qubits_per_qpu: int,
    arrangement: QpuArrangement
    | Sequence[tuple[int, int]] = "chain",
    *,
    intra_qpu: IntraQpuConnectivity = "nearest_neighbor",
    links_per_pair: int = 2,
    coherence_time: float = 100.0,
) -> dict[str, Any]

Generate a network topology with identically sized QPUs.

Parameters:

Name Type Description Default
num_qpus int

Number of QPUs, with ids 0 to num_qpus - 1.

required
computation_qubits_per_qpu int

Computation (data) qubits on every QPU.

required
arrangement QpuArrangement | Sequence[tuple[int, int]]

How the QPUs are linked. "chain" links QPU i to i + 1; "ring" also links the last QPU to QPU 0; "hub" links QPU 0 to every other QPU; "all_to_all" links every pair. Alternatively, an explicit sequence of (qpu_a, qpu_b) pairs.

'chain'
intra_qpu IntraQpuConnectivity

Coupling between qubits inside each QPU, either "nearest_neighbor" or "all_to_all".

'nearest_neighbor'
links_per_pair int

Remote links between each pair of linked QPUs. Use at least 2 so qubits can be teleported across a link, which routing between QPUs that are not directly linked requires.

2
coherence_time float

Coherence time recorded on every qubit, in microseconds. No current algorithm reads it.

100.0

Returns:

Type Description
dict[str, Any]

The network as a JSON-serializable dictionary, in the format

dict[str, Any]

NetworkGraph loads.

Raises:

Type Description
ValueError

If a count is below 1, the arrangement is unknown or needs more QPUs, or the QPU links reference unknown QPUs, contain a self-link, or leave a QPU unreachable.

Source code in src/memq_dqc/network/generation.py
def generate_network(
    num_qpus: int,
    computation_qubits_per_qpu: int,
    arrangement: QpuArrangement | Sequence[tuple[int, int]] = "chain",
    *,
    intra_qpu: IntraQpuConnectivity = "nearest_neighbor",
    links_per_pair: int = 2,
    coherence_time: float = 100.0,
) -> dict[str, Any]:
    """Generate a network topology with identically sized QPUs.

    Args:
        num_qpus: Number of QPUs, with ids ``0`` to ``num_qpus - 1``.
        computation_qubits_per_qpu: Computation (data) qubits on every QPU.
        arrangement: How the QPUs are linked. ``"chain"`` links QPU ``i`` to
            ``i + 1``; ``"ring"`` also links the last QPU to QPU 0;
            ``"hub"`` links QPU 0 to every other QPU; ``"all_to_all"``
            links every pair. Alternatively, an explicit sequence of
            ``(qpu_a, qpu_b)`` pairs.
        intra_qpu: Coupling between qubits inside each QPU, either
            ``"nearest_neighbor"`` or ``"all_to_all"``.
        links_per_pair: Remote links between each pair of linked QPUs. Use
            at least 2 so qubits can be teleported across a link, which
            routing between QPUs that are not directly linked requires.
        coherence_time: Coherence time recorded on every qubit, in
            microseconds. No current algorithm reads it.

    Returns:
        The network as a JSON-serializable dictionary, in the format
        ``NetworkGraph`` loads.

    Raises:
        ValueError: If a count is below 1, the arrangement is unknown or
            needs more QPUs, or the QPU links reference unknown QPUs,
            contain a self-link, or leave a QPU unreachable.
    """
    if num_qpus < 1:
        raise ValueError("num_qpus must be at least 1.")
    if computation_qubits_per_qpu < 1:
        raise ValueError("computation_qubits_per_qpu must be at least 1.")
    if links_per_pair < 1:
        raise ValueError("links_per_pair must be at least 1.")

    qpu_links = _qpu_links(num_qpus, arrangement)
    neighbors: dict[int, list[int]] = {qpu: [] for qpu in range(num_qpus)}
    for a, b in qpu_links:
        neighbors[a].append(b)
        neighbors[b].append(a)
    for linked in neighbors.values():
        linked.sort()
    n_comp = computation_qubits_per_qpu

    local_edges = _computation_edges(n_comp, intra_qpu)
    boundary = _grid_boundary(n_comp)

    processors: dict[str, Any] = {}
    qubits: dict[str, Any] = {}
    local_connections: list[tuple[str, str]] = []
    for qpu in range(num_qpus):
        n_comm = links_per_pair * len(neighbors[qpu])
        comp_ids = [_qubit_id("q", qpu, i) for i in range(n_comp)]
        comm_ids = [_qubit_id("c", qpu, j) for j in range(n_comm)]
        processors[str(qpu)] = {
            "id": qpu,
            "qubits": {"computation": comp_ids, "communication": comm_ids},
        }

        adjacency: dict[str, list[str]] = {q: [] for q in comp_ids + comm_ids}
        for a, b in local_edges:
            _couple(adjacency, local_connections, comp_ids[a], comp_ids[b])
        for j, comm in enumerate(comm_ids):
            if intra_qpu == "all_to_all":
                attached = comp_ids
            else:
                attached = [comp_ids[boundary[j * len(boundary) // n_comm]]]
            for comp in attached:
                _couple(adjacency, local_connections, comm, comp)

        for index, qubit in enumerate(comp_ids + comm_ids):
            qubits[qubit] = _qubit_entry(
                qubit,
                "computation" if index < n_comp else "communication",
                qpu,
                index,
                sorted(adjacency[qubit], key=_qubit_sort_key),
                coherence_time,
            )

    remote_connections: list[dict[str, Any]] = []
    for a, b in qpu_links:
        for k in range(links_per_pair):
            comm_a = _qubit_id(
                "c", a, neighbors[a].index(b) * links_per_pair + k
            )
            comm_b = _qubit_id(
                "c", b, neighbors[b].index(a) * links_per_pair + k
            )
            qubits[comm_a]["remoteConnections"].append(comm_b)
            qubits[comm_b]["remoteConnections"].append(comm_a)
            remote_connections.append(
                {
                    "qubit1": comm_a,
                    "qubit2": comm_b,
                    "type": "remote",
                    "fidelity": 1,
                }
            )

    connections = [
        {"qubit1": a, "qubit2": b, "type": "local"}
        for a, b in local_connections
    ] + remote_connections
    return {
        "processors": processors,
        "qubits": qubits,
        "connections": connections,
    }

validate_network

validate_network(network: Mapping[str, Any]) -> None

Check that a network topology is structurally sound.

Checks that:

  • every QPU in processors is keyed by its numeric id;
  • every qubit has a valid type and belongs to exactly one QPU, the one its processorId names;
  • local connections join qubits on the same QPU;
  • remote connections join communication qubits on different QPUs;
  • every connection references a known qubit and is listed on both ends.

Parameters:

Name Type Description Default
network Mapping[str, Any]

The parsed network JSON.

required

Raises:

Type Description
ValueError

If the network is malformed. The message lists every problem found.

Source code in src/memq_dqc/network/validation.py
def validate_network(network: Mapping[str, Any]) -> None:
    """Check that a network topology is structurally sound.

    Checks that:

    - every QPU in ``processors`` is keyed by its numeric ``id``;
    - every qubit has a valid ``type`` and belongs to exactly one QPU, the
      one its ``processorId`` names;
    - local connections join qubits on the same QPU;
    - remote connections join communication qubits on different QPUs;
    - every connection references a known qubit and is listed on both ends.

    Args:
        network: The parsed network JSON.

    Raises:
        ValueError: If the network is malformed. The message lists every
            problem found.
    """
    processors = network.get("processors")
    qubits = network.get("qubits")
    if not (
        isinstance(processors, Mapping)
        and processors
        and isinstance(qubits, Mapping)
        and qubits
    ):
        raise ValueError(
            "Invalid network: 'processors' and 'qubits' must both be "
            "non-empty objects."
        )

    problems: list[str] = []
    owner = _check_processors(processors, problems)
    entries: dict[str, Mapping[str, Any]] = {}
    for key, entry in qubits.items():
        if isinstance(entry, Mapping):
            entries[_id(key)] = entry
        else:
            problems.append(f"Qubit {key!r} must be an object.")
    for qubit, entry in entries.items():
        _check_qubit(qubit, entry, owner, problems)
    for qubit in owner:
        if qubit not in entries:
            problems.append(f"QPU lists unknown qubit {qubit!r}.")
    for qubit, entry in entries.items():
        _check_connections(qubit, entry, entries, problems)

    if problems:
        raise ValueError(_message(problems))