qref 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: qref
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Quantum Resource Estimation Format
5
5
  License: Apache 2.0
6
6
  Author: PsiQuantum, Corp.
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "qref"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Quantum Resource Estimation Format"
5
5
  authors = ["PsiQuantum, Corp."]
6
6
  license = "Apache 2.0"
@@ -18,7 +18,14 @@ from __future__ import annotations
18
18
 
19
19
  from typing import Annotated, Any, Literal, Optional, Union
20
20
 
21
- from pydantic import AfterValidator, BaseModel, ConfigDict, Field, StringConstraints
21
+ from pydantic import (
22
+ AfterValidator,
23
+ BaseModel,
24
+ ConfigDict,
25
+ Field,
26
+ StringConstraints,
27
+ field_validator,
28
+ )
22
29
  from pydantic.json_schema import GenerateJsonSchema
23
30
 
24
31
  NAME_PATTERN = "[A-Za-z_][A-Za-z0-9_]*"
@@ -96,6 +103,30 @@ class RoutineV1(BaseModel):
96
103
  def __init__(self, **data: Any):
97
104
  super().__init__(**{k: v for k, v in data.items() if v != [] and v != {}})
98
105
 
106
+ @field_validator("connections", mode="after")
107
+ @classmethod
108
+ def _validate_connections(cls, v, values) -> list[_ConnectionV1]:
109
+ children_port_names = [
110
+ f"{child.name}.{port.name}"
111
+ for child in values.data.get("children")
112
+ for port in child.ports
113
+ ]
114
+ parent_port_names = [port.name for port in values.data["ports"]]
115
+ available_port_names = set(children_port_names + parent_port_names)
116
+
117
+ missed_ports = [
118
+ port
119
+ for connection in v
120
+ for port in (connection.source, connection.target)
121
+ if port not in available_port_names
122
+ ]
123
+ if missed_ports:
124
+ raise ValueError(
125
+ "The following ports appear in a connection but are not "
126
+ "among routine's port or their children's ports: {missed_ports}."
127
+ )
128
+ return v
129
+
99
130
 
100
131
  class SchemaV1(BaseModel):
101
132
  """Root object in Program schema V1."""
@@ -0,0 +1,154 @@
1
+ # Copyright 2024 PsiQuantum, Corp.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections import defaultdict
16
+ from dataclasses import dataclass
17
+ from typing import Optional, Union
18
+
19
+ from ._schema_v1 import RoutineV1, SchemaV1
20
+
21
+
22
+ @dataclass
23
+ class TopologyVerificationOutput:
24
+ """Dataclass containing the output of the topology verification"""
25
+
26
+ problems: list[str]
27
+
28
+ @property
29
+ def is_valid(self):
30
+ return len(self.problems) == 0
31
+
32
+ def __bool__(self) -> bool:
33
+ return self.is_valid
34
+
35
+
36
+ def verify_topology(routine: Union[SchemaV1, RoutineV1]) -> TopologyVerificationOutput:
37
+ """Checks whether program has correct topology.
38
+
39
+ Args:
40
+ routine: Routine or program to be verified.
41
+ """
42
+ if isinstance(routine, SchemaV1):
43
+ routine = routine.program
44
+ problems = _verify_routine_topology(routine)
45
+ return TopologyVerificationOutput(problems)
46
+
47
+
48
+ def _verify_routine_topology(routine: RoutineV1) -> list[str]:
49
+ problems = []
50
+ adjacency_list = _get_adjacency_list_from_routine(routine, path=None)
51
+
52
+ problems += _find_cycles(adjacency_list)
53
+ problems += _find_disconnected_ports(routine)
54
+
55
+ for child in routine.children:
56
+ new_problems = _verify_routine_topology(child)
57
+ problems += new_problems
58
+ return problems
59
+
60
+
61
+ def _get_adjacency_list_from_routine(
62
+ routine: RoutineV1, path: Optional[str]
63
+ ) -> dict[str, list[str]]:
64
+ """This function creates a flat graph representing one hierarchy level of a routine.
65
+
66
+ Nodes represent ports and edges represent connections (they're directed).
67
+ Additionaly, we add node for each children and edges coming from all the input ports
68
+ into the children, and from the children into all the output ports.
69
+ """
70
+ graph = defaultdict(list)
71
+ if path is None:
72
+ current_path = routine.name
73
+ else:
74
+ current_path = ".".join([path, routine.name])
75
+
76
+ # First, we go through all the connections and add them as adges to the graph
77
+ for connection in routine.connections:
78
+ source = ".".join([current_path, connection.source])
79
+ target = ".".join([current_path, connection.target])
80
+ graph[source].append(target)
81
+
82
+ # Then for each children we add an extra node and set of connections
83
+ for child in routine.children:
84
+ input_ports = []
85
+ output_ports = []
86
+
87
+ child_path = ".".join([current_path, child.name])
88
+ for port in child.ports:
89
+ if port.direction == "input":
90
+ input_ports.append(".".join([child_path, port.name]))
91
+ elif port.direction == "output":
92
+ output_ports.append(".".join([child_path, port.name]))
93
+
94
+ for input_port in input_ports:
95
+ graph[input_port].append(child_path)
96
+
97
+ graph[child_path] += output_ports
98
+
99
+ return graph
100
+
101
+
102
+ def _find_cycles(adjacency_list: dict[str, list[str]]) -> list[str]:
103
+ # Note: it only returns the first detected cycle.
104
+ for node in list(adjacency_list.keys()):
105
+ problem = _dfs_iteration(adjacency_list, node)
106
+ if problem:
107
+ return problem
108
+ return []
109
+
110
+
111
+ def _dfs_iteration(adjacency_list, start_node) -> list[str]:
112
+ to_visit = [start_node]
113
+ visited = []
114
+ predecessors = {}
115
+
116
+ while to_visit:
117
+ node = to_visit.pop()
118
+ visited.append(node)
119
+ for neighbour in adjacency_list[node]:
120
+ predecessors[neighbour] = node
121
+ if neighbour == start_node:
122
+ # Reconstruct the cycle
123
+ cycle = [neighbour]
124
+ while len(cycle) < 2 or cycle[-1] != start_node:
125
+ cycle.append(predecessors[cycle[-1]])
126
+ return [f"Cycle detected: {cycle[::-1]}"]
127
+ if neighbour not in visited:
128
+ to_visit.append(neighbour)
129
+ return []
130
+
131
+
132
+ def _find_disconnected_ports(routine: RoutineV1):
133
+ problems = []
134
+ for child in routine.children:
135
+ for port in child.ports:
136
+ pname = f"{routine.name}.{child.name}.{port.name}"
137
+ if port.direction == "input":
138
+ matches_in = [
139
+ c for c in routine.connections if c.target == f"{child.name}.{port.name}"
140
+ ]
141
+ if len(matches_in) == 0:
142
+ problems.append(f"No incoming connections to {pname}.")
143
+ elif len(matches_in) > 1:
144
+ problems.append(f"Too many incoming connections to {pname}.")
145
+ elif port.direction == "output":
146
+ matches_out = [
147
+ c for c in routine.connections if c.source == f"{child.name}.{port.name}"
148
+ ]
149
+ if len(matches_out) == 0:
150
+ problems.append(f"No outgoing connections from {pname}.")
151
+ elif len(matches_out) > 1:
152
+ problems.append(f"Too many outgoing connections from {pname}.")
153
+
154
+ return problems
File without changes
File without changes
File without changes
File without changes