westquant-core 0.2.0a1__py3-none-any.whl

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.
@@ -0,0 +1,42 @@
1
+ from .model import (
2
+ EquivalenceKind,
3
+ Representation,
4
+ RepresentationKind,
5
+ TransformationRecord,
6
+ )
7
+ from .repgraph import RepGraph
8
+ from .plugin import (
9
+ CompilerAdapter,
10
+ EvaluatorAdapter,
11
+ FrontendAdapter,
12
+ PluginCapabilities,
13
+ PluginManifest,
14
+ RuntimeAdapter,
15
+ TransformationProvider,
16
+ WestQuantPlugin,
17
+ )
18
+
19
+ __all__ = [
20
+ "EquivalenceKind",
21
+ "Representation",
22
+ "RepresentationKind",
23
+ "TransformationRecord",
24
+ "RepGraph",
25
+ "PluginCapabilities",
26
+ "PluginManifest",
27
+ "FrontendAdapter",
28
+ "TransformationProvider",
29
+ "CompilerAdapter",
30
+ "EvaluatorAdapter",
31
+ "RuntimeAdapter",
32
+ "WestQuantPlugin",
33
+ ]
34
+
35
+ from .search import Action, Evaluation, Objective, PolicyState, BeamSearchResult, DeterministicBeamSearch, pareto_front, pareto_dominates, metric_delta, state_id
36
+ from .registry import TransformationRegistry, TransformationSpec
37
+ from .dataset import DatasetManifest, write_jsonl, read_jsonl
38
+
39
+ __all__ += ["Action", "Evaluation", "Objective", "PolicyState", "BeamSearchResult", "DeterministicBeamSearch", "pareto_front", "pareto_dominates", "metric_delta", "state_id", "TransformationRegistry", "TransformationSpec", "DatasetManifest", "write_jsonl", "read_jsonl"]
40
+
41
+ from .validation import validate_policy_record
42
+ __all__ += ["validate_policy_record"]
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any, Iterable
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class DatasetManifest:
12
+ dataset_id: str
13
+ schema_version: str
14
+ generator_version: str
15
+ framework: str
16
+ config: dict[str, Any]
17
+ planned_challenges: int
18
+ metadata: dict[str, Any] = field(default_factory=dict)
19
+
20
+ def to_dict(self) -> dict[str, Any]:
21
+ return {
22
+ "dataset_id": self.dataset_id,
23
+ "schema_version": self.schema_version,
24
+ "generator_version": self.generator_version,
25
+ "framework": self.framework,
26
+ "config": self.config,
27
+ "planned_challenges": self.planned_challenges,
28
+ "metadata": self.metadata,
29
+ }
30
+
31
+ @property
32
+ def sha256(self) -> str:
33
+ blob = json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"), default=str).encode()
34
+ return hashlib.sha256(blob).hexdigest()
35
+
36
+
37
+ def write_jsonl(path: str | Path, records: Iterable[dict[str, Any]], *, append: bool = False) -> int:
38
+ path = Path(path)
39
+ path.parent.mkdir(parents=True, exist_ok=True)
40
+ mode = "a" if append else "w"
41
+ n = 0
42
+ with path.open(mode, encoding="utf-8") as f:
43
+ for record in records:
44
+ f.write(json.dumps(record, sort_keys=True, default=str) + "\n")
45
+ n += 1
46
+ return n
47
+
48
+
49
+ def read_jsonl(path: str | Path) -> list[dict[str, Any]]:
50
+ out: list[dict[str, Any]] = []
51
+ with Path(path).open("r", encoding="utf-8") as f:
52
+ for line_no, line in enumerate(f, 1):
53
+ if not line.strip():
54
+ continue
55
+ try:
56
+ out.append(json.loads(line))
57
+ except json.JSONDecodeError as exc:
58
+ raise ValueError(f"invalid JSONL at line {line_no}: {exc}") from exc
59
+ return out
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Any
6
+
7
+
8
+ class RepresentationKind(str, Enum):
9
+ PROBLEM = "problem"
10
+ OPERATOR = "operator"
11
+ CIRCUIT = "circuit"
12
+ LAYOUT = "layout"
13
+ CONTROL = "control"
14
+ HARDWARE = "hardware"
15
+ EXECUTION = "execution"
16
+ EVALUATION = "evaluation"
17
+ SEARCH_STATE = "search_state"
18
+ PROGRAM = "program"
19
+ HAMILTONIAN = "hamiltonian"
20
+ RESOURCE_ESTIMATE = "resource_estimate"
21
+
22
+
23
+ class EquivalenceKind(str, Enum):
24
+ EXACT = "exact"
25
+ OBJECTIVE_EQUIVALENT = "objective_equivalent"
26
+ GROUND_STATE_EQUIVALENT = "ground_state_equivalent"
27
+ SAME_PROBLEM_DIFFERENT_DYNAMICS = "same_problem_different_dynamics"
28
+ APPROXIMATE = "approximate"
29
+ UNKNOWN = "unknown"
30
+ INVALID = "invalid"
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Representation:
35
+ id: str
36
+ kind: RepresentationKind
37
+ payload: dict[str, Any]
38
+ schema_version: str = "0.2"
39
+ semantic_root: str | None = None
40
+ framework: str | None = None
41
+ metadata: dict[str, Any] = field(default_factory=dict)
42
+
43
+ def __post_init__(self) -> None:
44
+ if not self.id.strip():
45
+ raise ValueError("representation id must be non-empty")
46
+ if not isinstance(self.payload, dict):
47
+ raise TypeError("payload must be a dict")
48
+
49
+ def to_dict(self) -> dict[str, Any]:
50
+ return {
51
+ "id": self.id,
52
+ "kind": self.kind.value,
53
+ "schema_version": self.schema_version,
54
+ "semantic_root": self.semantic_root,
55
+ "framework": self.framework,
56
+ "payload": self.payload,
57
+ "metadata": self.metadata,
58
+ }
59
+
60
+ @classmethod
61
+ def from_dict(cls, data: dict[str, Any]) -> "Representation":
62
+ return cls(
63
+ id=data["id"],
64
+ kind=RepresentationKind(data["kind"]),
65
+ schema_version=data.get("schema_version", "0.2"),
66
+ semantic_root=data.get("semantic_root"),
67
+ framework=data.get("framework"),
68
+ payload=dict(data.get("payload", {})),
69
+ metadata=dict(data.get("metadata", {})),
70
+ )
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class TransformationRecord:
75
+ id: str
76
+ input_id: str
77
+ output_id: str
78
+ transform_id: str
79
+ transform_version: str
80
+ equivalence: EquivalenceKind = EquivalenceKind.UNKNOWN
81
+ parameters: dict[str, Any] = field(default_factory=dict)
82
+ verification: dict[str, Any] = field(default_factory=dict)
83
+ outcome: dict[str, Any] = field(default_factory=dict)
84
+ metrics_before: dict[str, float | int | None] = field(default_factory=dict)
85
+ metrics_after: dict[str, float | int | None] = field(default_factory=dict)
86
+ framework: str | None = None
87
+ cost: dict[str, float | int | None] = field(default_factory=dict)
88
+
89
+ def __post_init__(self) -> None:
90
+ if not self.id.strip() or not self.transform_id.strip():
91
+ raise ValueError("transformation id fields must be non-empty")
92
+ if self.input_id == self.output_id:
93
+ raise ValueError("input_id and output_id must differ")
94
+
95
+ def to_dict(self) -> dict[str, Any]:
96
+ return {
97
+ "id": self.id,
98
+ "input_id": self.input_id,
99
+ "output_id": self.output_id,
100
+ "transform_id": self.transform_id,
101
+ "transform_version": self.transform_version,
102
+ "equivalence": self.equivalence.value,
103
+ "parameters": self.parameters,
104
+ "verification": self.verification,
105
+ "outcome": self.outcome,
106
+ "metrics_before": self.metrics_before,
107
+ "metrics_after": self.metrics_after,
108
+ "framework": self.framework,
109
+ "cost": self.cost,
110
+ }
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Protocol, runtime_checkable
5
+
6
+ from .model import Representation, TransformationRecord
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class PluginCapabilities:
11
+ import_kinds: tuple[str, ...] = ()
12
+ export_kinds: tuple[str, ...] = ()
13
+ transformations: tuple[str, ...] = ()
14
+ evaluators: tuple[str, ...] = ()
15
+ runtimes: tuple[str, ...] = ()
16
+ supports_repgraph: bool = True
17
+ supports_wqt_policy: bool = False
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class PluginManifest:
22
+ plugin_id: str
23
+ version: str
24
+ framework: str
25
+ framework_versions: str
26
+ api_version: str = "0.1"
27
+ capabilities: PluginCapabilities = field(default_factory=PluginCapabilities)
28
+
29
+
30
+ @runtime_checkable
31
+ class FrontendAdapter(Protocol):
32
+ def import_native(self, obj: Any, **context: Any) -> Representation: ...
33
+ def export_native(self, representation: Representation, **context: Any) -> Any: ...
34
+
35
+
36
+ @runtime_checkable
37
+ class TransformationProvider(Protocol):
38
+ def available_transformations(self, representation: Representation, **context: Any) -> list[str]: ...
39
+ def apply_transformation(
40
+ self, representation: Representation, transform_id: str, **context: Any
41
+ ) -> tuple[Representation, TransformationRecord]: ...
42
+
43
+
44
+ @runtime_checkable
45
+ class CompilerAdapter(Protocol):
46
+ def compile(self, representation: Representation, **context: Any) -> Representation: ...
47
+
48
+
49
+ @runtime_checkable
50
+ class EvaluatorAdapter(Protocol):
51
+ def evaluate(self, representation: Representation, **context: Any) -> dict[str, Any]: ...
52
+
53
+
54
+ @runtime_checkable
55
+ class RuntimeAdapter(Protocol):
56
+ def execute(self, representation: Representation, **context: Any) -> dict[str, Any]: ...
57
+
58
+
59
+ @runtime_checkable
60
+ class WestQuantPlugin(Protocol):
61
+ @property
62
+ def manifest(self) -> PluginManifest: ...
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Callable
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class TransformationSpec:
9
+ transform_id: str
10
+ version: str
11
+ input_kinds: tuple[str, ...]
12
+ output_kind: str
13
+ equivalence: str = "unknown"
14
+ description: str = ""
15
+ applicability: dict[str, Any] = field(default_factory=dict)
16
+ verification_method: str = "runtime"
17
+
18
+
19
+ class TransformationRegistry:
20
+ def __init__(self) -> None:
21
+ self._specs: dict[str, TransformationSpec] = {}
22
+ self._impls: dict[str, Callable[..., Any]] = {}
23
+
24
+ def register(self, spec: TransformationSpec, implementation: Callable[..., Any] | None = None) -> None:
25
+ key = f"{spec.transform_id}@{spec.version}"
26
+ if key in self._specs:
27
+ raise ValueError(f"duplicate transformation: {key}")
28
+ self._specs[key] = spec
29
+ if implementation is not None:
30
+ self._impls[key] = implementation
31
+
32
+ def get(self, transform_id: str, version: str) -> TransformationSpec:
33
+ return self._specs[f"{transform_id}@{version}"]
34
+
35
+ def implementation(self, transform_id: str, version: str) -> Callable[..., Any] | None:
36
+ return self._impls.get(f"{transform_id}@{version}")
37
+
38
+ def list(self) -> list[TransformationSpec]:
39
+ return [self._specs[k] for k in sorted(self._specs)]
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ from .model import Representation, TransformationRecord
7
+
8
+
9
+ @dataclass
10
+ class RepGraph:
11
+ graph_id: str
12
+ schema_version: str = "0.2"
13
+ nodes: dict[str, Representation] = field(default_factory=dict)
14
+ edges: list[TransformationRecord] = field(default_factory=list)
15
+ metadata: dict[str, Any] = field(default_factory=dict)
16
+
17
+ def add_representation(self, representation: Representation) -> None:
18
+ if representation.id in self.nodes:
19
+ raise ValueError(f"duplicate representation id: {representation.id}")
20
+ self.nodes[representation.id] = representation
21
+
22
+ def add_transformation(self, edge: TransformationRecord) -> None:
23
+ if edge.input_id not in self.nodes:
24
+ raise ValueError(f"missing input representation: {edge.input_id}")
25
+ if edge.output_id not in self.nodes:
26
+ raise ValueError(f"missing output representation: {edge.output_id}")
27
+ if any(existing.id == edge.id for existing in self.edges):
28
+ raise ValueError(f"duplicate transformation id: {edge.id}")
29
+ self.edges.append(edge)
30
+ if self._has_cycle():
31
+ self.edges.pop()
32
+ raise ValueError("RepGraph must remain acyclic")
33
+
34
+ def children(self, node_id: str) -> list[Representation]:
35
+ ids = [e.output_id for e in self.edges if e.input_id == node_id]
36
+ return [self.nodes[i] for i in ids]
37
+
38
+ def validate(self) -> list[str]:
39
+ errors: list[str] = []
40
+ if not self.graph_id.strip():
41
+ errors.append("graph_id is empty")
42
+ for edge in self.edges:
43
+ if edge.input_id not in self.nodes:
44
+ errors.append(f"dangling input: {edge.input_id}")
45
+ if edge.output_id not in self.nodes:
46
+ errors.append(f"dangling output: {edge.output_id}")
47
+ if self._has_cycle():
48
+ errors.append("graph contains a cycle")
49
+ return errors
50
+
51
+ def _has_cycle(self) -> bool:
52
+ adjacency: dict[str, list[str]] = {node_id: [] for node_id in self.nodes}
53
+ for edge in self.edges:
54
+ if edge.input_id in adjacency:
55
+ adjacency[edge.input_id].append(edge.output_id)
56
+
57
+ visiting: set[str] = set()
58
+ visited: set[str] = set()
59
+
60
+ def dfs(node: str) -> bool:
61
+ if node in visiting:
62
+ return True
63
+ if node in visited:
64
+ return False
65
+ visiting.add(node)
66
+ for nxt in adjacency.get(node, []):
67
+ if dfs(nxt):
68
+ return True
69
+ visiting.remove(node)
70
+ visited.add(node)
71
+ return False
72
+
73
+ return any(dfs(node) for node in adjacency if node not in visited)
74
+
75
+ def to_dict(self) -> dict[str, Any]:
76
+ return {
77
+ "schema_version": self.schema_version,
78
+ "graph_id": self.graph_id,
79
+ "metadata": self.metadata,
80
+ "nodes": [node.to_dict() for node in self.nodes.values()],
81
+ "edges": [edge.to_dict() for edge in self.edges],
82
+ }
@@ -0,0 +1,271 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Callable, Iterable, Protocol, Sequence
8
+
9
+
10
+ MetricValue = float | int | None
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Objective:
15
+ name: str
16
+ direction: str = "min"
17
+ weight: float = 1.0
18
+
19
+ def __post_init__(self) -> None:
20
+ if self.direction not in {"min", "max"}:
21
+ raise ValueError("direction must be 'min' or 'max'")
22
+
23
+ def normalize(self, value: MetricValue) -> float:
24
+ if value is None:
25
+ return math.inf
26
+ x = float(value)
27
+ return x if self.direction == "min" else -x
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Action:
32
+ stage: str
33
+ name: str
34
+ parameters: dict[str, Any] = field(default_factory=dict)
35
+
36
+ @property
37
+ def id(self) -> str:
38
+ blob = json.dumps(
39
+ {"stage": self.stage, "name": self.name, "parameters": self.parameters},
40
+ sort_keys=True,
41
+ separators=(",", ":"),
42
+ default=str,
43
+ )
44
+ return f"{self.stage}:{self.name}:{hashlib.sha256(blob.encode()).hexdigest()[:12]}"
45
+
46
+ def to_dict(self) -> dict[str, Any]:
47
+ return {"id": self.id, "stage": self.stage, "name": self.name, "parameters": self.parameters}
48
+
49
+
50
+ @dataclass
51
+ class Evaluation:
52
+ success: bool
53
+ metrics: dict[str, MetricValue] = field(default_factory=dict)
54
+ verification: dict[str, Any] = field(default_factory=dict)
55
+ error: dict[str, Any] | None = None
56
+ artifacts: dict[str, Any] = field(default_factory=dict)
57
+ cost: dict[str, MetricValue] = field(default_factory=dict)
58
+
59
+ @property
60
+ def selectable(self) -> bool:
61
+ if not self.success:
62
+ return False
63
+ equivalence = self.verification.get("equivalence")
64
+ return equivalence != "invalid"
65
+
66
+ def to_dict(self) -> dict[str, Any]:
67
+ return {
68
+ "success": self.success,
69
+ "selectable": self.selectable,
70
+ "metrics": self.metrics,
71
+ "verification": self.verification,
72
+ "error": self.error,
73
+ "artifacts": self.artifacts,
74
+ "cost": self.cost,
75
+ }
76
+
77
+
78
+ @dataclass
79
+ class PolicyState:
80
+ state_id: str
81
+ parent_state_id: str | None
82
+ step_index: int
83
+ prefix: tuple[Action, ...]
84
+ evaluation: Evaluation | None = None
85
+ kept: bool = False
86
+ terminal: bool = False
87
+
88
+ def to_dict(self) -> dict[str, Any]:
89
+ return {
90
+ "state_id": self.state_id,
91
+ "parent_state_id": self.parent_state_id,
92
+ "step_index": self.step_index,
93
+ "prefix": [a.to_dict() for a in self.prefix],
94
+ "evaluation": self.evaluation.to_dict() if self.evaluation else None,
95
+ "kept": self.kept,
96
+ "terminal": self.terminal,
97
+ }
98
+
99
+
100
+ class RolloutEvaluator(Protocol):
101
+ def __call__(self, prefix: Sequence[Action]) -> Evaluation: ...
102
+
103
+
104
+ class ActionProvider(Protocol):
105
+ def __call__(self, stage: str, prefix: Sequence[Action]) -> Iterable[Action]: ...
106
+
107
+
108
+ def state_id(challenge_id: str, prefix: Sequence[Action]) -> str:
109
+ blob = json.dumps([a.to_dict() for a in prefix], sort_keys=True, separators=(",", ":"), default=str)
110
+ return f"{challenge_id}:state:{hashlib.sha256(blob.encode()).hexdigest()[:16]}"
111
+
112
+
113
+ def pareto_dominates(a: dict[str, MetricValue], b: dict[str, MetricValue], objectives: Sequence[Objective]) -> bool:
114
+ better_or_equal = True
115
+ strictly_better = False
116
+ for obj in objectives:
117
+ av = obj.normalize(a.get(obj.name))
118
+ bv = obj.normalize(b.get(obj.name))
119
+ if av > bv:
120
+ better_or_equal = False
121
+ break
122
+ if av < bv:
123
+ strictly_better = True
124
+ return better_or_equal and strictly_better
125
+
126
+
127
+ def pareto_front(items: Sequence[Any], metrics: Callable[[Any], dict[str, MetricValue]], objectives: Sequence[Objective]) -> list[Any]:
128
+ front: list[Any] = []
129
+ for i, item in enumerate(items):
130
+ mi = metrics(item)
131
+ if any(i != j and pareto_dominates(metrics(other), mi, objectives) for j, other in enumerate(items)):
132
+ continue
133
+ front.append(item)
134
+ return front
135
+
136
+
137
+ @dataclass
138
+ class BeamSearchResult:
139
+ challenge_id: str
140
+ stages: tuple[str, ...]
141
+ beam_width: int
142
+ states: list[PolicyState]
143
+ final_beam: list[PolicyState]
144
+ objectives: tuple[Objective, ...]
145
+
146
+ @property
147
+ def best(self) -> PolicyState | None:
148
+ selectable = [s for s in self.final_beam if s.evaluation and s.evaluation.selectable]
149
+ if not selectable:
150
+ return None
151
+ return min(selectable, key=self._score_key)
152
+
153
+ def _score_key(self, state: PolicyState) -> tuple[float, ...]:
154
+ assert state.evaluation is not None
155
+ exact_penalty = 0.0 if state.evaluation.verification.get("equivalence") == "exact" else 1.0
156
+ vals = tuple(obj.normalize(state.evaluation.metrics.get(obj.name)) for obj in self.objectives)
157
+ return (exact_penalty, *vals)
158
+
159
+ def records(self, *, framework: str, context: dict[str, Any] | None = None) -> list[dict[str, Any]]:
160
+ by_id = {s.state_id: s for s in self.states}
161
+ out: list[dict[str, Any]] = []
162
+ for s in self.states:
163
+ if s.parent_state_id is None or s.evaluation is None:
164
+ continue
165
+ p = by_id.get(s.parent_state_id)
166
+ before = p.evaluation.metrics if p and p.evaluation else {}
167
+ after = s.evaluation.metrics
168
+ out.append({
169
+ "schema_version": "wqt-policy-v0.1",
170
+ "framework": framework,
171
+ "challenge_id": self.challenge_id,
172
+ "context": context or {},
173
+ "state_id": s.parent_state_id,
174
+ "next_state_id": s.state_id,
175
+ "step_index": s.step_index,
176
+ "stage": s.prefix[-1].stage,
177
+ "action": s.prefix[-1].to_dict(),
178
+ "prefix_before": [a.to_dict() for a in (p.prefix if p else ())],
179
+ "prefix_after": [a.to_dict() for a in s.prefix],
180
+ "success": s.evaluation.success,
181
+ "selectable": s.evaluation.selectable,
182
+ "verification": s.evaluation.verification,
183
+ "metrics_before": before,
184
+ "metrics_after": after,
185
+ "reward_vector": metric_delta(after, before),
186
+ "cost": s.evaluation.cost,
187
+ "kept_in_beam": s.kept,
188
+ "terminal": s.terminal,
189
+ "error": s.evaluation.error,
190
+ })
191
+ return out
192
+
193
+
194
+ def metric_delta(after: dict[str, MetricValue], before: dict[str, MetricValue]) -> dict[str, float | None]:
195
+ keys = sorted(set(after) | set(before))
196
+ out: dict[str, float | None] = {}
197
+ for k in keys:
198
+ av, bv = after.get(k), before.get(k)
199
+ if isinstance(av, (int, float)) and isinstance(bv, (int, float)):
200
+ out[k] = float(av) - float(bv)
201
+ else:
202
+ out[k] = None
203
+ return out
204
+
205
+
206
+ class DeterministicBeamSearch:
207
+ def __init__(self, *, stages: Sequence[str], beam_width: int, objectives: Sequence[Objective]) -> None:
208
+ if not stages:
209
+ raise ValueError("stages must be non-empty")
210
+ if beam_width < 1:
211
+ raise ValueError("beam_width must be >= 1")
212
+ if not objectives:
213
+ raise ValueError("at least one objective is required")
214
+ self.stages = tuple(stages)
215
+ self.beam_width = int(beam_width)
216
+ self.objectives = tuple(objectives)
217
+
218
+ def run(self, *, challenge_id: str, actions: ActionProvider, evaluate: RolloutEvaluator) -> BeamSearchResult:
219
+ root = PolicyState(
220
+ state_id=state_id(challenge_id, ()),
221
+ parent_state_id=None,
222
+ step_index=-1,
223
+ prefix=(),
224
+ evaluation=None,
225
+ kept=True,
226
+ terminal=False,
227
+ )
228
+ states = [root]
229
+ beam = [root]
230
+
231
+ for step_index, stage in enumerate(self.stages):
232
+ expanded: list[PolicyState] = []
233
+ for parent in beam:
234
+ choices = sorted(list(actions(stage, parent.prefix)), key=lambda a: (a.name, a.id))
235
+ for action in choices:
236
+ prefix = parent.prefix + (action,)
237
+ ev = evaluate(prefix)
238
+ expanded.append(PolicyState(
239
+ state_id=state_id(challenge_id, prefix),
240
+ parent_state_id=parent.state_id,
241
+ step_index=step_index,
242
+ prefix=prefix,
243
+ evaluation=ev,
244
+ kept=False,
245
+ terminal=step_index == len(self.stages) - 1,
246
+ ))
247
+ expanded.sort(key=self._state_key)
248
+ beam = [s for s in expanded if s.evaluation and s.evaluation.selectable][: self.beam_width]
249
+ for s in beam:
250
+ s.kept = True
251
+ states.extend(expanded)
252
+ if not beam:
253
+ break
254
+
255
+ return BeamSearchResult(
256
+ challenge_id=challenge_id,
257
+ stages=self.stages,
258
+ beam_width=self.beam_width,
259
+ states=states,
260
+ final_beam=beam,
261
+ objectives=self.objectives,
262
+ )
263
+
264
+ def _state_key(self, state: PolicyState) -> tuple[float, ...]:
265
+ if state.evaluation is None or not state.evaluation.selectable:
266
+ return (math.inf,) * (len(self.objectives) + 2)
267
+ exact_penalty = 0.0 if state.evaluation.verification.get("equivalence") == "exact" else 1.0
268
+ vals = tuple(obj.normalize(state.evaluation.metrics.get(obj.name)) for obj in self.objectives)
269
+ # Stable deterministic tie-breaker based on prefix action ids.
270
+ tie = int(hashlib.sha256("|".join(a.id for a in state.prefix).encode()).hexdigest()[:12], 16)
271
+ return (exact_penalty, *vals, float(tie))
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ POLICY_REQUIRED = {
5
+ "schema_version", "framework", "challenge_id", "state_id", "next_state_id",
6
+ "step_index", "stage", "action", "success", "selectable", "verification",
7
+ "metrics_before", "metrics_after", "kept_in_beam", "terminal",
8
+ }
9
+
10
+
11
+ def validate_policy_record(record: dict[str, Any]) -> list[str]:
12
+ errors=[]
13
+ missing=sorted(POLICY_REQUIRED-set(record))
14
+ if missing: errors.append(f"missing fields: {missing}")
15
+ if record.get("schema_version") != "wqt-policy-v0.1": errors.append("schema_version must be wqt-policy-v0.1")
16
+ if not isinstance(record.get("action"),dict): errors.append("action must be an object")
17
+ else:
18
+ for key in ("stage","name","parameters"):
19
+ if key not in record["action"]: errors.append(f"action missing {key}")
20
+ for key in ("success","selectable","kept_in_beam","terminal"):
21
+ if key in record and not isinstance(record[key],bool): errors.append(f"{key} must be boolean")
22
+ if isinstance(record.get("step_index"),int) and record["step_index"]<0: errors.append("step_index must be >= 0")
23
+ return errors
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: westquant-core
3
+ Version: 0.2.0a1
4
+ Summary: Core representation contracts, WQIR and RepGraph for WestQuant Open
5
+ Author: WestQuant Open / David Vesterlund
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/WestQuantOpen
8
+ Project-URL: Source, https://github.com/WestQuantOpen/westquant-core
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest>=8; extra == "test"
14
+ Dynamic: license-file
15
+
16
+ # westquant-core
17
+
18
+ Framework-neutral substrate for WestQuant Open representation search.
19
+
20
+ ## Alpha contents
21
+
22
+ - WQIR-style typed representations across problem, Hamiltonian/operator,
23
+ circuit/program, layout, control, hardware, execution, evaluation and
24
+ resource-estimation layers;
25
+ - RepGraph v0.2 DAG with explicit transformation provenance;
26
+ - Transformation Registry;
27
+ - framework-neutral plugin protocols;
28
+ - deterministic beam search with explicit state/action rollouts;
29
+ - Pareto utilities;
30
+ - dataset manifests and JSONL utilities;
31
+ - canonical `wqt-policy-v0.1` training-record schema and lightweight validator.
32
+
33
+ WQT20 is intentionally not a runtime dependency. Deterministic and heuristic
34
+ search remain fully usable without a learned model, giving a clean baseline for
35
+ future WQT20 comparisons.
@@ -0,0 +1,13 @@
1
+ westquant_core/__init__.py,sha256=eZ3amE5u-qqYF1O53dNHp1fjW8eJHkk3LUOcUn30vNs,1317
2
+ westquant_core/dataset.py,sha256=d4Ezya6hl72riRlzNgLF53ePwoQKtO6wREVNEQ_x348,1876
3
+ westquant_core/model.py,sha256=ZsCwRikEymwm8UHoIjaKP74caCtjA4FCDhIuXQeBoZc,3710
4
+ westquant_core/plugin.py,sha256=OaSzIGUR9rpi8GCJxkQtd5Cw4pWHEu4HXR2l_osI7Hw,1854
5
+ westquant_core/registry.py,sha256=2vXYSfqZJsSuB9nq6SfOxoOmKufZsZ2nBqJth_cbtnU,1363
6
+ westquant_core/repgraph.py,sha256=3VTZxRGleEUHqLegGcI-lusq34XE8xhm7zBub8O4aUM,3119
7
+ westquant_core/search.py,sha256=AQQpV8RkNHZyGsTOqCT7A9d6p8Ny6KhjUy-9YXX2-XM,9857
8
+ westquant_core/validation.py,sha256=ufV-3EGeG0luR2p-_1eHnNCl0SFT1kJHsF09LRW8IXY,1149
9
+ westquant_core-0.2.0a1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ westquant_core-0.2.0a1.dist-info/METADATA,sha256=6KEVYngPIRttY5LPwN4ui0hHfa7Cry_oZs2B5UKLQpo,1295
11
+ westquant_core-0.2.0a1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ westquant_core-0.2.0a1.dist-info/top_level.txt,sha256=XOOGbyA-Yt9T6_vQYPjZLHUJd_acMcpbkENJTjncYC8,15
13
+ westquant_core-0.2.0a1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ westquant_core