Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
7227507
base implementation of scheduler
masa10-f Jul 26, 2025
66d6147
implement on-the-fly scheduler
masa10-f Jul 26, 2025
4bff8d6
add time slice grouping methods
masa10-f Jul 27, 2025
b7908c3
add scheduler attribute in qompiler func
masa10-f Jul 27, 2025
bc26c01
fix pyright warning
masa10-f Jul 27, 2025
d190f3b
add ortools as a requirements
masa10-f Aug 2, 2025
cddb743
implement mimize_space/minimize_time solvers
masa10-f Aug 2, 2025
97115bc
update scheduler class
masa10-f Aug 3, 2025
2999781
add schedule grouping method
masa10-f Aug 3, 2025
e7f393f
fix pyright warning
masa10-f Aug 3, 2025
fc3a1f2
scheduler generation with manual design
masa10-f Aug 6, 2025
7a51968
rename
masa10-f Aug 6, 2025
7f6989c
improve performance
masa10-f Aug 6, 2025
e77f9df
connect scheduler and solver
masa10-f Aug 12, 2025
2af2c74
test for scheduler module
masa10-f Aug 12, 2025
635ae8b
fix ruff error at test
masa10-f Aug 12, 2025
3436b4a
fix qompiler generation order
masa10-f Aug 12, 2025
0d6351c
add scheduled pattern generation demo
masa10-f Aug 12, 2025
c16f0bf
add documents
masa10-f Aug 12, 2025
559c3a4
use general type
masa10-f Aug 12, 2025
ab94a3e
fix mypy error
masa10-f Aug 12, 2025
9a82721
improve data pipeline in Scheduler
masa10-f Aug 12, 2025
1e56b05
add schedule validator
masa10-f Aug 12, 2025
5b89fa5
check schedule
masa10-f Aug 12, 2025
3c3867b
implement constrained solver
masa10-f Aug 12, 2025
00f3d92
update UI
masa10-f Aug 12, 2025
c765aad
update demo with new solvers
masa10-f Aug 12, 2025
3071328
add docstrings
masa10-f Aug 12, 2025
c3f8b98
resolve pyright warnings
masa10-f Aug 12, 2025
9e4612a
update unittest
masa10-f Aug 12, 2025
341fe71
implement time compression method
masa10-f Aug 12, 2025
2ef360c
add test
masa10-f Aug 12, 2025
b793a3d
use frozenset
masa10-f Aug 13, 2025
5dff041
use and
masa10-f Aug 13, 2025
8d556ac
replace and
masa10-f Aug 13, 2025
7d1f635
fix docstring
masa10-f Aug 13, 2025
33f3686
simplify code
masa10-f Aug 13, 2025
5f9a960
fix missing type hint
masa10-f Aug 13, 2025
2a139a3
unify MINIMIZE_TIME strategy
masa10-f Aug 16, 2025
643a13b
update related files
masa10-f Aug 16, 2025
cf76464
ruff
masa10-f Aug 16, 2025
55377f9
add missing branch
masa10-f Aug 16, 2025
1cbd843
remove redundant set collections
masa10-f Aug 16, 2025
b910bbd
use defaultdict
masa10-f Aug 16, 2025
aa9dd24
change get_schedule() -> schedule
masa10-f Aug 16, 2025
c5c046d
avoid from_xxx
masa10-f Aug 16, 2025
6b7423a
update related files
masa10-f Aug 16, 2025
00b0385
use disjoint
masa10-f Aug 16, 2025
f4cc470
add test for schedule validation
masa10-f Aug 16, 2025
2457b36
use collections type hint in private func
masa10-f Aug 16, 2025
64b9332
separate compress_schedule from Scheduler class
masa10-f Aug 16, 2025
58ced99
fix docstring
masa10-f Aug 16, 2025
4a63230
change method name
masa10-f Aug 22, 2025
3745bef
update qompile
masa10-f Aug 22, 2025
cc88c4f
update
masa10-f Aug 22, 2025
4118d8f
add comment
masa10-f Aug 22, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/references.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ Module reference
pattern
pauli_frame
qompiler
scheduler
15 changes: 15 additions & 0 deletions docs/source/scheduler.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Scheduler Module
================


Scheduler
---------

.. automodule:: graphix_zx.scheduler
:members:

Scheduling Solver
-----------------

.. automodule:: graphix_zx.schedule_solver
:members:
197 changes: 197 additions & 0 deletions examples/scheduler_pattern_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
"""
Scheduler-based Pattern Generation Demo
=======================================

This example demonstrates how to use the scheduler to generate optimized
measurement patterns from graph states using different scheduling strategies.
"""

# %%
from graphix_zx.pattern import Pattern, print_pattern
from graphix_zx.qompiler import qompile
from graphix_zx.random_objects import generate_random_flow_graph
from graphix_zx.schedule_solver import ScheduleConfig, Strategy
from graphix_zx.scheduler import Scheduler

# %%
# Create sample graph state and flow
print("=== Scheduler-based Pattern Generation Demo ===\n")
print("1. Creating sample graph state...")
graph, xflow = generate_random_flow_graph(width=3, depth=3, edge_p=0.7)
print(f" Graph has {len(graph.physical_nodes)} nodes")
print(f" Input nodes: {list(graph.input_node_indices.keys())}")
print(f" Output nodes: {list(graph.output_node_indices.keys())}")
print(f" Edges: {len(graph.physical_edges)}")

# %%
# Demonstrate space-optimized scheduling
print("\n2. Space-optimized Scheduling:")
print("=" * 40)

scheduler_space = Scheduler(graph, xflow)
space_config = ScheduleConfig(strategy=Strategy.MINIMIZE_SPACE)
success_space = scheduler_space.solve_schedule(space_config, timeout=10)
pattern_space = None

if success_space and scheduler_space.validate_schedule():
print(" Scheduling successful!")
print(f" Number of time slices: {scheduler_space.num_slices()}")

prep_times = {k: v for k, v in scheduler_space.prepare_time.items() if v is not None}
if prep_times:
print(f" Preparation times: {prep_times}")

meas_times = {k: v for k, v in scheduler_space.measure_time.items() if v is not None}
if meas_times:
print(f" Measurement times: {meas_times}")

print("\n Generated Pattern (Space-optimized):")
pattern_space = qompile(graph, xflow, scheduler=scheduler_space)
print(f" Pattern has {len(pattern_space.commands)} commands")
print(f" Maximum space usage: {pattern_space.max_space} qubits")
print(f" Space usage over time: {pattern_space.space}")

print("\n Pattern commands:")
print_pattern(pattern_space, lim=10)
else:
print(" Failed to find solution for Space-optimized strategy")

# %%
# Demonstrate time-optimized scheduling
print("\n3. Time-optimized Scheduling:")
print("=" * 40)

scheduler_time = Scheduler(graph, xflow)
time_config = ScheduleConfig(strategy=Strategy.MINIMIZE_TIME)
success_time = scheduler_time.solve_schedule(time_config, timeout=10)
pattern_time = None

if success_time and scheduler_time.validate_schedule():
print(" Scheduling successful!")
print(f" Number of time slices: {scheduler_time.num_slices()}")

prep_times = {k: v for k, v in scheduler_time.prepare_time.items() if v is not None}
if prep_times:
print(f" Preparation times: {prep_times}")

meas_times = {k: v for k, v in scheduler_time.measure_time.items() if v is not None}
if meas_times:
print(f" Measurement times: {meas_times}")

print("\n Generated Pattern (Time-optimized):")
pattern_time = qompile(graph, xflow, scheduler=scheduler_time)
print(f" Pattern has {len(pattern_time.commands)} commands")
print(f" Maximum space usage: {pattern_time.max_space} qubits")
print(f" Space usage over time: {pattern_time.space}")

print("\n Pattern commands:")
print_pattern(pattern_time, lim=10)
else:
print(" Failed to find solution for Time-optimized strategy")

# %%
# Demonstrate space-constrained time optimization using ScheduleConfig
print("\n4. Space-constrained Time-optimized Scheduling (ScheduleConfig):")
print("=" * 60)

# Use ScheduleConfig for more detailed control
max_qubits = 5
constrained_config = ScheduleConfig(
strategy=Strategy.MINIMIZE_TIME,
max_qubit_count=max_qubits,
max_time=20, # Custom time limit
)

scheduler_constrained = Scheduler(graph, xflow)
success_constrained = scheduler_constrained.solve_schedule(constrained_config, timeout=15)
pattern_constrained = None

if success_constrained and scheduler_constrained.validate_schedule():
print(" Scheduling successful!")
print(f" Number of time slices: {scheduler_constrained.num_slices()}")
print(f" Max qubits constraint: {max_qubits}")

prep_times = {k: v for k, v in scheduler_constrained.prepare_time.items() if v is not None}
if prep_times:
print(f" Preparation times: {prep_times}")

meas_times = {k: v for k, v in scheduler_constrained.measure_time.items() if v is not None}
if meas_times:
print(f" Measurement times: {meas_times}")

print("\n Generated Pattern (Space-constrained Time-optimized):")
pattern_constrained = qompile(graph, xflow, scheduler=scheduler_constrained)
print(f" Pattern has {len(pattern_constrained.commands)} commands")
print(f" Maximum space usage: {pattern_constrained.max_space} qubits")
print(f" Space usage over time: {pattern_constrained.space}")

if pattern_constrained.max_space <= max_qubits:
print(f" ✓ Space constraint satisfied: {pattern_constrained.max_space} <= {max_qubits}")
else:
print(f" ⚠ Space constraint violated: {pattern_constrained.max_space} > {max_qubits}")

print("\n Pattern commands:")
print_pattern(pattern_constrained, lim=10)
else:
print(f" Failed to find solution with {max_qubits} qubits constraint")

# %%
# Demonstrate custom max_time using ScheduleConfig
print("\n5. Custom max_time Scheduling (ScheduleConfig):")
print("=" * 50)

custom_time_config = ScheduleConfig(
strategy=Strategy.MINIMIZE_SPACE,
max_time=15, # Smaller time horizon for faster solving
)

scheduler_custom = Scheduler(graph, xflow)
success_custom = scheduler_custom.solve_schedule(custom_time_config, timeout=10)

if success_custom and scheduler_custom.validate_schedule():
print(" Scheduling with custom max_time successful!")
print(f" Number of time slices: {scheduler_custom.num_slices()}")
print(f" Custom max_time: {custom_time_config.max_time}")

pattern_custom = qompile(graph, xflow, scheduler=scheduler_custom)
print(f" Maximum space usage: {pattern_custom.max_space} qubits")
else:
print(" Failed to find solution with custom max_time")

# %%
# Compare all strategies
print("\n6. Strategy Comparison:")
print("=" * 40)

all_results: list[tuple[str, Scheduler, Pattern]] = []
if success_space and pattern_space:
all_results.append(("Space-optimized", scheduler_space, pattern_space))
if success_time and pattern_time:
all_results.append(("Time-optimized", scheduler_time, pattern_time))
if success_constrained and pattern_constrained:
all_results.append(("Space-constrained", scheduler_constrained, pattern_constrained))

min_results_needed = 2
if len(all_results) >= min_results_needed:
for name, scheduler, pattern in all_results:
print(
f" {name:18}: {scheduler.num_slices()} slices, "
f"{pattern.max_space} max qubits, {len(pattern.commands)} commands"
)

print("\n Analysis:")
min_results_for_comparison = 2
if len(all_results) >= min_results_for_comparison:
min_slices = min(s.num_slices() for _, s, _ in all_results)
min_qubits = min(p.max_space for _, _, p in all_results)

for name, scheduler, pattern in all_results:
notes: list[str] = []
if scheduler.num_slices() == min_slices:
notes.append("fastest execution")
if pattern.max_space == min_qubits:
notes.append("lowest qubit usage")
if notes:
print(f" → {name}: {', '.join(notes)}")

print("\nDemo completed successfully!")
34 changes: 30 additions & 4 deletions graphix_zx/qompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
from collections.abc import Set as AbstractSet

from graphix_zx.graphstate import BaseGraphState
from graphix_zx.scheduler import Scheduler


def qompile(
graph: BaseGraphState,
xflow: Mapping[int, AbstractSet[int]],
zflow: Mapping[int, AbstractSet[int]] | None = None,
*,
scheduler: Scheduler | None = None,
correct_output: bool = True,
) -> Pattern:
r"""Compile graph state into pattern with x/z correction flows.
Expand All @@ -43,6 +45,10 @@ def qompile(
zflow : `collections.abc.Mapping`\[`int`, `collections.abc.Set`\[`int`\]\] | `None`
z correction flow
if `None`, it is generated from xflow by odd neighbors
scheduler : `Scheduler` | `None`, optional
scheduler to schedule the graph state preparation and measurements,
if `None`, the commands are scheduled in a single slice,
by default `None`
correct_output : `bool`, optional
whether to correct outputs or not, by default True

Expand All @@ -66,13 +72,14 @@ def qompile(

pauli_frame = PauliFrame(graph.physical_nodes, xflow, zflow)

return _qompile(graph, pauli_frame, correct_output=correct_output)
return _qompile(graph, pauli_frame, scheduler=scheduler, correct_output=correct_output)


def _qompile(
graph: BaseGraphState,
pauli_frame: PauliFrame,
*,
scheduler: Scheduler | None = None,
correct_output: bool = True,
) -> Pattern:
"""Compile graph state into pattern with a given Pauli frame.
Expand All @@ -85,6 +92,10 @@ def _qompile(
graph state
pauli_frame : `PauliFrame`
Pauli frame to track the Pauli state of each node
scheduler : `Scheduler` | `None`, optional
scheduler to schedule the graph state preparation and measurements,
if `None`, the commands are scheduled in a single slice,
by default `None`
correct_output : `bool`, optional
whether to correct outputs or not, by default True

Expand All @@ -101,9 +112,24 @@ def _qompile(
topo_order.reverse() # children first

commands: list[Command] = []
commands.extend(N(node=node) for node in non_input_nodes)
commands.extend(E(nodes=edge) for edge in graph.physical_edges)
commands.extend(M(node, meas_bases[node]) for node in topo_order if node not in graph.output_node_indices)
if not scheduler:
commands.extend(N(node=node) for node in non_input_nodes)
commands.extend(E(nodes=edge) for edge in graph.physical_edges)
commands.extend(M(node, meas_bases[node]) for node in topo_order if node not in graph.output_node_indices)
else:
timeline = scheduler.timeline
prepared_edges: set[frozenset[int]] = set()

for time in range(scheduler.num_slices()):
prepare_nodes, measure_nodes = timeline[time]
for node in measure_nodes:
for neighbor in graph.neighbors(node):
edge = frozenset({node, neighbor})
if edge not in prepared_edges:
commands.append(E(nodes=(node, neighbor)))
prepared_edges.add(edge)
commands.extend(M(node, meas_bases[node]) for node in measure_nodes)
commands.extend(N(node) for node in prepare_nodes)
if correct_output:
commands.extend(X(node=node) for node in graph.output_node_indices)
commands.extend(Z(node=node) for node in graph.output_node_indices)
Expand Down
Loading
Loading