Skip to content

memq_dqc

memq_dqc

Public package interface for memq_dqc.

This module exposes the core workflow objects and configuration types needed for distributed quantum compilation. The recommended entry point is Compiler (compile -> verify) together with Scheduler; Compiler wraps the lower-level Partitioner, which stays available for callers who want direct control over partitioning. Supporting helpers remain importable from their own subpackages (e.g. memq_dqc.network, memq_dqc.verify).

Compiler

Compiler(
    circuit: ProgramInput,
    topology: NetworkInput,
    algo: str
    | type[BasePartitioner]
    | BasePartitioner = "interaction",
    *,
    algo_kwargs: dict[str, Any] | None = None,
)

Compile a circuit for a distributed quantum network.

This is the recommended entry point for end users. Construct it with a circuit and a network topology, then call compile; the distributed circuit and its derived artifacts are then available as properties. Under the hood it drives a Partitioner, which can also be used directly for finer control over partitioning.

Initialize the compiler.

Parameters:

Name Type Description Default
circuit ProgramInput

The input circuit, as a parsed OpenQASM 3 program, a path to a .qasm/.qasm3 file, or inline OpenQASM source text.

required
topology NetworkInput

The network topology, as a NetworkGraph or a path to its .json description.

required
algo str | type[BasePartitioner] | BasePartitioner

Partitioning 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/compiler.py
def __init__(
    self,
    circuit: ProgramInput,
    topology: NetworkInput,
    algo: str | type[BasePartitioner] | BasePartitioner = "interaction",
    *,
    algo_kwargs: dict[str, Any] | None = None,
) -> None:
    """Initialize the compiler.

    Args:
        circuit: The input circuit, as a parsed OpenQASM 3 program, a path
            to a ``.qasm``/``.qasm3`` file, or inline OpenQASM source text.
        topology: The network topology, as a ``NetworkGraph`` or a path to
            its ``.json`` description.
        algo: Partitioning algorithm name, class, or preconfigured
            instance.
        algo_kwargs: Keyword arguments forwarded to the algorithm.
    """
    self._partitioner = Partitioner(
        topology, circuit, algo=algo, algo_kwargs=algo_kwargs
    )
    # Deterministic signature of a caller-injected placement, folded into
    # the scheduling-instance fingerprint. ``None`` on the normal compile
    # path so its fingerprint is unaffected.
    self._injected_placement_signature: dict[str, Any] | None = None

partitioner property

partitioner: Partitioner

Return the underlying partitioner driving this compiler.

network property

network: NetworkGraph

Return the network graph used by this compiler.

circuit property

circuit: Circuit

Return the circuit model for the input program.

cost property

cost: float | None

Return the latest entanglement cost, if available.

distributed_circuit property

distributed_circuit: DistributedCircuit

Return the distributed circuit, extracting it on first access.

Raises:

Type Description
ValueError

If the circuit has not been compiled yet.

RuntimeError

If extraction does not populate the circuit.

distributed_program property

distributed_program: Program

Return the distributed OpenQASM program.

distributed_qasm property

distributed_qasm: str

Return the distributed circuit as OpenQASM 3 source text.

compile

compile(
    *,
    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

Compile the circuit for the configured network.

Runs partitioning and reconstructs the distributed circuit. After this call, distributed_circuit, distributed_qasm, and the other result properties are available.

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, partitioning runs and extraction is deferred until the distributed circuit is first accessed.

None
group_gates bool

Whether to 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'
Source code in src/memq_dqc/compiler.py
def compile(
    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:
    """Compile the circuit for the configured network.

    Runs partitioning and reconstructs the distributed circuit. After this
    call, [distributed_circuit][memq_dqc.compiler.Compiler.distributed_circuit], [distributed_qasm][memq_dqc.compiler.Compiler.distributed_qasm], and the
    other result properties are available.

    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,
            partitioning runs and extraction is deferred until the
            distributed circuit is first accessed.
        group_gates: Whether to 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.
    """
    self._partitioner.run(
        ebit_assignment=ebit_assignment,
        group_gates=group_gates,
        max_group_size=max_group_size,
        group_size_profile=group_size_profile,
        verbosity=verbosity,
    )

save_distributed_circuit

save_distributed_circuit(path: str | Path) -> Path

Write the distributed circuit to an OpenQASM 3 file.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required

Returns:

Type Description
Path

The path the circuit was written to.

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

    Args:
        path: Destination file path.

    Returns:
        The path the circuit was written to.
    """
    return self._partitioner.save_distributed_circuit(path)

annotated_dag

annotated_dag() -> DiGraph

Return the compiled program as an annotated distributed DAG.

Opt-in export; compiling never builds this automatically. A fresh annotated networkx.DiGraph is constructed on each call. See memq_dqc.circuit.dag.build_annotated_dag for the node and edge attributes.

Returns:

Type Description
DiGraph

An annotated networkx.DiGraph of the distributed circuit.

Source code in src/memq_dqc/compiler.py
def annotated_dag(self) -> nx.DiGraph:
    """Return the compiled program as an annotated distributed DAG.

    Opt-in export; compiling never builds this automatically. A fresh
    annotated `networkx.DiGraph` is constructed on each call. See
    [memq_dqc.circuit.dag.build_annotated_dag][memq_dqc.circuit.dag.annotated.build_annotated_dag] for the node and edge
    attributes.

    Returns:
        An annotated `networkx.DiGraph` of the distributed circuit.
    """
    return self._partitioner.annotated_dag()

to_dag_json

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

Serialize the annotated distributed DAG to a JSON document.

Opt-in export; compiling never serializes automatically. See memq_dqc.circuit.dag.annotated_dag_to_json for the document layout.

Parameters:

Name Type Description Default
path str | Path | 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/compiler.py
def to_dag_json(
    self,
    path: str | Path | None = None,
    *,
    indent: int | None = 2,
) -> str:
    """Serialize the annotated distributed DAG to a JSON document.

    Opt-in export; compiling 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.

    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.
    """
    return self._partitioner.to_dag_json(path, indent=indent)

get_verification_artifacts

get_verification_artifacts() -> VerificationArtifacts

Return original and distributed circuit verification inputs.

The returned OpenQASM programs can be passed directly to memq_dqc.verify.verify_distributed_circuit. The DAGs are independent NetworkX graph objects suitable for structural checks.

Returns:

Type Description
VerificationArtifacts

Original and distributed OpenQASM programs, source strings, and

VerificationArtifacts

DAGs.

Raises:

Type Description
ValueError

If the circuit has not been compiled yet.

Source code in src/memq_dqc/compiler.py
def get_verification_artifacts(self) -> VerificationArtifacts:
    """Return original and distributed circuit verification inputs.

    The returned OpenQASM programs can be passed directly to
    [memq_dqc.verify.verify_distributed_circuit][memq_dqc.verify.verify.verify_distributed_circuit]. The DAGs are
    independent NetworkX graph objects suitable for structural checks.

    Returns:
        Original and distributed OpenQASM programs, source strings, and
        DAGs.

    Raises:
        ValueError: If the circuit has not been compiled yet.
    """
    original_program = self.circuit.mono.program
    distributed_program = self.distributed_program
    return VerificationArtifacts(
        original_program=original_program,
        original_qasm=dump_qasm_program(original_program),
        original_dag=self.circuit.mono.dag.graph.copy(),
        distributed_program=distributed_program,
        distributed_qasm=dump_qasm_program(distributed_program),
        distributed_dag=self.annotated_dag(),
    )

verify

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

Verify the distributed circuit against the original circuit.

See memq_dqc.partition.Partitioner.verify for details.

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/compiler.py
def verify(
    self,
    *,
    shots: int = 50000000,
    fidelity_threshold: float = 0.90,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> bool:
    """Verify the distributed circuit against the original circuit.

    See [memq_dqc.partition.Partitioner.verify][memq_dqc.partition.partitioner.Partitioner.verify] for details.

    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.
    """
    return self._partitioner.verify(
        shots=shots,
        fidelity_threshold=fidelity_threshold,
        verbosity=verbosity,
    )

to_scheduling_instance

to_scheduling_instance(
    *,
    hardware_profile: SchedulerHardwareProfile
    | None = None,
) -> SchedulingInstance

Build a scheduling instance from the existing distributed result.

Opt-in export for external RL schedulers. Uses the already-compiled distributed circuit (extracting it on first access if compilation has occurred) and does not rerun partitioning. Compile the circuit first.

Parameters:

Name Type Description Default
hardware_profile SchedulerHardwareProfile | None

Scheduler hardware profile whose timings set the deterministic operation durations. None selects the default profile.

None

Returns:

Type Description
SchedulingInstance

A validated SchedulingInstance.

Source code in src/memq_dqc/compiler.py
def to_scheduling_instance(
    self,
    *,
    hardware_profile: SchedulerHardwareProfile | None = None,
) -> SchedulingInstance:
    """Build a scheduling instance from the existing distributed result.

    Opt-in export for external RL schedulers. Uses the already-compiled
    distributed circuit (extracting it on first access if compilation has
    occurred) and does not rerun partitioning. Compile the circuit first.

    Args:
        hardware_profile: Scheduler hardware profile whose timings set the
            deterministic operation durations. ``None`` selects the default
            profile.

    Returns:
        A validated [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance].
    """
    from memq_dqc.scheduler.instance import SchedulingCompileOptions
    from memq_dqc.scheduler.nominal import build_scheduling_instance

    algorithm = self._partitioner._algorithm
    options = SchedulingCompileOptions(
        partitioner=_PARTITIONER_REGISTRY_NAMES.get(
            type(algorithm).__name__, type(algorithm).__name__
        ),
        partitioner_kwargs=None,
        partition_seed=getattr(algorithm, "seed", None),
        ebit_assignment=self._partitioner._distributed_ebit_assignment,
        group_gates=self._partitioner._distributed_group_gates,
        max_group_size=self._partitioner._distributed_max_group_size,
        hardware_profile=hardware_profile,
    )
    fingerprint = _fingerprint_from_parts(
        self.circuit.mono.program,
        self.network,
        options,
        placement=self._injected_placement_signature,
    )
    return build_scheduling_instance(
        self.distributed_circuit,
        self.network,
        options=options,
        compiler_version=_memq_dqc_version(),
        source_fingerprint=fingerprint,
    )

recompile_with_placement

recompile_with_placement(
    schedule: PartitionSchedule,
    windows: PartitionWindows | None = None,
    *,
    hardware_profile: SchedulerHardwareProfile
    | None = None,
) -> SchedulingInstance

Re-derive the distributed circuit and scheduling instance.

Injects a caller-supplied placement and rebuilds the scheduling instance from it, reusing the parsed program, monolithic DAG, and (unless overridden) the windows from the prior compile; only the placement -> distributed derivation re-runs. Partitioning is not re-run, so the compiler must already have produced windows (call compile first) or windows must be supplied explicitly.

The existing distributed flags held on the partitioner (ebit_assignment, group_gates, max_group_size) are preserved. The injected placement is folded into the resulting instance's source_fingerprint so distinct placements never collide.

Parameters:

Name Type Description Default
schedule PartitionSchedule

Per-window placement mapping each QPU to the set of logical qubit indices assigned to it.

required
windows PartitionWindows | None

Optional replacement operation windows. When omitted, the windows from the prior compile are reused.

None
hardware_profile SchedulerHardwareProfile | None

Scheduler hardware profile whose timings set the deterministic operation durations. None selects the default profile.

None

Returns:

Type Description
SchedulingInstance

A validated SchedulingInstance

SchedulingInstance

derived from the injected placement.

Raises:

Type Description
ValueError

If the placement is missing windows, its schedule and windows differ in length, a window is not a partition of the circuit's logical qubits, per-QPU counts differ across windows, or a QPU id or qubit index is out of range for the network.

Source code in src/memq_dqc/compiler.py
def recompile_with_placement(
    self,
    schedule: PartitionSchedule,
    windows: PartitionWindows | None = None,
    *,
    hardware_profile: SchedulerHardwareProfile | None = None,
) -> SchedulingInstance:
    """Re-derive the distributed circuit and scheduling instance.

    Injects a caller-supplied placement and rebuilds the scheduling
    instance from it, reusing the parsed program, monolithic DAG, and
    (unless overridden) the windows from the prior compile; only the
    placement -> distributed derivation re-runs. Partitioning is *not*
    re-run, so the compiler must already have produced windows (call
    [compile][memq_dqc.compiler.Compiler.compile] first) or ``windows`` must be supplied explicitly.

    The existing distributed flags held on the partitioner
    (``ebit_assignment``, ``group_gates``, ``max_group_size``) are
    preserved. The injected placement is folded into the resulting
    instance's ``source_fingerprint`` so distinct placements never collide.

    Args:
        schedule: Per-window placement mapping each QPU to the set of
            logical qubit indices assigned to it.
        windows: Optional replacement operation windows. When omitted, the
            windows from the prior compile are reused.
        hardware_profile: Scheduler hardware profile whose timings set the
            deterministic operation durations. ``None`` selects the default
            profile.

    Returns:
        A validated [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance]
        derived from the injected placement.

    Raises:
        ValueError: If the placement is missing windows, its schedule and
            windows differ in length, a window is not a partition of the
            circuit's logical qubits, per-QPU counts differ across windows,
            or a QPU id or qubit index is out of range for the network.
    """
    algorithm = self._partitioner._algorithm
    effective_windows = algorithm.windows if windows is None else windows
    self._validate_injected_placement(schedule, effective_windows)

    algorithm.schedule = schedule
    if windows is not None:
        algorithm.windows = windows
    self._partitioner.circuit.distributed = None
    self._injected_placement_signature = _placement_signature(
        schedule, windows
    )
    return self.to_scheduling_instance(hardware_profile=hardware_profile)

VerificationArtifacts dataclass

VerificationArtifacts(
    original_program: Program,
    original_qasm: str,
    original_dag: DiGraph,
    distributed_program: Program,
    distributed_qasm: str,
    distributed_dag: DiGraph,
)

Represent both circuits needed for equivalence verification.

Attributes:

Name Type Description
original_program Program

Parsed original OpenQASM program.

original_qasm str

Original circuit serialized as OpenQASM source.

original_dag DiGraph

Original circuit dependency graph.

distributed_program Program

Parsed distributed OpenQASM program.

distributed_qasm str

Distributed circuit serialized as OpenQASM source.

distributed_dag DiGraph

Annotated distributed circuit dependency graph.

SchedulingCompileRequest dataclass

SchedulingCompileRequest(
    request_id: str,
    circuit: ProgramInput,
    topology: NetworkInput,
    options: SchedulingCompileOptions | None = None,
)

One batch compilation request.

Attributes:

Name Type Description
request_id str

Caller-chosen identifier echoed back in the result.

circuit ProgramInput

The input circuit (parsed program, path, or inline source). Use a file path when compiling with workers > 1 so the request is picklable across processes.

topology NetworkInput

The network topology (NetworkGraph or path).

options SchedulingCompileOptions | None

Compilation options; None uses the defaults.

SchedulingCompileResult dataclass

SchedulingCompileResult(
    request_id: str,
    instance: SchedulingInstance | None,
    cache_hit: bool,
    elapsed_seconds: float,
    error: str | None,
)

The outcome of one batch compilation request.

Attributes:

Name Type Description
request_id str

Identifier of the originating request.

instance SchedulingInstance | None

The compiled instance, or None when compilation failed.

cache_hit bool

Whether the instance was loaded from the cache.

elapsed_seconds float

Wall-clock time spent on this request.

error str | None

A "TypeName: message" string when compilation failed, else None.

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,
    )

Scheduler

Scheduler(
    source: Compiler | Partitioner | DistributedCircuit,
    *,
    algo: str | type[_Algorithm] | _Algorithm = "fifo",
    profile: SchedulerHardwareProfile | None = None,
    modality: SchedulerModality = DEFAULT_SCHEDULER_MODALITY,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    multiplex_entangle: bool = True,
    algo_kwargs: dict[str, Any] | None = None,
)

Orchestrate a scheduling algorithm implementation.

Initialize the scheduler and select the algorithm.

Parameters:

Name Type Description Default
source Compiler | Partitioner | DistributedCircuit

What to schedule. A Compiler or Partitioner (its distributed circuit is used) or a DistributedCircuit directly.

required
algo str | type[_Algorithm] | _Algorithm

Algorithm name, class, or preconfigured instance.

'fifo'
profile SchedulerHardwareProfile | None

Optional convenience object selecting both modality and entanglement profile. When provided, modality and entanglement_profile must be left at their defaults.

None
modality SchedulerModality

Hardware timing profile used for local 1Q/2Q gate durations. Defaults to "trapped_ion.ba" (Ba+ trapped ion).

DEFAULT_SCHEDULER_MODALITY
entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile used for entanglement timing. Defaults to "ion.time_bin".

DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
multiplex_entangle bool

Whether entanglement generation may overlap across independent communication resources.

True
algo_kwargs dict[str, Any] | None

Keyword arguments forwarded to the algorithm.

None
Source code in src/memq_dqc/scheduler/schedule.py
def __init__(
    self,
    source: Compiler | Partitioner | DistributedCircuit,
    *,
    algo: str | type[_Algorithm] | _Algorithm = "fifo",
    profile: SchedulerHardwareProfile | None = None,
    modality: SchedulerModality = DEFAULT_SCHEDULER_MODALITY,
    entanglement_profile: SchedulerEntanglementProfile = (
        DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
    ),
    # TODO: make explicit / check
    multiplex_entangle: bool = True,
    algo_kwargs: dict[str, Any] | None = None,
) -> None:
    """Initialize the scheduler and select the algorithm.

    Args:
        source: What to schedule. A ``Compiler`` or ``Partitioner`` (its
            distributed circuit is used) or a ``DistributedCircuit``
            directly.
        algo: Algorithm name, class, or preconfigured instance.
        profile: Optional convenience object selecting both modality and
            entanglement profile. When provided, ``modality`` and
            ``entanglement_profile`` must be left at their defaults.
        modality: Hardware timing profile used for local 1Q/2Q gate
            durations. Defaults to ``"trapped_ion.ba"`` (Ba+ trapped ion).
        entanglement_profile: Entanglement-generation profile used for
            entanglement timing. Defaults to ``"ion.time_bin"``.
        multiplex_entangle: Whether entanglement generation may overlap
            across independent communication resources.
        algo_kwargs: Keyword arguments forwarded to the algorithm.
    """
    self._algorithm = self._resolve_algorithm(
        _resolve_distributed_circuit(source),
        algo,
        profile,
        modality,
        entanglement_profile,
        multiplex_entangle,
        algo_kwargs,
    )

distributed_circuit property

distributed_circuit: DistributedCircuit

Return the distributed circuit used by the scheduler.

multiplex_entangle property

multiplex_entangle: bool

Return the entanglement multiplexing option.

schedule property

schedule: OperationSchedule | None

Return the latest operation schedule, if available.

run

run(
    *,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> None

Run the configured scheduling algorithm.

Parameters:

Name Type Description Default
verbosity Literal['quiet', 'info', 'debug']

Logging verbosity for this workflow call.

'quiet'
Source code in src/memq_dqc/scheduler/schedule.py
def run(
    self,
    *,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> None:
    """Run the configured scheduling algorithm.

    Args:
        verbosity: Logging verbosity for this workflow call.
    """
    with workflow_logging(verbosity):
        timer = StepTimer()
        logger.info(
            "Starting scheduling with %s.",
            type(self._algorithm).__name__,
        )
        self._algorithm.run()
        schedule = self._algorithm.schedule
        if schedule is None:
            logger.warning(
                "Scheduling finished without an operation schedule "
                "after %.3fs.",
                timer.elapsed_seconds(),
            )
            return

        logger.info(
            "Scheduling completed in %.3fs: operations=%d "
            "makespan=%.3f failed_entanglement_operations=%d.",
            timer.elapsed_seconds(),
            len(schedule.operations),
            schedule.makespan,
            _count_failed_entanglement_operations(schedule),
        )
        logger.debug(
            "Scheduled qubit timelines: %s",
            schedule.qubits,
        )

plot_gantt

plot_gantt(
    *,
    ax: Axes | None = None,
    title: str | None = None,
    display: Literal["pretty", "legacy"] = "pretty",
    explicit_ops: bool = False,
    show: bool = False,
    save_path: str | PathLike[str] | None = None,
    dpi: int = 150,
) -> Axes

Render this scheduler's result as a Gantt chart.

Parameters:

Name Type Description Default
ax Axes | None

Existing axes to draw into. A new figure and axes are created when omitted.

None
title str | None

Optional chart title (ignored in "pretty" display).

None
display Literal['pretty', 'legacy']

Which rendering to produce. "pretty" is the publication-ready variant; "legacy" is the on-screen diagnostic chart.

'pretty'
explicit_ops bool

Whether to render one row per scheduled event instead of one row per physical qubit.

False
show bool

Whether to call matplotlib.pyplot.show after rendering.

False
save_path str | PathLike[str] | None

Optional file path. When given, the rendered figure is saved there.

None
dpi int

Resolution used when saving to save_path.

150

Returns:

Type Description
Axes

The Matplotlib axes containing the rendered schedule.

Raises:

Type Description
ValueError

If the scheduler has not produced a schedule yet.

Source code in src/memq_dqc/scheduler/schedule.py
def plot_gantt(
    self,
    *,
    ax: Axes | None = None,
    title: str | None = None,
    display: Literal["pretty", "legacy"] = "pretty",
    explicit_ops: bool = False,
    show: bool = False,
    save_path: str | PathLike[str] | None = None,
    dpi: int = 150,
) -> Axes:
    """Render this scheduler's result as a Gantt chart.

    Args:
        ax: Existing axes to draw into. A new figure and axes are created
            when omitted.
        title: Optional chart title (ignored in ``"pretty"`` display).
        display: Which rendering to produce. ``"pretty"`` is the
            publication-ready variant; ``"legacy"`` is the on-screen
            diagnostic chart.
        explicit_ops: Whether to render one row per scheduled event instead
            of one row per physical qubit.
        show: Whether to call ``matplotlib.pyplot.show`` after rendering.
        save_path: Optional file path. When given, the rendered figure is
            saved there.
        dpi: Resolution used when saving to ``save_path``.

    Returns:
        The Matplotlib axes containing the rendered schedule.

    Raises:
        ValueError: If the scheduler has not produced a schedule yet.
    """
    if self.schedule is None:
        raise ValueError(
            "No schedule available; call run() before plot_gantt()."
        )
    from memq_dqc.scheduler.schedule_visualizer import plot_schedule_gantt

    axes = plot_schedule_gantt(
        self.schedule,
        ax=ax,
        title=title,
        show=show,
        explicit_ops=explicit_ops,
        display=display,
    )
    if save_path is not None:
        axes.figure.savefig(str(save_path), dpi=dpi, bbox_inches="tight")
    return axes

to_json

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

Serialize this scheduler's result to a JSON document.

Opt-in export; scheduling never serializes automatically. See memq_dqc.scheduler.serialize.schedule_to_json for the document layout.

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.

Raises:

Type Description
ValueError

If the scheduler has not produced a schedule yet.

Source code in src/memq_dqc/scheduler/schedule.py
def to_json(
    self,
    path: str | PathLike[str] | None = None,
    *,
    indent: int | None = 2,
) -> str:
    """Serialize this scheduler's result to a JSON document.

    Opt-in export; scheduling never serializes automatically. See
    [memq_dqc.scheduler.serialize.schedule_to_json][memq_dqc.scheduler.serialize.schedule_to_json] for the document
    layout.

    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.

    Raises:
        ValueError: If the scheduler has not produced a schedule yet.
    """
    if self.schedule is None:
        raise ValueError(
            "No schedule available; call run() before to_json()."
        )
    from memq_dqc.scheduler.serialize import schedule_to_json

    return schedule_to_json(self.schedule, path, indent=indent)

SchedulerHardwareProfile dataclass

SchedulerHardwareProfile(
    modality: SchedulerModality = DEFAULT_SCHEDULER_MODALITY,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
)

User-facing hardware selection for scheduler timing.

The two selector fields pick a named profile from settings.toml. The remaining fields are optional per-instance overrides of the individual hardware parameters that profile resolves to: None keeps the profile's value, and any other value replaces it. Derived timings (cat-entangling, cat-disentangling, state teleport, entanglement duration, DES success probability) always recompute from the effective values, so they cannot contradict the parameters they are built from.

Example

A Sr+ trapped-ion device with a faster two-qubit gate and a longer EPR lifetime than the packaged profile assumes:

profile = SchedulerHardwareProfile.sr_trapped_ion(
    two_qubit_gate_time=120.0,
    epr_lifetime=80.0,
)

Attributes:

Name Type Description
modality SchedulerModality

Modality profile used for local gate times.

entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile used for entanglement timing.

one_qubit_gate_time float | None

Optional override for the local single-qubit gate duration.

two_qubit_gate_time float | None

Optional override for the local two-qubit gate duration.

measurement_time float | None

Optional override for the measurement duration.

entanglement_rate float | None

Optional override for the entanglement-generation rate.

epr_lifetime float | None

Optional override for the maximum EPR-pair lifetime.

overrides property

overrides: dict[str, float]

Return the supplied overrides, keyed by field name.

ba_trapped_ion classmethod

ba_trapped_ion(
    *,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile

Return the Ba+ trapped-ion hardware selection.

Parameters:

Name Type Description Default
entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile to pair with the modality.

DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
one_qubit_gate_time float | None

Optional single-qubit gate duration override.

None
two_qubit_gate_time float | None

Optional two-qubit gate duration override.

None
measurement_time float | None

Optional measurement duration override.

None
entanglement_rate float | None

Optional entanglement-generation rate override.

None
epr_lifetime float | None

Optional EPR-pair lifetime override.

None

Returns:

Type Description
SchedulerHardwareProfile

The hardware profile.

Source code in src/memq_dqc/scheduler/schedule.py
@classmethod
def ba_trapped_ion(
    cls,
    *,
    entanglement_profile: SchedulerEntanglementProfile = (
        DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
    ),
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile:
    """Return the Ba+ trapped-ion hardware selection.

    Args:
        entanglement_profile: Entanglement-generation profile to pair with
            the modality.
        one_qubit_gate_time: Optional single-qubit gate duration override.
        two_qubit_gate_time: Optional two-qubit gate duration override.
        measurement_time: Optional measurement duration override.
        entanglement_rate: Optional entanglement-generation rate override.
        epr_lifetime: Optional EPR-pair lifetime override.

    Returns:
        The hardware profile.
    """
    return cls(
        modality="trapped_ion.ba",
        entanglement_profile=entanglement_profile,
        one_qubit_gate_time=one_qubit_gate_time,
        two_qubit_gate_time=two_qubit_gate_time,
        measurement_time=measurement_time,
        entanglement_rate=entanglement_rate,
        epr_lifetime=epr_lifetime,
    )

sr_trapped_ion classmethod

sr_trapped_ion(
    *,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile

Return the Sr+ trapped-ion hardware selection.

Parameters:

Name Type Description Default
entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile to pair with the modality.

DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
one_qubit_gate_time float | None

Optional single-qubit gate duration override.

None
two_qubit_gate_time float | None

Optional two-qubit gate duration override.

None
measurement_time float | None

Optional measurement duration override.

None
entanglement_rate float | None

Optional entanglement-generation rate override.

None
epr_lifetime float | None

Optional EPR-pair lifetime override.

None

Returns:

Type Description
SchedulerHardwareProfile

The hardware profile.

Source code in src/memq_dqc/scheduler/schedule.py
@classmethod
def sr_trapped_ion(
    cls,
    *,
    entanglement_profile: SchedulerEntanglementProfile = (
        DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
    ),
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile:
    """Return the Sr+ trapped-ion hardware selection.

    Args:
        entanglement_profile: Entanglement-generation profile to pair with
            the modality.
        one_qubit_gate_time: Optional single-qubit gate duration override.
        two_qubit_gate_time: Optional two-qubit gate duration override.
        measurement_time: Optional measurement duration override.
        entanglement_rate: Optional entanglement-generation rate override.
        epr_lifetime: Optional EPR-pair lifetime override.

    Returns:
        The hardware profile.
    """
    return cls(
        modality="trapped_ion.sr",
        entanglement_profile=entanglement_profile,
        one_qubit_gate_time=one_qubit_gate_time,
        two_qubit_gate_time=two_qubit_gate_time,
        measurement_time=measurement_time,
        entanglement_rate=entanglement_rate,
        epr_lifetime=epr_lifetime,
    )

forte_trapped_ion classmethod

forte_trapped_ion(
    *,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile

Return the IonQ Forte Enterprise 1 trapped-ion hardware selection.

Timings come from the vendor-published calibration record; unlike the other packaged modalities, this profile also supplies its own measurement time rather than falling back to the package default.

Parameters:

Name Type Description Default
entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile to pair with the modality.

DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
one_qubit_gate_time float | None

Optional single-qubit gate duration override.

None
two_qubit_gate_time float | None

Optional two-qubit gate duration override.

None
measurement_time float | None

Optional measurement duration override.

None
entanglement_rate float | None

Optional entanglement-generation rate override.

None
epr_lifetime float | None

Optional EPR-pair lifetime override.

None

Returns:

Type Description
SchedulerHardwareProfile

The hardware profile.

Source code in src/memq_dqc/scheduler/schedule.py
@classmethod
def forte_trapped_ion(
    cls,
    *,
    entanglement_profile: SchedulerEntanglementProfile = (
        DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
    ),
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile:
    """Return the IonQ Forte Enterprise 1 trapped-ion hardware selection.

    Timings come from the vendor-published calibration record; unlike the
    other packaged modalities, this profile also supplies its own
    measurement time rather than falling back to the package default.

    Args:
        entanglement_profile: Entanglement-generation profile to pair with
            the modality.
        one_qubit_gate_time: Optional single-qubit gate duration override.
        two_qubit_gate_time: Optional two-qubit gate duration override.
        measurement_time: Optional measurement duration override.
        entanglement_rate: Optional entanglement-generation rate override.
        epr_lifetime: Optional EPR-pair lifetime override.

    Returns:
        The hardware profile.
    """
    return cls(
        modality="trapped_ion.forte",
        entanglement_profile=entanglement_profile,
        one_qubit_gate_time=one_qubit_gate_time,
        two_qubit_gate_time=two_qubit_gate_time,
        measurement_time=measurement_time,
        entanglement_rate=entanglement_rate,
        epr_lifetime=epr_lifetime,
    )

neutral_atom classmethod

neutral_atom(
    *,
    entanglement_profile: SchedulerEntanglementProfile = DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE,
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile

Return the neutral-atom hardware selection.

Parameters:

Name Type Description Default
entanglement_profile SchedulerEntanglementProfile

Entanglement-generation profile to pair with the modality.

DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
one_qubit_gate_time float | None

Optional single-qubit gate duration override.

None
two_qubit_gate_time float | None

Optional two-qubit gate duration override.

None
measurement_time float | None

Optional measurement duration override.

None
entanglement_rate float | None

Optional entanglement-generation rate override.

None
epr_lifetime float | None

Optional EPR-pair lifetime override.

None

Returns:

Type Description
SchedulerHardwareProfile

The hardware profile.

Source code in src/memq_dqc/scheduler/schedule.py
@classmethod
def neutral_atom(
    cls,
    *,
    entanglement_profile: SchedulerEntanglementProfile = (
        DEFAULT_SCHEDULER_ENTANGLEMENT_PROFILE
    ),
    one_qubit_gate_time: float | None = None,
    two_qubit_gate_time: float | None = None,
    measurement_time: float | None = None,
    entanglement_rate: float | None = None,
    epr_lifetime: float | None = None,
) -> SchedulerHardwareProfile:
    """Return the neutral-atom hardware selection.

    Args:
        entanglement_profile: Entanglement-generation profile to pair with
            the modality.
        one_qubit_gate_time: Optional single-qubit gate duration override.
        two_qubit_gate_time: Optional two-qubit gate duration override.
        measurement_time: Optional measurement duration override.
        entanglement_rate: Optional entanglement-generation rate override.
        epr_lifetime: Optional EPR-pair lifetime override.

    Returns:
        The hardware profile.
    """
    return cls(
        modality="neutral_atom",
        entanglement_profile=entanglement_profile,
        one_qubit_gate_time=one_qubit_gate_time,
        two_qubit_gate_time=two_qubit_gate_time,
        measurement_time=measurement_time,
        entanglement_rate=entanglement_rate,
        epr_lifetime=epr_lifetime,
    )

SchedulingCompileOptions dataclass

SchedulingCompileOptions(
    partitioner: str = "interaction",
    partitioner_kwargs: Mapping[str, Any] | None = None,
    partition_seed: int | None = None,
    ebit_assignment: bool = True,
    group_gates: bool = False,
    max_group_size: int | None = None,
    hardware_profile: Any | None = None,
)

Options controlling how a scheduling instance is compiled.

For the initial RL corpus the MVP requires ebit_assignment=True and group_gates=False; the remaining fields are kept general for later experiments.

Attributes:

Name Type Description
partitioner str

Registry name of the partitioning algorithm.

partitioner_kwargs Mapping[str, Any] | None

Extra keyword arguments forwarded to the partitioning algorithm, or None for defaults.

partition_seed int | None

Optional seed for partitioners with random components.

ebit_assignment bool

Whether the compiler assigns concrete e-bit pairs (True) or exposes candidate assignments for deferred choice.

group_gates bool

Whether compatible remote gates share a cat-entanglement region.

max_group_size int | None

Optional maximum number of two-qubit gates per group.

hardware_profile Any | None

Scheduler hardware profile whose timings set the deterministic operation durations. None selects the default profile. Besides naming a modality and entanglement profile, a SchedulerHardwareProfile can carry custom hardware parameters (gate, measurement, and entanglement timings) that override the selected profile's values.

SchedulingInstance dataclass

SchedulingInstance(
    schema_version: int,
    instance_id: str,
    compiler_version: str,
    source_fingerprint: str,
    time_unit: str,
    operations: tuple[SchedulingOperation, ...],
    dependencies: tuple[SchedulingDependency, ...],
    resources: tuple[SchedulingResource, ...],
    epr_demands: tuple[EPRDemand, ...],
    nominal_makespan: float,
    metadata: Mapping[str, JSONValue] = dict(),
)

A self-contained scheduling artifact for an external RL scheduler.

Attributes:

Name Type Description
schema_version int

Scheduling-instance schema version.

instance_id str

Deterministic identifier derived from source_fingerprint.

compiler_version str

memq_dqc version that produced the instance.

source_fingerprint str

Hash of the normalized inputs, options, hardware profile, and schema version.

time_unit str

Unit for all durations and nominal times.

operations tuple[SchedulingOperation, ...]

Distributed operations, ordered by op_id.

dependencies tuple[SchedulingDependency, ...]

Precedence edges, ordered by (source, target).

resources tuple[SchedulingResource, ...]

Physical resources, ordered by resource_id.

epr_demands tuple[EPRDemand, ...]

Entanglement demands, ordered by demand_id.

nominal_makespan float

Maximum nominal operation end time.

metadata Mapping[str, JSONValue]

Reproducibility metadata (partitioner, seed, profile, ...).

DESSimulationSettings dataclass

DESSimulationSettings(entanglement_time_step: float)

Timing assumptions for DES scheduler simulation.

Attributes:

Name Type Description
entanglement_time_step float

Duration of one entanglement-attempt cycle.

EntanglementGenerationProfile dataclass

EntanglementGenerationProfile(
    path: tuple[str, ...],
    entanglement_rate: float,
    epr_lifetime: float,
)

Entanglement-generation assumptions for one link profile.

Attributes:

Name Type Description
path tuple[str, ...]

Selector path used to identify the profile.

entanglement_rate float

Nominal entanglement generation rate.

epr_lifetime float

Maximum lifetime of a generated EPR pair.

GlobalSettings dataclass

GlobalSettings(time_unit: str | None = None)

Optional global settings shared across workflows.

Attributes:

Name Type Description
time_unit str | None

Optional human-readable time unit label such as "us".

ModalityProfile dataclass

ModalityProfile(
    path: tuple[str, ...],
    one_qubit_gate_time: float,
    two_qubit_gate_time: float,
    measurement_time: float | None = None,
)

Timing assumptions for one hardware modality profile.

Attributes:

Name Type Description
path tuple[str, ...]

Selector path used to identify the profile.

one_qubit_gate_time float

Duration of a single-qubit gate.

two_qubit_gate_time float

Duration of a two-qubit gate.

measurement_time float | None

Duration of a measurement (readout). None when the profile does not specify one, in which case the scheduler falls back to its package default.

Settings dataclass

Settings(
    global_settings: GlobalSettings,
    des_simulation: DESSimulationSettings,
    modality_profiles: dict[
        tuple[str, ...], ModalityProfile
    ],
    entanglement_profiles: dict[
        tuple[str, ...], EntanglementGenerationProfile
    ],
    verification: VerificationSettings,
)

Validated settings loaded from TOML.

Attributes:

Name Type Description
global_settings GlobalSettings

Optional global configuration values.

des_simulation DESSimulationSettings

DES scheduler simulation timing settings.

modality_profiles dict[tuple[str, ...], ModalityProfile]

Modality timing profiles indexed by selector path.

entanglement_profiles dict[tuple[str, ...], EntanglementGenerationProfile]

Entanglement profiles indexed by selector path.

verification VerificationSettings

Verification defaults.

modality_profile

modality_profile(*path: str) -> ModalityProfile

Return one modality profile selected by path.

Parameters:

Name Type Description Default
*path str

Selector components such as "trapped_ion", "ba" or a single dotted selector such as "trapped_ion.ba".

()

Returns:

Type Description
ModalityProfile

The matching modality profile.

Raises:

Type Description
ValueError

If the selector is empty or no matching profile exists.

Source code in src/memq_dqc/settings.py
def modality_profile(self, *path: str) -> ModalityProfile:
    """Return one modality profile selected by path.

    Args:
        *path: Selector components such as ``"trapped_ion", "ba"`` or a
            single dotted selector such as ``"trapped_ion.ba"``.

    Returns:
        The matching modality profile.

    Raises:
        ValueError: If the selector is empty or no matching profile exists.
    """
    selector = _normalize_selector(*path)
    try:
        return self.modality_profiles[selector]
    except KeyError as exc:
        raise ValueError(
            f"Unknown modality profile selector: {'.'.join(selector)!r}."
        ) from exc

entanglement_profile

entanglement_profile(
    *path: str,
) -> EntanglementGenerationProfile

Return one entanglement-generation profile selected by path.

Parameters:

Name Type Description Default
*path str

Selector components such as "ion", "time_bin" or a single dotted selector such as "ion.time_bin".

()

Returns:

Type Description
EntanglementGenerationProfile

The matching entanglement-generation profile.

Raises:

Type Description
ValueError

If the selector is empty or no matching profile exists.

Source code in src/memq_dqc/settings.py
def entanglement_profile(
    self, *path: str
) -> EntanglementGenerationProfile:
    """Return one entanglement-generation profile selected by path.

    Args:
        *path: Selector components such as ``"ion", "time_bin"`` or a
            single dotted selector such as ``"ion.time_bin"``.

    Returns:
        The matching entanglement-generation profile.

    Raises:
        ValueError: If the selector is empty or no matching profile exists.
    """
    selector = _normalize_selector(*path)
    try:
        return self.entanglement_profiles[selector]
    except KeyError as exc:
        raise ValueError(
            "Unknown entanglement profile selector: "
            f"{'.'.join(selector)!r}."
        ) from exc

VerificationSettings dataclass

VerificationSettings(shots: int, fidelity_threshold: float)

Verification defaults loaded from TOML.

Attributes:

Name Type Description
shots int

Number of simulator shots to use by default.

fidelity_threshold float

Minimum required fidelity threshold.

compile_scheduling_instance

compile_scheduling_instance(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> SchedulingInstance

Compile a circuit into a self-contained scheduling instance.

High-level entry point for external RL schedulers: partitions, extracts the distributed circuit, and assembles a versioned, JSON-persistable SchedulingInstance (distributed DAG, zero-EPR-wait nominal schedule, physical resources and links, and EPR demands).

Parameters:

Name Type Description Default
circuit ProgramInput

The input circuit, as a parsed OpenQASM 3 program, a path to a .qasm/.qasm3 file, or inline OpenQASM source text.

required
topology NetworkInput

The network topology, as a NetworkGraph or a path to its .json description.

required
options SchedulingCompileOptions | None

Compilation options. None uses the defaults (interaction partitioner, explicit e-bit assignment, no gate grouping, default hardware profile). Set options.hardware_profile to select a hardware modality or to override individual hardware parameters such as gate, measurement, and entanglement timings.

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

Logging verbosity for this workflow call.

'quiet'

Returns:

Type Description
SchedulingInstance

A validated SchedulingInstance.

Source code in src/memq_dqc/compiler.py
def compile_scheduling_instance(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> SchedulingInstance:
    """Compile a circuit into a self-contained scheduling instance.

    High-level entry point for external RL schedulers: partitions, extracts the
    distributed circuit, and assembles a versioned, JSON-persistable
    [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance] (distributed DAG,
    zero-EPR-wait nominal schedule, physical resources and links, and EPR
    demands).

    Args:
        circuit: The input circuit, as a parsed OpenQASM 3 program, a path to a
            ``.qasm``/``.qasm3`` file, or inline OpenQASM source text.
        topology: The network topology, as a ``NetworkGraph`` or a path to its
            ``.json`` description.
        options: Compilation options. ``None`` uses the defaults
            (``interaction`` partitioner, explicit e-bit assignment, no gate
            grouping, default hardware profile). Set
            ``options.hardware_profile`` to select a hardware modality or to
            override individual hardware parameters such as gate, measurement,
            and entanglement timings.
        verbosity: Logging verbosity for this workflow call.

    Returns:
        A validated [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance].
    """
    from memq_dqc.scheduler.instance import SchedulingCompileOptions
    from memq_dqc.scheduler.nominal import build_scheduling_instance

    resolved_options = options or SchedulingCompileOptions()
    algo_kwargs = dict(resolved_options.partitioner_kwargs or {})
    if resolved_options.partition_seed is not None:
        algo_kwargs["seed"] = resolved_options.partition_seed

    compiler = Compiler(
        circuit,
        topology,
        algo=resolved_options.partitioner,
        algo_kwargs=algo_kwargs or None,
    )
    compiler.compile(
        ebit_assignment=resolved_options.ebit_assignment,
        group_gates=resolved_options.group_gates,
        max_group_size=resolved_options.max_group_size,
        verbosity=verbosity,
    )
    fingerprint = _fingerprint_from_parts(
        compiler.circuit.mono.program, compiler.network, resolved_options
    )
    return build_scheduling_instance(
        compiler.distributed_circuit,
        compiler.network,
        options=resolved_options,
        compiler_version=_memq_dqc_version(),
        source_fingerprint=fingerprint,
    )

compute_scheduling_source_fingerprint

compute_scheduling_source_fingerprint(
    circuit: ProgramInput,
    topology: NetworkInput,
    options: SchedulingCompileOptions | None = None,
) -> str

Return the source fingerprint for a compile request without compiling.

Parses and normalizes the inputs and hashes them together with the compilation options, hardware profile, and source-normalization schema version. This is the same value compile_scheduling_instance records, enabling a cache lookup before the (much more expensive) compilation runs.

Parameters:

Name Type Description Default
circuit ProgramInput

The input circuit (parsed program, path, or inline source).

required
topology NetworkInput

The network topology (NetworkGraph or path).

required
options SchedulingCompileOptions | None

Compilation options; None uses the defaults.

None

Returns:

Type Description
str

A hex SHA-256 digest of the normalized inputs and options.

Source code in src/memq_dqc/compiler.py
def compute_scheduling_source_fingerprint(
    circuit: ProgramInput,
    topology: NetworkInput,
    options: SchedulingCompileOptions | None = None,
) -> str:
    """Return the source fingerprint for a compile request without compiling.

    Parses and normalizes the inputs and hashes them together with the
    compilation options, hardware profile, and source-normalization schema
    version. This is the same
    value [compile_scheduling_instance][memq_dqc.compiler.compile_scheduling_instance] records, enabling a cache lookup
    before the (much more expensive) compilation runs.

    Args:
        circuit: The input circuit (parsed program, path, or inline source).
        topology: The network topology (``NetworkGraph`` or path).
        options: Compilation options; ``None`` uses the defaults.

    Returns:
        A hex SHA-256 digest of the normalized inputs and options.
    """
    from memq_dqc.scheduler.instance import SchedulingCompileOptions

    resolved_options = options or SchedulingCompileOptions()
    program = _resolve_program_input(circuit)
    network = _resolve_network_input(topology)
    return _fingerprint_from_parts(program, network, resolved_options)

get_verification_artifacts

get_verification_artifacts(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> VerificationArtifacts

Compile and return everything needed for circuit equivalence checks.

Parameters:

Name Type Description Default
circuit ProgramInput

The input circuit, as a parsed OpenQASM 3 program, a path to a .qasm/.qasm3 file, or inline OpenQASM source text.

required
topology NetworkInput

The network topology, as a NetworkGraph or a path to its .json description.

required
options SchedulingCompileOptions | None

Compilation options. None uses the scheduling API defaults.

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

Logging verbosity for the compilation workflow.

'quiet'

Returns:

Type Description
VerificationArtifacts

Original and distributed OpenQASM programs, source strings, and DAGs.

Source code in src/memq_dqc/compiler.py
def get_verification_artifacts(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> VerificationArtifacts:
    """Compile and return everything needed for circuit equivalence checks.

    Args:
        circuit: The input circuit, as a parsed OpenQASM 3 program, a path to a
            ``.qasm``/``.qasm3`` file, or inline OpenQASM source text.
        topology: The network topology, as a ``NetworkGraph`` or a path to its
            ``.json`` description.
        options: Compilation options. ``None`` uses the scheduling API
            defaults.
        verbosity: Logging verbosity for the compilation workflow.

    Returns:
        Original and distributed OpenQASM programs, source strings, and DAGs.
    """
    from memq_dqc.scheduler.instance import SchedulingCompileOptions

    resolved_options = options or SchedulingCompileOptions()
    algo_kwargs = dict(resolved_options.partitioner_kwargs or {})
    if resolved_options.partition_seed is not None:
        algo_kwargs["seed"] = resolved_options.partition_seed

    compiler = Compiler(
        circuit,
        topology,
        algo=resolved_options.partitioner,
        algo_kwargs=algo_kwargs or None,
    )
    compiler.compile(
        ebit_assignment=resolved_options.ebit_assignment,
        group_gates=resolved_options.group_gates,
        max_group_size=resolved_options.max_group_size,
        verbosity=verbosity,
    )
    return compiler.get_verification_artifacts()

recompile_scheduling_instance

recompile_scheduling_instance(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    schedule: PartitionSchedule,
    windows: PartitionWindows | None = None,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> SchedulingInstance

Compile a circuit and re-derive its instance from an injected placement.

Convenience wrapper mirroring compile_scheduling_instance: it builds a Compiler, runs a full compile to establish the reusable program, monolithic DAG, windows, and distributed flags, then re-derives the scheduling instance from schedule (and windows when provided) via Compiler.recompile_with_placement.

Parameters:

Name Type Description Default
circuit ProgramInput

The input circuit, as a parsed OpenQASM 3 program, a path to a .qasm/.qasm3 file, or inline OpenQASM source text.

required
topology NetworkInput

The network topology, as a NetworkGraph or a path to its .json description.

required
schedule PartitionSchedule

Per-window placement mapping each QPU to the set of logical qubit indices assigned to it.

required
windows PartitionWindows | None

Optional replacement operation windows. When omitted, the windows produced by the initial compile are reused.

None
options SchedulingCompileOptions | None

Compilation options. None uses the defaults.

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

Logging verbosity for this workflow call.

'quiet'

Returns:

Type Description
SchedulingInstance

A validated SchedulingInstance

SchedulingInstance

derived from the injected placement.

Source code in src/memq_dqc/compiler.py
def recompile_scheduling_instance(
    circuit: ProgramInput,
    topology: NetworkInput,
    *,
    schedule: PartitionSchedule,
    windows: PartitionWindows | None = None,
    options: SchedulingCompileOptions | None = None,
    verbosity: Literal["quiet", "info", "debug"] = "quiet",
) -> SchedulingInstance:
    """Compile a circuit and re-derive its instance from an injected placement.

    Convenience wrapper mirroring [compile_scheduling_instance][memq_dqc.compiler.compile_scheduling_instance]: it builds
    a [Compiler][memq_dqc.compiler.Compiler], runs a full compile to establish the reusable program,
    monolithic DAG, windows, and distributed flags, then re-derives the
    scheduling instance from ``schedule`` (and ``windows`` when provided) via
    [Compiler.recompile_with_placement][memq_dqc.compiler.Compiler.recompile_with_placement].

    Args:
        circuit: The input circuit, as a parsed OpenQASM 3 program, a path to a
            ``.qasm``/``.qasm3`` file, or inline OpenQASM source text.
        topology: The network topology, as a ``NetworkGraph`` or a path to its
            ``.json`` description.
        schedule: Per-window placement mapping each QPU to the set of logical
            qubit indices assigned to it.
        windows: Optional replacement operation windows. When omitted, the
            windows produced by the initial compile are reused.
        options: Compilation options. ``None`` uses the defaults.
        verbosity: Logging verbosity for this workflow call.

    Returns:
        A validated [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance]
        derived from the injected placement.
    """
    from memq_dqc.scheduler.instance import SchedulingCompileOptions

    resolved_options = options or SchedulingCompileOptions()
    algo_kwargs = dict(resolved_options.partitioner_kwargs or {})
    if resolved_options.partition_seed is not None:
        algo_kwargs["seed"] = resolved_options.partition_seed

    compiler = Compiler(
        circuit,
        topology,
        algo=resolved_options.partitioner,
        algo_kwargs=algo_kwargs or None,
    )
    compiler.compile(
        ebit_assignment=resolved_options.ebit_assignment,
        group_gates=resolved_options.group_gates,
        max_group_size=resolved_options.max_group_size,
        verbosity=verbosity,
    )
    return compiler.recompile_with_placement(
        schedule,
        windows,
        hardware_profile=resolved_options.hardware_profile,
    )

compile_scheduling_batch

compile_scheduling_batch(
    requests: Sequence[SchedulingCompileRequest],
    *,
    workers: int = 1,
    cache_dir: str | PathLike[str] | None = None,
    fail_fast: bool = False,
) -> tuple[SchedulingCompileResult, ...]

Compile a batch of scheduling-instance requests.

Parameters:

Name Type Description Default
requests Sequence[SchedulingCompileRequest]

Requests to compile. The returned results preserve this order.

required
workers int

Number of worker processes. 1 compiles sequentially; greater than 1 uses process-based parallelism.

1
cache_dir str | PathLike[str] | None

Optional directory for the fingerprint cache. When set, each artifact is cached by source_fingerprint with an atomic write and reused on a subsequent request with the same inputs.

None
fail_fast bool

When True, the first failing request raises instead of returning a per-request error.

False

Returns:

Type Description
tuple[SchedulingCompileResult, ...]

One SchedulingCompileResult per request, in input order.

Raises:

Type Description
ValueError

If workers is less than 1.

RuntimeError

If fail_fast is True and a request fails.

Source code in src/memq_dqc/compiler_batch.py
def compile_scheduling_batch(
    requests: Sequence[SchedulingCompileRequest],
    *,
    workers: int = 1,
    cache_dir: str | PathLike[str] | None = None,
    fail_fast: bool = False,
) -> tuple[SchedulingCompileResult, ...]:
    """Compile a batch of scheduling-instance requests.

    Args:
        requests: Requests to compile. The returned results preserve this
            order.
        workers: Number of worker processes. ``1`` compiles sequentially;
            greater than ``1`` uses process-based parallelism.
        cache_dir: Optional directory for the fingerprint cache. When set,
            each artifact is cached by ``source_fingerprint`` with an atomic
            write and reused on a subsequent request with the same inputs.
        fail_fast: When ``True``, the first failing request raises instead of
            returning a per-request error.

    Returns:
        One [SchedulingCompileResult][memq_dqc.compiler_batch.SchedulingCompileResult] per request, in input order.

    Raises:
        ValueError: If ``workers`` is less than 1.
        RuntimeError: If ``fail_fast`` is ``True`` and a request fails.
    """
    if workers < 1:
        raise ValueError("workers must be at least 1.")

    resolved_cache_dir = _prepare_cache_dir(cache_dir)

    if workers == 1:
        results: list[SchedulingCompileResult] = []
        for request in requests:
            result = _compile_one(request, cache_dir=resolved_cache_dir)
            if fail_fast and result.error is not None:
                raise RuntimeError(
                    f"Request {request.request_id!r} failed: {result.error}"
                )
            results.append(result)
        return tuple(results)

    worker = functools.partial(_compile_one, cache_dir=resolved_cache_dir)
    with ProcessPoolExecutor(max_workers=workers) as executor:
        results = list(executor.map(worker, requests))

    if fail_fast:
        for result in results:
            if result.error is not None:
                raise RuntimeError(
                    f"Request {result.request_id!r} failed: {result.error}"
                )
    return tuple(results)

scheduling_instance_from_json

scheduling_instance_from_json(
    source: str | PathLike[str] | Mapping[str, Any],
) -> SchedulingInstance

Load and validate a scheduling instance from JSON.

Parameters:

Name Type Description Default
source str | PathLike[str] | Mapping[str, Any]

A parsed mapping, a JSON document string, or a path to a JSON file (as str or os.PathLike).

required

Returns:

Type Description
SchedulingInstance

The reconstructed, validated SchedulingInstance.

Raises:

Type Description
ValueError

If the document type or schema version is unsupported, a number is non-finite, or the reconstructed instance is invalid.

Source code in src/memq_dqc/scheduler/instance_serialize.py
def scheduling_instance_from_json(
    source: str | PathLike[str] | Mapping[str, Any],
) -> SchedulingInstance:
    """Load and validate a scheduling instance from JSON.

    Args:
        source: A parsed mapping, a JSON document string, or a path to a JSON
            file (as ``str`` or `os.PathLike`).

    Returns:
        The reconstructed, validated [SchedulingInstance][memq_dqc.scheduler.instance.SchedulingInstance].

    Raises:
        ValueError: If the document type or schema version is unsupported, a
            number is non-finite, or the reconstructed instance is invalid.
    """
    data = _load_document(source)
    document_type = data.get("type")
    if document_type != _INSTANCE_TYPE:
        raise ValueError(
            f"Unsupported document type {document_type!r}; expected "
            f"{_INSTANCE_TYPE!r}."
        )
    schema_version = data.get("schema_version")
    if schema_version not in (1, SCHEDULING_INSTANCE_SCHEMA_VERSION):
        raise ValueError(
            f"Unsupported scheduling-instance schema version "
            f"{schema_version!r}; this build supports "
            f"1 and {SCHEDULING_INSTANCE_SCHEMA_VERSION}."
        )

    instance = _instance_from_dict(data)
    validate_scheduling_instance(instance)
    return instance

scheduling_instance_to_json

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

Serialize a scheduling instance to a JSON document.

Parameters:

Name Type Description Default
instance SchedulingInstance

The scheduling instance to serialize.

required
path str | PathLike[str] | None

Optional destination file. When given, the 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 (suited to large corpora).

2

Returns:

Type Description
str

The JSON document as a string.

Raises:

Type Description
ValueError

If the instance contains a non-finite number.

Source code in src/memq_dqc/scheduler/instance_serialize.py
def scheduling_instance_to_json(
    instance: SchedulingInstance,
    path: str | PathLike[str] | None = None,
    *,
    indent: int | None = 2,
) -> str:
    """Serialize a scheduling instance to a JSON document.

    Args:
        instance: The scheduling instance to serialize.
        path: Optional destination file. When given, the 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 (suited to large corpora).

    Returns:
        The JSON document as a string.

    Raises:
        ValueError: If the instance contains a non-finite number.
    """
    document = json.dumps(
        _instance_to_dict(instance),
        indent=indent,
        allow_nan=False,
    )
    if path is not None:
        Path(path).write_text(document, encoding="utf-8")
    return document

validate_scheduling_instance

validate_scheduling_instance(
    instance: SchedulingInstance,
) -> None

Validate the structural and nominal-schedule invariants of an instance.

Parameters:

Name Type Description Default
instance SchedulingInstance

The scheduling instance to validate.

required

Raises:

Type Description
ValueError

If any invariant is violated. The message names the offending id(s) and the invariant.

Source code in src/memq_dqc/scheduler/instance.py
def validate_scheduling_instance(instance: SchedulingInstance) -> None:
    """Validate the structural and nominal-schedule invariants of an instance.

    Args:
        instance: The scheduling instance to validate.

    Raises:
        ValueError: If any invariant is violated. The message names the
            offending id(s) and the invariant.
    """
    if instance.schema_version not in (1, SCHEDULING_INSTANCE_SCHEMA_VERSION):
        raise ValueError(
            f"Unsupported scheduling-instance schema version {instance.schema_version!r}."
        )
    op_ids = _validate_unique_ids(
        (op.op_id for op in instance.operations),
        kind="operation",
    )
    resource_ids = _validate_unique_ids(
        (resource.resource_id for resource in instance.resources),
        kind="resource",
    )
    _validate_unique_ids(
        (demand.demand_id for demand in instance.epr_demands),
        kind="EPR demand",
    )

    op_by_id = {op.op_id: op for op in instance.operations}
    _validate_dependencies(instance, op_ids)
    _validate_acyclic(instance, op_ids)
    _validate_epr_demands(instance, op_by_id, resource_ids)
    _validate_cat_proxy_metadata(instance)
    _validate_nominal_times(instance)
    _validate_nominal_ordering(instance, op_by_id)
    _validate_resource_intervals(instance)
    _validate_makespan(instance)

default_settings_path

default_settings_path() -> Path

Return the packaged default settings file path.

Source code in src/memq_dqc/settings.py
def default_settings_path() -> Path:
    """Return the packaged default settings file path."""
    return Path(__file__).with_name("settings.toml")

load_settings

load_settings() -> Settings

Load and validate the packaged default settings.

Source code in src/memq_dqc/settings.py
def load_settings() -> Settings:
    """Load and validate the packaged default settings."""
    return load_settings_file(default_settings_path())

load_settings_file

load_settings_file(path: str | Path) -> Settings

Load and validate settings from a TOML file.

Parameters:

Name Type Description Default
path str | Path

Filesystem path to the TOML file.

required

Returns:

Type Description
Settings

The validated settings object.

Raises:

Type Description
ValueError

If the TOML file is malformed or misses required fields.

Source code in src/memq_dqc/settings.py
def load_settings_file(path: str | Path) -> Settings:
    """Load and validate settings from a TOML file.

    Args:
        path: Filesystem path to the TOML file.

    Returns:
        The validated settings object.

    Raises:
        ValueError: If the TOML file is malformed or misses required fields.
    """
    settings_path = Path(path)
    try:
        with settings_path.open("rb") as handle:
            raw_settings = tomllib.load(handle)
    except tomllib.TOMLDecodeError as exc:
        raise ValueError(
            f"Invalid TOML in settings file {settings_path!s}: {exc}."
        ) from exc

    if not isinstance(raw_settings, dict):
        raise ValueError(
            f"Settings file {settings_path!s} must contain a TOML table."
        )

    return Settings(
        global_settings=_parse_global_settings(raw_settings),
        des_simulation=_parse_des_simulation_settings(raw_settings),
        modality_profiles=_parse_modality_profiles(raw_settings),
        entanglement_profiles=_parse_entanglement_profiles(raw_settings),
        verification=_parse_verification_settings(raw_settings),
    )