Skip to content

memq_dqc.circuit

circuit

Circuit-level data structures.

Circuit

Circuit(program_or_path: str | Program)

Primary circuit model for memq_dqc.

A Circuit owns grouped monolithic and distributed representations. The monolithic representation is always populated at construction time. The distributed representation is populated on demand after partitioning and extraction.

Initialize a circuit from a program or QASM file path.

Parameters:

Name Type Description Default
program_or_path str | Program

Parsed OpenQASM 3 program or filesystem path.

required
Source code in src/memq_dqc/circuit/circuit.py
def __init__(self, program_or_path: str | ast.Program) -> None:
    """Initialize a circuit from a program or QASM file path.

    Args:
        program_or_path: Parsed OpenQASM 3 program or filesystem path.
    """
    if isinstance(program_or_path, ast.Program):
        program = program_or_path
    else:
        program = load_qasm_program(program_or_path)

    statements = extract_program_statements(program)
    validate_register_names(statements)
    # TODO: think about how to make this easier to access (currently circuit.mono.program)
    ops = extract_ops(statements)
    if any(op.cat_proxy_x for op in ops):
        raise ValueError(
            "The @memq.cat_proxy_x annotation is reserved for emitted "
            "distributed circuits, not monolithic compiler inputs."
        )
    self.mono = MonoCircuit(
        program=program,
        statements=statements,
        ops=ops,
        num_two_qubit_gates=count_two_qubit_ops(ops),
        dag=CircuitDAG(ops),
    )
    self.distributed: DistributedCircuit | None = None

build_distributed

build_distributed(
    remote_statement_ids: set[int],
    swaps_schedule: list[list[SwapOp]],
    windows: list[list[Op]],
    schedule: list[dict[QPU, set[int]]],
    network: NetworkGraph,
    comp_qubits_per_qpu: list[int] | None = None,
    comm_qubits_per_qpu: list[int] | None = None,
    ebit_assignment: bool = True,
    gate_group_op_ids: tuple[tuple[int, ...], ...] = (),
) -> DistributedCircuit

Populate the distributed representation for this circuit.

Parameters:

Name Type Description Default
remote_statement_ids set[int]

Statement indices to rename as remote gates.

required
swaps_schedule list[list[SwapOp]]

Swap operations organized by scheduling windows.

required
windows list[list[Op]]

Operation windows for distributed execution.

required
schedule list[dict[QPU, set[int]]]

Per-window QPU assignments for logical qubits.

required
network NetworkGraph

Network graph used to route communication.

required
comp_qubits_per_qpu list[int] | None

Optional computation-qubit capacities by QPU.

None
comm_qubits_per_qpu list[int] | None

Optional communication-qubit capacities by QPU.

None
ebit_assignment bool

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

True
gate_group_op_ids tuple[tuple[int, ...], ...]

Operation IDs for detected gate groups that may share cat-entanglement in the emitted program.

()

Returns:

Type Description
DistributedCircuit

The populated distributed circuit representation.

Source code in src/memq_dqc/circuit/circuit.py
def build_distributed(
    self,
    remote_statement_ids: set[int],
    swaps_schedule: list[list[SwapOp]],
    windows: list[list[Op]],
    schedule: list[dict[QPU, set[int]]],
    network: NetworkGraph,
    comp_qubits_per_qpu: list[int] | None = None,
    comm_qubits_per_qpu: list[int] | None = None,
    ebit_assignment: bool = True,
    gate_group_op_ids: tuple[tuple[int, ...], ...] = (),
) -> DistributedCircuit:
    """Populate the distributed representation for this circuit.

    Args:
        remote_statement_ids: Statement indices to rename as remote gates.
        swaps_schedule: Swap operations organized by scheduling windows.
        windows: Operation windows for distributed execution.
        schedule: Per-window QPU assignments for logical qubits.
        network: Network graph used to route communication.
        comp_qubits_per_qpu: Optional computation-qubit capacities by QPU.
        comm_qubits_per_qpu: Optional communication-qubit capacities by
            QPU.
        ebit_assignment: Whether the compiler assigns concrete e-bit
            pairs into the scheduler DAG. If false, schedulers choose from
            viable e-bit pair candidates.
        gate_group_op_ids: Operation IDs for detected gate groups that may
            share cat-entanglement in the emitted program.

    Returns:
        The populated distributed circuit representation.
    """
    statements, num_local_swaps_added = build_distributed_statements(
        statements=self.mono.statements,
        remote_statement_ids=remote_statement_ids,
        windows=windows,
        swaps_schedule=swaps_schedule,
        schedule=schedule,
        network=network,
        comp_qubits_per_qpu=comp_qubits_per_qpu,
        comm_qubits_per_qpu=comm_qubits_per_qpu,
        ebit_assignment=ebit_assignment,
        gate_group_op_ids=gate_group_op_ids,
    )
    ops = extract_ops(statements)
    ebit_candidates_by_op_id = (
        None
        if ebit_assignment
        else _build_ebit_candidates_by_op_id(ops, network)
    )
    distributed_program = ast.Program(
        version=self.mono.program.version,
        statements=[statement.node for statement in statements],
    )
    distributed = DistributedCircuit(
        program=distributed_program,
        statements=statements,
        ops=ops,
        num_two_qubit_gates=count_two_qubit_ops(ops),
        num_remote_gates=count_remote_gates(ops),
        num_local_swaps_added=num_local_swaps_added,
        dag=DistributedCircuitDAG(
            ops,
            ignore_remote_ebit_dependencies=not ebit_assignment,
        ),
        ebit_candidates_by_op_id=ebit_candidates_by_op_id,
    )
    self.distributed = distributed
    return distributed

DistributedCircuit dataclass

DistributedCircuit(
    program: Program,
    statements: list[CleanedStatement],
    ops: list[Op],
    num_two_qubit_gates: int,
    num_remote_gates: int,
    num_local_swaps_added: int,
    dag: DistributedCircuitDAG,
    ebit_candidates_by_op_id: EbitCandidatesByOpId
    | None = None,
)

Distributed circuit representation and associated metadata.

Attributes:

Name Type Description
program Program

Parsed OpenQASM 3 program for the distributed circuit.

statements list[CleanedStatement]

Cleaned distributed statements in emitted order.

ops list[Op]

Operations extracted for the distributed circuit.

num_two_qubit_gates int

Number of two-qubit operations in the circuit.

num_remote_gates int

Number of operations marked as remote gates.

num_local_swaps_added int

Number of local swaps inserted during routing.

dag DistributedCircuitDAG

DAG derived from the distributed operations.

ebit_candidates_by_op_id EbitCandidatesByOpId | None

Optional scheduler-facing e-bit candidates for remote operations when e-bit assignment is deferred.

MonoCircuit dataclass

MonoCircuit(
    program: Program,
    statements: list[CleanedStatement],
    ops: list[Op],
    num_two_qubit_gates: int,
    dag: CircuitDAG,
)

Monolithic (original) circuit representation and associated metadata.

Attributes:

Name Type Description
program Program

Parsed OpenQASM 3 program for the original circuit.

statements list[CleanedStatement]

Cleaned program statements in source order.

ops list[Op]

Operations extracted from the cleaned statements.

num_two_qubit_gates int

Number of two-qubit operations in the circuit.

dag CircuitDAG

DAG derived from ops.

CircuitDAG

CircuitDAG(ops: list[Op])

Directed acyclic graph for a circuit's operations.

The DAG captures dependencies between operations and provides layered views suitable for scheduling and partitioning. Circuit-level metadata such as statements and operation lists live on the higher-level circuit model rather than on this DAG.

Initialize the DAG representation for operations in source order.

Parameters:

Name Type Description Default
ops list[Op]

Operations in source order.

required
Source code in src/memq_dqc/circuit/dag/mono.py
def __init__(self, ops: list[Op]) -> None:
    """Initialize the DAG representation for operations in source order.

    Args:
        ops: Operations in source order.
    """
    self._ops = ops
    self.graph: nx.DiGraph = self._build_dag()
    self.layers: list[Layer] = self._extract_layers()
    self.depth = len(self.layers)

iter_topological

iter_topological() -> Iterator[Op]

Return operations in dependency-respecting topological order.

Yields:

Type Description
Op

Operations ordered so each operation appears after all of its DAG

Op

predecessors.

Source code in src/memq_dqc/circuit/dag/mono.py
def iter_topological(self) -> Iterator[Op]:
    """Return operations in dependency-respecting topological order.

    Yields:
        Operations ordered so each operation appears after all of its DAG
        predecessors.
    """
    for node_id in nx.topological_sort(self.graph):
        yield self.graph.nodes[node_id]["op"]

DistributedCircuitDAG

DistributedCircuitDAG(
    ops: list[Op],
    *,
    ignore_remote_ebit_dependencies: bool = False,
)

Bases: CircuitDAG

DAG representation for distributed circuit operations.

Inherits methods and attributes from base CircuitDAG, and adds a few distributed-specific utilities and attributes.

Initialize a distributed DAG.

Parameters:

Name Type Description Default
ops list[Op]

Distributed operations in source order.

required
ignore_remote_ebit_dependencies bool

Whether remote-operation communication operands should be ignored for dependency edges.

False
Source code in src/memq_dqc/circuit/dag/distributed.py
def __init__(
    self,
    ops: list[Op],
    *,
    ignore_remote_ebit_dependencies: bool = False,
) -> None:
    """Initialize a distributed DAG.

    Args:
        ops: Distributed operations in source order.
        ignore_remote_ebit_dependencies: Whether remote-operation
            communication operands should be ignored for dependency edges.
    """
    self.ignore_remote_ebit_dependencies = ignore_remote_ebit_dependencies
    super().__init__(ops)

Layer dataclass

Layer(ops: tuple[Op, ...])

Bases: Sequence[Op]

A layer of operations that can be executed in parallel.

Attributes:

Name Type Description
ops tuple[Op, ...]

Operations contained in the layer, in scheduling order.

qubits property

qubits: list[int]

Return the sorted unique qubits used by the layer.

Returns:

Type Description
list[int]

Sorted unique qubit indices used by operations in the layer.

Op dataclass

Op(
    op_id: int,
    statement_id: int,
    name: str,
    is_remote: bool,
    qubits: tuple[CircuitQubit, ...],
    node: QASMNode,
)

A quantum operation in the DAG extracted from an OpenQASM circuit.

Attributes:

Name Type Description
op_id int

Unique index of the operation in the extracted ops list.

statement_id int

Index of the statement in the original program.

name str

Gate or instruction name.

is_remote bool

Whether the operation is a remote distributed operation.

qubits tuple[CircuitQubit, ...]

Qubits the operation applies to.

node QASMNode

Original OpenQASM AST node.

cat_proxy_x property

cat_proxy_x: bool

Return whether this gate also requires X on its live cat proxy.

The annotation persists in OpenQASM when communication-qubit assignment is deferred. It refers to the remote half of the enclosing catent group's selected e-bit, not the measured local Bell half. The original X/Y still acts once on its data operand.

is_two_qubit property

is_two_qubit: bool

Return True when the operation acts on two qubits.

Returns:

Type Description
bool

True if the operation spans two qubits, otherwise False.

qubit_indices property

qubit_indices: tuple[int, ...]

Return the integer indices of the operation's qubits.

Returns:

Type Description
tuple[int, ...]

CircuitQubit indices in operation order.

ebit_pairs property

ebit_pairs: (
    tuple[tuple[PhysicalQubit, PhysicalQubit], ...] | None
)

Return the physical communication-qubit e-bit pairs for a remote op.

Returns:

Type Description
tuple[tuple[PhysicalQubit, PhysicalQubit], ...] | None

None for non-remote operations. For remote two-qubit gates,

tuple[tuple[PhysicalQubit, PhysicalQubit], ...] | None

returns one pair of physical communication qubits. For rswap,

tuple[tuple[PhysicalQubit, PhysicalQubit], ...] | None

returns two physical communication-qubit pairs.

Raises:

Type Description
ValueError

If a remote operation does not contain the expected communication-qubit payload.

build_circuit

build_circuit(program_or_path: str | Program) -> Circuit

Build a Circuit from a program or QASM file path.

Parameters:

Name Type Description Default
program_or_path str | Program

OpenQASM 3 program or filesystem path.

required

Returns:

Type Description
Circuit

The constructed Circuit.

Source code in src/memq_dqc/circuit/circuit.py
def build_circuit(program_or_path: str | ast.Program) -> Circuit:
    """Build a Circuit from a program or QASM file path.

    Args:
        program_or_path: OpenQASM 3 program or filesystem path.

    Returns:
        The constructed Circuit.
    """
    return Circuit(program_or_path)

annotated_dag_to_json

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

Serialize an annotated distributed-DAG graph to a JSON document.

This is an opt-in helper; building the graph never serializes automatically. The document mirrors the node and edge attributes baked on by build_annotated_dag; the raw operation object and its AST node are intentionally omitted.

Parameters:

Name Type Description Default
graph DiGraph

An annotated graph produced by build_annotated_dag.

required
path str | PathLike[str] | None

Optional destination file. When given, the JSON document is written there as UTF-8 text in addition to being returned.

None
indent int | None

Indentation forwarded to json.dumps. 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/circuit/dag/annotated.py
def annotated_dag_to_json(
    graph: nx.DiGraph,
    path: str | PathLike[str] | None = None,
    *,
    indent: int | None = 2,
) -> str:
    """Serialize an annotated distributed-DAG graph to a JSON document.

    This is an opt-in helper; building the graph never serializes
    automatically. The document mirrors the node and edge attributes baked on
    by [build_annotated_dag][memq_dqc.circuit.dag.annotated.build_annotated_dag]; the raw operation object and its AST node
    are intentionally omitted.

    Args:
        graph: An annotated graph produced by [build_annotated_dag][memq_dqc.circuit.dag.annotated.build_annotated_dag].
        path: Optional destination file. When given, the JSON document is
            written there as UTF-8 text in addition to being returned.
        indent: Indentation forwarded to `json.dumps`. Pass ``None`` for
            the most compact single-line output.

    Returns:
        The JSON document as a string.
    """
    document = json.dumps(_graph_to_dict(graph), indent=indent)
    if path is not None:
        Path(path).write_text(document, encoding="utf-8")
    return document

build_annotated_dag

build_annotated_dag(
    distributed: DistributedCircuit,
) -> DiGraph

Build an annotated distributed-DAG graph for a compiled circuit.

Constructs a brand-new networkx.DiGraph that mirrors the dependency structure of distributed.dag and annotates each node and edge with execution detail. The source circuit and its DAG are only read; nothing is mutated.

Parameters:

Name Type Description Default
distributed DistributedCircuit

The compiled distributed circuit to derive the graph from.

required

Returns:

Type Description
DiGraph

A directed acyclic graph whose nodes are keyed by op_id and whose

DiGraph

node/edge attributes carry the annotated execution detail.

Source code in src/memq_dqc/circuit/dag/annotated.py
def build_annotated_dag(distributed: DistributedCircuit) -> nx.DiGraph:
    """Build an annotated distributed-DAG graph for a compiled circuit.

    Constructs a brand-new `networkx.DiGraph` that mirrors the
    dependency structure of ``distributed.dag`` and annotates each node and
    edge with execution detail. The source circuit and its DAG are only read;
    nothing is mutated.

    Args:
        distributed: The compiled distributed circuit to derive the graph from.

    Returns:
        A directed acyclic graph whose nodes are keyed by ``op_id`` and whose
        node/edge attributes carry the annotated execution detail.
    """
    group_by_op_id = _assign_group_ids(distributed.ops)
    ebit_candidates_by_op_id = distributed.ebit_candidates_by_op_id or {}
    source_graph = distributed.dag.graph

    graph = nx.DiGraph()
    graph.graph["type"] = _GRAPH_TYPE
    # Older consumers must not silently discard a required proxy action.
    graph.graph["schema_version"] = (
        2 if any(op.cat_proxy_x for op in distributed.ops) else _SCHEMA_VERSION
    )

    for node_id in source_graph.nodes:
        op = source_graph.nodes[node_id]["op"]
        data_qubits, comm_qubits = _op_split_qubits(op)
        graph.add_node(
            op.op_id,
            op=op,
            op_id=op.op_id,
            op_type=_op_type(op),
            name=op.name,
            statement_id=op.statement_id,
            is_remote=op.is_remote,
            is_two_qubit=len(data_qubits) == 2,
            group_id=group_by_op_id.get(op.op_id),
            cat_proxy_x=op.cat_proxy_x,
            logical_qubits=data_qubits,
            physical_qubits=tuple(_physical_qubit(q) for q in data_qubits),
            comm_qubits=tuple(_physical_qubit(q) for q in comm_qubits),
            ebit_pairs=_ebit_pairs(comm_qubits),
            ebit_candidates=ebit_candidates_by_op_id.get(op.op_id),
            hardware={},
        )

    for source_id, target_id, edge_data in source_graph.edges(data=True):
        source_op = source_graph.nodes[source_id]["op"]
        target_op = source_graph.nodes[target_id]["op"]
        shared_qubits = tuple(
            sorted(
                edge_data["qubits"],
                key=lambda qubit: (qubit.register_name, qubit.index),
            )
        )
        graph.add_edge(
            source_id,
            target_id,
            qubits=shared_qubits,
            is_cross_qpu=_is_cross_qpu(source_op, target_op),
            hardware={},
        )

    return graph