qtiming 0.1.0__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.
Files changed (102) hide show
  1. qtiming/__init__.py +0 -0
  2. qtiming/bench/__init__.py +327 -0
  3. qtiming/bench/diff.py +230 -0
  4. qtiming/bench/report.py +161 -0
  5. qtiming/bench/truth.py +88 -0
  6. qtiming/cli/__init__.py +0 -0
  7. qtiming/cli/cmd_evidence.py +35 -0
  8. qtiming/cli/main.py +398 -0
  9. qtiming/contract/__init__.py +0 -0
  10. qtiming/contract/compat.py +49 -0
  11. qtiming/contract/instances/README.md +30 -0
  12. qtiming/contract/instances/artiq.toml +45 -0
  13. qtiming/contract/instances/ibm_heron.toml +62 -0
  14. qtiming/contract/instances/ibm_heron_snapshot.json +22 -0
  15. qtiming/contract/instances/q1.toml +88 -0
  16. qtiming/contract/instances/qua.toml +65 -0
  17. qtiming/contract/loader.py +355 -0
  18. qtiming/contract/model.py +123 -0
  19. qtiming/contract/schema.py +106 -0
  20. qtiming/contract/target_import.py +46 -0
  21. qtiming/core/__init__.py +0 -0
  22. qtiming/core/ast.py +140 -0
  23. qtiming/core/errors.py +36 -0
  24. qtiming/core/ids.py +34 -0
  25. qtiming/core/labels.py +121 -0
  26. qtiming/core/provenance.py +77 -0
  27. qtiming/core/time.py +96 -0
  28. qtiming/dispatch/__init__.py +22 -0
  29. qtiming/dispatch/artiq.py +70 -0
  30. qtiming/dispatch/ibm.py +83 -0
  31. qtiming/dispatch/q1.py +102 -0
  32. qtiming/dispatch/qua.py +88 -0
  33. qtiming/elab/__init__.py +360 -0
  34. qtiming/evidence/__init__.py +15 -0
  35. qtiming/evidence/ingest.py +235 -0
  36. qtiming/exec/__init__.py +0 -0
  37. qtiming/exec/artiq.py +100 -0
  38. qtiming/exec/engine.py +235 -0
  39. qtiming/exec/explore.py +43 -0
  40. qtiming/exec/ibm.py +117 -0
  41. qtiming/exec/oracle.py +88 -0
  42. qtiming/exec/q1.py +95 -0
  43. qtiming/exec/qua.py +95 -0
  44. qtiming/frontend/__init__.py +40 -0
  45. qtiming/frontend/_shared.py +149 -0
  46. qtiming/frontend/annotations.py +81 -0
  47. qtiming/frontend/lint.py +116 -0
  48. qtiming/frontend/payload.py +113 -0
  49. qtiming/frontend/program.py +51 -0
  50. qtiming/frontend/qasm3_fe.py +341 -0
  51. qtiming/frontend/qiskit_expr.py +89 -0
  52. qtiming/frontend/qiskit_fe.py +220 -0
  53. qtiming/frontend/serialise.py +63 -0
  54. qtiming/frontend/stretch.py +71 -0
  55. qtiming/graph/__init__.py +0 -0
  56. qtiming/graph/builder.py +245 -0
  57. qtiming/graph/export.py +25 -0
  58. qtiming/graph/invariants.py +67 -0
  59. qtiming/graph/lteg.py +153 -0
  60. qtiming/graph/window.py +120 -0
  61. qtiming/oblig/__init__.py +0 -0
  62. qtiming/oblig/generate.py +145 -0
  63. qtiming/oblig/model.py +76 -0
  64. qtiming/py.typed +0 -0
  65. qtiming/qiskit_pass/__init__.py +7 -0
  66. qtiming/qiskit_pass/_common.py +21 -0
  67. qtiming/qiskit_pass/equalize.py +171 -0
  68. qtiming/qiskit_pass/plugin.py +23 -0
  69. qtiming/qiskit_pass/strip.py +42 -0
  70. qtiming/qiskit_pass/timing_check.py +40 -0
  71. qtiming/repair/__init__.py +0 -0
  72. qtiming/repair/suggest.py +146 -0
  73. qtiming/solve/__init__.py +0 -0
  74. qtiming/solve/concrete.py +148 -0
  75. qtiming/solve/dispatcher.py +55 -0
  76. qtiming/solve/interval.py +185 -0
  77. qtiming/solve/smt.py +167 -0
  78. qtiming/solve/smt_o5.py +1 -0
  79. qtiming/solve/synth/__init__.py +0 -0
  80. qtiming/solve/synth/bruteforce_dc.py +156 -0
  81. qtiming/solve/synth/model.py +59 -0
  82. qtiming/solve/synth/relax.py +93 -0
  83. qtiming/solve/synth/rigid.py +33 -0
  84. qtiming/solve/synth/sc.py +55 -0
  85. qtiming/solve/synth/stn.py +74 -0
  86. qtiming/solve/synth/stnu_dc.py +93 -0
  87. qtiming/verdict/__init__.py +0 -0
  88. qtiming/verdict/minimise.py +45 -0
  89. qtiming/verdict/model.py +107 -0
  90. qtiming/verdict/render.py +72 -0
  91. qtiming/verdict/render_html.py +80 -0
  92. qtiming/verdict/render_json.py +12 -0
  93. qtiming/verdict/render_sarif.py +104 -0
  94. qtiming/verdict/replay.py +77 -0
  95. qtiming/verdict/run.py +174 -0
  96. qtiming/verdict/rus.py +53 -0
  97. qtiming-0.1.0.dist-info/METADATA +262 -0
  98. qtiming-0.1.0.dist-info/RECORD +102 -0
  99. qtiming-0.1.0.dist-info/WHEEL +4 -0
  100. qtiming-0.1.0.dist-info/entry_points.txt +6 -0
  101. qtiming-0.1.0.dist-info/licenses/LICENSE +177 -0
  102. qtiming-0.1.0.dist-info/licenses/NOTICE +8 -0
@@ -0,0 +1,106 @@
1
+ """Pydantic v2 input models. Floats are rejected in time fields (strict str|int only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fractions import Fraction
6
+ from typing import Any, Literal, Union
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, model_validator
9
+
10
+ Num = Union[StrictStr, StrictInt] # noqa: UP007 decimal string or int; never float
11
+
12
+ PROV = Literal["vendor", "msigma", "pctl", "mmax", "sched", "cyc", "cert"]
13
+ LATE = Literal["raise", "drop_log", "delay", "defer_round", "halt", "compile_error", "mixed"]
14
+ _FROZEN = ConfigDict(extra="forbid", frozen=True, populate_by_name=True)
15
+
16
+
17
+ def frac(x: Num) -> Fraction:
18
+ """Exact decimal parse (never via float)."""
19
+ return Fraction(str(x))
20
+
21
+
22
+ class Meta(BaseModel):
23
+ model_config = _FROZEN
24
+ name: str
25
+ version: str
26
+ schema_: Literal["qtiming-contract/0.2"] = Field(alias="schema")
27
+ personality: Literal["ibm", "artiq", "q1", "qua"]
28
+
29
+
30
+ class LatencyIn(BaseModel):
31
+ model_config = _FROZEN
32
+ key: str
33
+ src: str
34
+ dst: str
35
+ tier: str = "default"
36
+ lo_ns: Num = 0
37
+ hi_ns: Num | None = None # None = unbounded; dependants are UNKNOWN
38
+ data_dependent: StrictBool = False
39
+ prov: PROV
40
+ source: str
41
+ n: StrictInt | None = None
42
+ p: Num | None = None
43
+ load: str | None = None
44
+ k_sigma: Num | None = None
45
+ placeholder: StrictBool = False
46
+ meta: dict[str, str] = {}
47
+
48
+ @model_validator(mode="after")
49
+ def _check(self) -> LatencyIn:
50
+ if self.prov == "mmax" and self.n is None:
51
+ raise ValueError("prov=mmax requires n")
52
+ if self.prov == "pctl" and (self.p is None or self.load is None):
53
+ raise ValueError("prov=pctl requires p and load")
54
+ if self.prov == "msigma" and self.k_sigma is None:
55
+ raise ValueError("prov=msigma requires k_sigma")
56
+ if self.prov in ("msigma", "pctl") and self.hi_ns is None:
57
+ raise ValueError("msigma/pctl entries must state hi_ns explicitly; hi is never derived")
58
+ if self.hi_ns is not None and frac(self.lo_ns) > frac(self.hi_ns):
59
+ raise ValueError(f"lo_ns {self.lo_ns} > hi_ns {self.hi_ns}")
60
+ return self
61
+
62
+
63
+ class Branch(BaseModel):
64
+ model_config = _FROZEN
65
+ klass: Literal["predicated", "equalized", "resync", "exposed", "restricted"] = Field(
66
+ alias="class")
67
+ default_policy: Literal["eq", "sync", "exp"]
68
+ allow_nested: bool = True
69
+ allow_measure_in_branch: bool = True
70
+ allow_loops: bool = True
71
+ max_cond_bits: int = 64
72
+
73
+
74
+ class Timebase(BaseModel):
75
+ model_config = _FROZEN
76
+ dt_ns: Num # "from_target" allowed only when [target] present
77
+ grid: dict[str, StrictInt] = {}
78
+ latency_resolution: Literal["continuous", "dt"] = "continuous"
79
+
80
+
81
+ class Timeline(BaseModel):
82
+ model_config = _FROZEN
83
+ late_policy: LATE
84
+ commit_lead: Any = None # number (ns) or {lo_ns, prov}
85
+
86
+
87
+ class ContractIn(BaseModel):
88
+ model_config = _FROZEN
89
+ meta: Meta
90
+ target: dict[str, Any] | None = None
91
+ timebase: Timebase
92
+ timeline: Timeline
93
+ issue_cost: dict[str, Any] = {}
94
+ capacity: dict[str, Any] = {}
95
+ durations: dict[str, Any] = {}
96
+ latency: list[LatencyIn] = Field(min_length=1)
97
+ topology: dict[str, Any] | None = None
98
+ feedback_tier: list[dict[str, Any]] = []
99
+ branch: Branch
100
+ personality_params: dict[str, Any] = {}
101
+ dep: list[dict[str, Any]] = []
102
+ domain_call: list[dict[str, Any]] = []
103
+ sync: dict[str, Any] | None = None
104
+ idle: dict[str, Any] = {}
105
+ loop: dict[str, Any] = {}
106
+ evidence: list[dict[str, Any]] = []
@@ -0,0 +1,46 @@
1
+ """Backend Target -> snapshot dict (Section 7.4). Duck-typed: needs no qiskit import.
2
+
3
+ A snapshot is plain JSON so CI never needs network access:
4
+ {"backend", "dt_ns", "alignments": {...}, "durations_ns": {name: ns}, "ambiguous": [...]}
5
+ Durations that differ across qubit tuples are NOT guessed; they are listed in `ambiguous`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from fractions import Fraction
11
+ from typing import Any
12
+
13
+
14
+ def _dec(x: Fraction) -> str:
15
+ return str(x.numerator) if x.denominator == 1 else f"{x.numerator}/{x.denominator}"
16
+
17
+
18
+ def snapshot_from_target(target: Any, backend: str) -> dict[str, Any]:
19
+ dt_ns = Fraction(str(target.dt)) * 10**9
20
+ if (dt_ns * 1000).denominator != 1: # must be an integer number of picoseconds
21
+ raise ValueError(f"target dt = {target.dt} s is not an integer number of picoseconds")
22
+ aligns = {
23
+ "acquire": target.acquire_alignment,
24
+ "pulse": target.pulse_alignment,
25
+ "granularity": target.granularity,
26
+ "min_length": target.min_length,
27
+ }
28
+ durations: dict[str, str] = {}
29
+ ambiguous: list[str] = []
30
+ for name in target.operation_names:
31
+ vals = {
32
+ Fraction(str(p.duration)) * 10**9
33
+ for p in target[name].values()
34
+ if p is not None and p.duration is not None
35
+ }
36
+ if len(vals) == 1:
37
+ durations[name] = _dec(vals.pop())
38
+ elif len(vals) > 1:
39
+ ambiguous.append(name)
40
+ return {
41
+ "backend": backend,
42
+ "dt_ns": _dec(dt_ns),
43
+ "alignments": aligns,
44
+ "durations_ns": durations,
45
+ "ambiguous": sorted(ambiguous),
46
+ }
File without changes
qtiming/core/ast.py ADDED
@@ -0,0 +1,140 @@
1
+ """TQ: the timed-OpenQASM-3 core syntax tree. Frozen, hashable, stdlib only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal, Union
7
+
8
+ from .labels import Expr
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class SourceLoc:
13
+ file: str
14
+ line: int = 0
15
+ col: int = 0
16
+ instr: int | None = None # Qiskit instruction index when no text position exists
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class BitRef:
21
+ reg: str # register NAME, not a Clbit object (finding F14)
22
+ idx: int
23
+
24
+
25
+ PolicyKind = Literal["eq", "sync", "exp"]
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Policy:
30
+ kind: PolicyKind
31
+ delta: int | None = None # SYNC spread bound (dt, rounded DOWN by the loader)
32
+ gap: int | None = None # SYNC per-resource gap bound G (dt)
33
+
34
+
35
+ @dataclass(frozen=True, slots=True, kw_only=True)
36
+ class Node:
37
+ nid: int
38
+ loc: SourceLoc
39
+ origin_nid: int | None = None # set by elaboration for synthesised nodes
40
+
41
+
42
+ @dataclass(frozen=True, slots=True, kw_only=True)
43
+ class Gate(Node):
44
+ name: str
45
+ qubits: tuple[int, ...]
46
+ dur: int
47
+
48
+
49
+ @dataclass(frozen=True, slots=True, kw_only=True)
50
+ class Delay(Node):
51
+ qubits: tuple[int, ...]
52
+ dur: int
53
+ declared: bool = True # declared delays are intentional idle (O4a exempt)
54
+
55
+
56
+ @dataclass(frozen=True, slots=True, kw_only=True)
57
+ class Barrier(Node):
58
+ qubits: tuple[int, ...]
59
+
60
+
61
+ @dataclass(frozen=True, slots=True, kw_only=True)
62
+ class Measure(Node):
63
+ qubit: int
64
+ cbit: BitRef
65
+ variant: Literal["std", "mid"] = "std"
66
+ tier: str = "default"
67
+
68
+
69
+ @dataclass(frozen=True, slots=True, kw_only=True)
70
+ class Reset(Node):
71
+ qubit: int
72
+
73
+
74
+ @dataclass(frozen=True, slots=True, kw_only=True)
75
+ class Assign(Node):
76
+ var: str
77
+ expr: Expr
78
+
79
+
80
+ @dataclass(frozen=True, slots=True, kw_only=True)
81
+ class Seq(Node):
82
+ stmts: tuple[Stmt, ...]
83
+
84
+
85
+ @dataclass(frozen=True, slots=True, kw_only=True)
86
+ class Box(Node):
87
+ dur: int | None # None: duration is the body's (stretch already resolved by the front end)
88
+ body: Stmt
89
+ annotations: tuple[tuple[str, str], ...] = ()
90
+
91
+
92
+ @dataclass(frozen=True, slots=True, kw_only=True)
93
+ class If(Node):
94
+ cond: Expr
95
+ then_: Stmt
96
+ else_: Stmt | None = None
97
+ policy: Policy | None = None # None = contract default until elaboration
98
+
99
+
100
+ @dataclass(frozen=True, slots=True, kw_only=True)
101
+ class Switch(Node):
102
+ target: Expr
103
+ cases: tuple[tuple[int, Stmt], ...]
104
+ default: Stmt | None = None
105
+
106
+
107
+ @dataclass(frozen=True, slots=True, kw_only=True)
108
+ class For(Node):
109
+ var: str
110
+ n: int # static
111
+ body: Stmt
112
+
113
+
114
+ @dataclass(frozen=True, slots=True, kw_only=True)
115
+ class While(Node):
116
+ cond: Expr
117
+ body: Stmt
118
+ cap: int # mandatory
119
+ exhaust: Stmt # mandatory handler
120
+ policy: Policy | None = None
121
+
122
+
123
+ @dataclass(frozen=True, slots=True, kw_only=True)
124
+ class Call(Node):
125
+ fn: str
126
+ args: tuple[str, ...]
127
+ latency_key: str
128
+ blocking: bool = True
129
+
130
+
131
+ @dataclass(frozen=True, slots=True, kw_only=True)
132
+ class Within(Node):
133
+ deadline: int # dt
134
+ anchor: BitRef
135
+ body: Stmt
136
+
137
+
138
+ Stmt = Union[ # noqa: UP007
139
+ Gate, Delay, Barrier, Measure, Reset, Assign, Seq, Box, If, Switch, For, While, Call, Within
140
+ ]
qtiming/core/errors.py ADDED
@@ -0,0 +1,36 @@
1
+ """Structured errors shared by every stage. Stdlib only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Literal
6
+
7
+ if TYPE_CHECKING:
8
+ from .ast import SourceLoc
9
+
10
+ Severity = Literal["error", "warning", "note"]
11
+
12
+
13
+ class QtError(Exception):
14
+ """A diagnostic with a stable `code` (also the SARIF ruleId).
15
+
16
+ Not a frozen dataclass: frozen Exception subclasses break when Python sets
17
+ `__traceback__` / `__context__` on them.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ code: str,
23
+ message: str,
24
+ loc: SourceLoc | None = None,
25
+ hint: str | None = None,
26
+ severity: Severity = "error",
27
+ ) -> None:
28
+ super().__init__(code, message)
29
+ self.code = code
30
+ self.message = message
31
+ self.loc = loc
32
+ self.hint = hint
33
+ self.severity = severity
34
+
35
+ def __str__(self) -> str:
36
+ return f"{self.code}: {self.message}"
qtiming/core/ids.py ADDED
@@ -0,0 +1,34 @@
1
+ """Stable node ids and proposition keys (occurrence-keyed, so loop iterations stay distinct)."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class IdGen:
7
+ """Source-order nid generator. One per front-end run; ids are never recomputed."""
8
+
9
+ def __init__(self) -> None:
10
+ self._n = 0
11
+
12
+ def next(self) -> int:
13
+ n = self._n
14
+ self._n += 1
15
+ return n
16
+
17
+
18
+ def _iter(it: int | None) -> str:
19
+ return "" if it is None else f"#i{it}"
20
+
21
+
22
+ def bit_prop(reg: str, idx: int, nid: int, it: int | None = None) -> str:
23
+ """Bit written by measurement node `nid` (iteration `it`): 'c[0]@m17#i3'."""
24
+ return f"{reg}[{idx}]@m{nid}{_iter(it)}"
25
+
26
+
27
+ def cond_prop(nid: int, it: int | None = None) -> str:
28
+ """Derived proposition for the condition of node `nid`: 'cond@n42#i3'."""
29
+ return f"cond@n{nid}{_iter(it)}"
30
+
31
+
32
+ def lat_occurrence(key: str, meas_nid: int, it: int | None = None) -> str:
33
+ """One contingent latency occurrence (key + the measurement it follows): 'ff.default@m17#i3'."""
34
+ return f"{key}@m{meas_nid}{_iter(it)}"
qtiming/core/labels.py ADDED
@@ -0,0 +1,121 @@
1
+ """Propositions, labels (conjunctions of literals) and the classical expression language."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Union
8
+
9
+ from .errors import QtError
10
+
11
+ Prop = str # "c[0]@m17#i3" (bit) or "cond@n42#i3" (derived)
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class Lit:
16
+ prop: Prop
17
+ pos: bool = True
18
+
19
+
20
+ Label = frozenset[Lit] # conjunction of literals; empty = always true
21
+ TOP: Label = frozenset()
22
+
23
+
24
+ def consistent(a: Label, b: Label) -> bool:
25
+ return not any(Lit(lit.prop, not lit.pos) in b for lit in a)
26
+
27
+
28
+ def conj(a: Label, b: Label) -> Label | None:
29
+ return None if not consistent(a, b) else a | b
30
+
31
+
32
+ def implies(a: Label, b: Label) -> bool:
33
+ """Every literal of b appears in a."""
34
+ return b <= a
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class EBit:
39
+ prop: Prop
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class EConst:
44
+ value: int
45
+ width: int = 1
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class EVar:
50
+ name: str
51
+ width: int
52
+
53
+
54
+ @dataclass(frozen=True, slots=True)
55
+ class EUn:
56
+ op: str # "not", "bit_not"
57
+ a: Expr
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class EBin:
62
+ op: str
63
+ a: Expr
64
+ b: Expr
65
+
66
+
67
+ Expr = Union[EBit, EConst, EVar, EUn, EBin] # noqa: UP007 (runtime alias, py3.10-safe)
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class Derived:
72
+ prop: Prop # "cond@n42#i3"
73
+ expr: Expr # exact definition over bit propositions / variables
74
+ operands: tuple[Prop, ...] # bit propositions the expression reads
75
+
76
+
77
+ _BIN: dict[str, Callable[[int, int], int]] = {
78
+ "and": lambda x, y: int(bool(x) and bool(y)),
79
+ "or": lambda x, y: int(bool(x) or bool(y)),
80
+ "xor": lambda x, y: x ^ y,
81
+ "bit_xor": lambda x, y: x ^ y,
82
+ "bit_and": lambda x, y: x & y,
83
+ "bit_or": lambda x, y: x | y,
84
+ "eq": lambda x, y: int(x == y),
85
+ "ne": lambda x, y: int(x != y),
86
+ "lt": lambda x, y: int(x < y),
87
+ "le": lambda x, y: int(x <= y),
88
+ "gt": lambda x, y: int(x > y),
89
+ "ge": lambda x, y: int(x >= y),
90
+ "add": lambda x, y: x + y,
91
+ "sub": lambda x, y: x - y,
92
+ "mul": lambda x, y: x * y,
93
+ }
94
+
95
+
96
+ def evaluate(e: Expr, env: Mapping[str, int]) -> int:
97
+ """Exact evaluation over bit/variable values in `env` (the executor's source of truth)."""
98
+ if isinstance(e, EConst):
99
+ return e.value
100
+ if isinstance(e, EBit):
101
+ return _lookup(env, e.prop)
102
+ if isinstance(e, EVar):
103
+ return _lookup(env, e.name)
104
+ if isinstance(e, EUn):
105
+ v = evaluate(e.a, env)
106
+ if e.op == "not":
107
+ return int(not v)
108
+ if e.op == "bit_not":
109
+ return ~v
110
+ raise QtError("E-LABEL-OP", f"unknown unary operator {e.op!r}")
111
+ fn = _BIN.get(e.op)
112
+ if fn is None:
113
+ raise QtError("E-LABEL-OP", f"unknown binary operator {e.op!r}")
114
+ return fn(evaluate(e.a, env), evaluate(e.b, env))
115
+
116
+
117
+ def _lookup(env: Mapping[str, int], key: str) -> int:
118
+ try:
119
+ return env[key]
120
+ except KeyError:
121
+ raise QtError("E-LABEL-UNBOUND", f"no value for {key!r}") from None
@@ -0,0 +1,77 @@
1
+ """Structured provenance and assumption sets (finding F8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from enum import IntEnum
8
+ from fractions import Fraction
9
+
10
+
11
+ class ProvClass(IntEnum):
12
+ """Evidence class, ordered by strength. The order only NAMES the weakest class.
13
+
14
+ VENDOR documentation claim; MSIGMA mean+spread; PCTL percentile under a load;
15
+ MMAX sample maximum over n runs; SCHED scheduler-reported value for one compiled job;
16
+ CYC cycle-counted design bound; CERT formally certified worst case.
17
+ """
18
+
19
+ VENDOR = 0
20
+ MSIGMA = 1
21
+ PCTL = 2
22
+ MMAX = 3
23
+ SCHED = 4
24
+ CYC = 5
25
+ CERT = 6
26
+
27
+ @property
28
+ def may_discharge_hard(self) -> bool:
29
+ return self >= ProvClass.CYC
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Prov:
34
+ cls: ProvClass
35
+ source: str # citation, URL, job id, measurement id
36
+ n: int | None = None # MMAX: sample count
37
+ p: Fraction | None = None # PCTL: percentile
38
+ load: str | None = None # PCTL: stated load
39
+ k_sigma: Fraction | None = None # MSIGMA: k used by whoever STATED hi
40
+ meta: tuple[tuple[str, str], ...] = ()
41
+
42
+ def __post_init__(self) -> None:
43
+ if self.cls == ProvClass.MMAX and self.n is None:
44
+ raise ValueError("mmax provenance requires n")
45
+ if self.cls == ProvClass.PCTL and (self.p is None or self.load is None):
46
+ raise ValueError("pctl provenance requires p and load")
47
+ if self.cls == ProvClass.MSIGMA and self.k_sigma is None:
48
+ raise ValueError("msigma provenance requires k_sigma")
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class Assumption:
53
+ """One latency value a proof relied on. The verdict lists all of them."""
54
+
55
+ key: str # contract latency key, e.g. "ff.intra"
56
+ lo: int # dt
57
+ hi: int | None # dt
58
+ prov: Prov
59
+
60
+
61
+ def weakest(assumptions: Iterable[Assumption]) -> ProvClass | None:
62
+ """Weakest class among the assumptions; None for an empty set."""
63
+ classes = [a.prov.cls for a in assumptions]
64
+ return min(classes) if classes else None
65
+
66
+
67
+ def combine(*sets: frozenset[Assumption]) -> frozenset[Assumption]:
68
+ """Union. The full list is kept; it is never collapsed to a single class."""
69
+ out: set[Assumption] = set()
70
+ for s in sets:
71
+ out |= s
72
+ return frozenset(out)
73
+
74
+
75
+ def can_discharge(hard: bool, assumptions: frozenset[Assumption]) -> bool:
76
+ """A hard obligation may be discharged only if every assumption is CYC or CERT."""
77
+ return (not hard) or all(a.prov.cls.may_discharge_hard for a in assumptions)
qtiming/core/time.py ADDED
@@ -0,0 +1,96 @@
1
+ """Integer `dt` time, intervals, and ns -> dt conversion rounded by ROLE (finding F7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from fractions import Fraction
7
+ from typing import Literal
8
+
9
+ from .errors import QtError
10
+ from .provenance import Prov
11
+
12
+ Dt = int # integer multiples of the backend dt
13
+ Time = Fraction # solver / executor time (exact rational, in dt)
14
+
15
+ Role = Literal[
16
+ "latency_lo", # uncertain interval lower end -> floor (outward)
17
+ "latency_hi", # uncertain interval upper end -> ceil (outward)
18
+ "deadline", # upper-bound requirement D -> floor (tighter)
19
+ "gap_bound", # upper-bound requirement G -> floor (tighter)
20
+ "spread_bound", # upper-bound requirement Delta -> floor (tighter)
21
+ "commit_lead", # lower-bound requirement -> ceil (tighter)
22
+ "min_separation", # lower-bound requirement -> ceil (tighter)
23
+ "exact", # fixed gate / measure duration -> must be an exact multiple of dt
24
+ ]
25
+
26
+ _ROUND: dict[str, str] = {
27
+ "latency_lo": "floor",
28
+ "latency_hi": "ceil",
29
+ "deadline": "floor",
30
+ "gap_bound": "floor",
31
+ "spread_bound": "floor",
32
+ "commit_lead": "ceil",
33
+ "min_separation": "ceil",
34
+ "exact": "exact",
35
+ }
36
+
37
+
38
+ def ns_to_dt(ns: Fraction | int | str, dt_ns: Fraction, role: Role, *, what: str = "") -> Dt:
39
+ """Convert nanoseconds to integer dt, rounding in the SOUND direction for `role`.
40
+
41
+ `ns` must be a Fraction, int or decimal string (never a float): the loader converts TOML
42
+ floats with Fraction(str(x)) so 0.1 never becomes 0.1000000000000000055.
43
+ """
44
+ q = Fraction(ns) / Fraction(dt_ns)
45
+ mode = _ROUND[role]
46
+ if mode == "floor":
47
+ return q.numerator // q.denominator
48
+ if mode == "ceil":
49
+ return -((-q.numerator) // q.denominator)
50
+ if q.denominator != 1:
51
+ raise QtError(
52
+ "E-TIME-EXACT",
53
+ f"{what or 'value'} = {ns} ns is not an integer multiple of dt = {dt_ns} ns",
54
+ hint="fix the contract or Target; fixed durations must be exact",
55
+ )
56
+ return q.numerator
57
+
58
+
59
+ def dt_to_ns(x: Time | Dt, dt_ns: Fraction) -> Fraction:
60
+ return Fraction(x) * Fraction(dt_ns)
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class Interval:
65
+ """Closed interval [lo, hi] of dt; hi=None means unbounded above (dependants are UNKNOWN)."""
66
+
67
+ lo: Dt
68
+ hi: Dt | None
69
+
70
+ def __post_init__(self) -> None:
71
+ if self.hi is not None and self.lo > self.hi:
72
+ raise QtError("E-INTERVAL", f"empty interval [{self.lo}, {self.hi}]")
73
+
74
+ @property
75
+ def bounded(self) -> bool:
76
+ return self.hi is not None
77
+
78
+ def __add__(self, o: Interval) -> Interval:
79
+ hi = None if self.hi is None or o.hi is None else self.hi + o.hi
80
+ return Interval(self.lo + o.lo, hi)
81
+
82
+ def hull(self, o: Interval) -> Interval:
83
+ hi = None if self.hi is None or o.hi is None else max(self.hi, o.hi)
84
+ return Interval(min(self.lo, o.lo), hi)
85
+
86
+ def contains(self, x: Time | Dt) -> bool:
87
+ return self.lo <= x and (self.hi is None or x <= self.hi)
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class Latency:
92
+ """A named uncertain latency from the contract: interval plus structured provenance."""
93
+
94
+ key: str # contract name, e.g. "ff.default"
95
+ iv: Interval
96
+ prov: Prov
@@ -0,0 +1,22 @@
1
+ """Personality dispatch rules: each builder subclasses the common LTEG builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from qtiming.contract.model import Contract
6
+ from qtiming.core.ast import Stmt
7
+ from qtiming.graph.builder import GraphBuilder
8
+ from qtiming.graph.lteg import LTEG
9
+
10
+ from .artiq import ArtiqBuilder
11
+ from .ibm import IbmBuilder
12
+ from .q1 import Q1Builder
13
+ from .qua import QuaBuilder
14
+
15
+ BUILDERS: dict[str, type[GraphBuilder]] = {
16
+ "ibm": IbmBuilder, "q1": Q1Builder, "artiq": ArtiqBuilder, "qua": QuaBuilder,
17
+ }
18
+
19
+
20
+ def build_graph(prog: Stmt, contract: Contract) -> LTEG:
21
+ """The LTEG of an ELABORATED program under the contract's personality."""
22
+ return BUILDERS[contract.personality](contract).build(prog)