API Reference¶
Core Modules¶
qgate.config
¶
config.py — Pydantic v2 configuration models for qgate.
All configuration objects are JSON-serialisable, immutable (frozen=True),
and carry field-level validation.
Patent pending (see LICENSE)
ThresholdMode = Literal['fixed', 'rolling_z', 'galton']
module-attribute
¶
Threshold adaptation strategy.
"fixed"— Static threshold (no adaptation)."rolling_z"— Legacy rolling z-score gating (existing behaviour)."galton"— Distribution-aware adaptive gating inspired by diffusion / central-limit principles. Supports both empirical-quantile and z-score sub-modes.
ConditioningVariant
¶
AdapterKind
¶
Bases: str, Enum
Known adapter back-ends.
Source code in src/qgate/config.py
FusionConfig
¶
Bases: BaseModel
Parameters for α-weighted LF / HF score fusion.
Attributes:
| Name | Type | Description |
|---|---|---|
alpha |
float
|
Weight for the low-frequency component (0 ≤ α ≤ 1). |
threshold |
float
|
Accept if combined score ≥ threshold. |
hf_cycles |
Optional[List[int]]
|
Explicit list of cycle indices counted as HF
( |
lf_cycles |
Optional[List[int]]
|
Explicit list of cycle indices counted as LF
( |
Source code in src/qgate/config.py
DynamicThresholdConfig
¶
Bases: BaseModel
Parameters for dynamic threshold gating.
Supports three modes:
"fixed" (default)
No adaptation — uses baseline as a static threshold.
"rolling_z"
Legacy rolling z-score gating:
.. math:: \theta_t = \text{clamp}(\mu_{\text{roll}} + z \cdot \sigma_{\text{roll}},\; \theta_{\min},\; \theta_{\max})
"galton"
Distribution-aware adaptive gating inspired by diffusion /
central-limit principles. The algorithm maintains a rolling window
of per-shot combined scores and sets the threshold so that a
target fraction of future scores is expected to be accepted.
Two sub-modes are available:
* **Quantile** (``use_quantile=True``, recommended) — sets
:math:`\theta = Q_{1 - \text{target\_acceptance}}(\text{window})`.
* **Z-score** — estimates μ and σ from the window, then
:math:`\theta = \mu + z_{\sigma} \cdot \sigma`. When
``robust_stats=True`` the median and MAD-based σ are used.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether dynamic thresholding is active. |
mode |
ThresholdMode
|
Threshold strategy ( |
baseline |
float
|
Starting / fallback threshold. |
z_factor |
float
|
Std-dev multiplier for |
window_size |
int
|
Rolling window capacity (batches for rolling_z, individual scores for galton). |
min_threshold |
float
|
Floor — threshold never drops below this. |
max_threshold |
float
|
Ceiling — threshold never exceeds this. |
min_window_size |
int
|
Galton mode: minimum observations before adaptation kicks in (warmup). |
target_acceptance |
float
|
Galton quantile mode: target acceptance fraction (one-sided tail). |
robust_stats |
bool
|
Galton z-score mode: use median + MAD instead of mean + std. |
use_quantile |
bool
|
Galton mode: prefer empirical quantile (True, default) over z-score. |
z_sigma |
float
|
Galton z-score mode: number of σ above centre to place the gate. |
.. note::
Setting mode="galton" automatically sets enabled=True
during validation. You do not need to set both.
Source code in src/qgate/config.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
ProbeConfig
¶
Bases: BaseModel
Probe-based batch abort configuration.
Before running a full batch a small probe batch is executed.
If the probe pass-rate is below theta the full batch is skipped.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether probing is active. |
probe_shots |
int
|
Number of probe shots. |
theta |
float
|
Minimum probe pass-rate to proceed. |
Source code in src/qgate/config.py
GateConfig
¶
Bases: BaseModel
Top-level configuration for a qgate trajectory-filter run.
Compose this from the sub-configs above, or load from JSON / YAML:
config = GateConfig.model_validate_json(path.read_text())
Attributes:
| Name | Type | Description |
|---|---|---|
schema_version |
str
|
Configuration schema version (for forward compat). |
n_subsystems |
int
|
Number of Bell-pair subsystems. |
n_cycles |
int
|
Number of monitoring cycles per shot. |
shots |
int
|
Total shots to execute per configuration. |
variant |
ConditioningVariant
|
Conditioning strategy to apply. |
k_fraction |
float
|
For hierarchical variant — required pass fraction. |
fusion |
FusionConfig
|
Fusion scoring parameters. |
dynamic_threshold |
DynamicThresholdConfig
|
Rolling z-score threshold adaptation. |
probe |
ProbeConfig
|
Probe-based batch abort. |
adapter |
AdapterKind
|
Which adapter back-end to use. |
adapter_options |
Dict[str, Any]
|
Arbitrary adapter-specific options (e.g. backend name). |
metadata |
Dict[str, Any]
|
Free-form metadata dict attached to run logs. |
Source code in src/qgate/config.py
qgate.filter
¶
filter.py — TrajectoryFilter: the main qgate API entry-point.
Orchestrates adapter → execute → score → threshold → accept/reject → log.
Usage::
from qgate import TrajectoryFilter, GateConfig
from qgate.adapters import MockAdapter
config = GateConfig(n_subsystems=4, n_cycles=2, shots=1024)
adapter = MockAdapter(error_rate=0.05, seed=42)
tf = TrajectoryFilter(config, adapter)
result = tf.run()
print(result.acceptance_probability)
Patent pending (see LICENSE)
TrajectoryFilter
¶
Main API class — build, run, and filter quantum trajectories.
Typical workflow::
tf = TrajectoryFilter(config, adapter)
result = tf.run() # build → execute → filter
result = tf.filter(outcomes) # filter pre-existing data
result = tf.filter_counts(counts) # filter from count dict
The adapter argument accepts:
- A :class:BaseAdapter instance (existing usage).
- A :class:BaseAdapter subclass (instantiated with no args).
- An adapter name string (e.g. "mock", "qiskit")
resolved via entry-point discovery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
GateConfig
|
:class: |
required |
adapter
|
BaseAdapter | type | str
|
Backend adapter — instance, class, or registered name. |
required |
logger
|
RunLogger | None
|
Optional :class: |
None
|
Source code in src/qgate/filter.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
current_threshold
property
¶
The current effective threshold (may be dynamic).
galton_snapshot
property
¶
The latest :class:GaltonSnapshot, or None if not in galton mode.
run()
¶
Build circuit → execute → parse → filter → return result.
This is the high-level "do everything" method.
Source code in src/qgate/filter.py
filter(outcomes)
¶
Apply the configured conditioning + thresholding to outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcomes
|
Sequence[ParityOutcome]
|
List of ParityOutcome (one per shot). May be empty. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
class: |
Source code in src/qgate/filter.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
filter_counts(counts, n_subsystems=None, n_cycles=None)
¶
Filter from a pre-existing count dictionary.
This is a convenience for working with raw Qiskit-style count dictionaries when you already have results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
dict
|
|
required |
n_subsystems
|
int | None
|
Override (defaults to |
None
|
n_cycles
|
int | None
|
Override (defaults to |
None
|
Source code in src/qgate/filter.py
qgate.scoring
¶
scoring.py — Score computation and fusion logic.
Extracted from the original monitors.py module to provide a clean,
stateless scoring API alongside the stateful :class:MultiRateMonitor.
Scoring is vectorised with NumPy: :func:score_batch processes all
shots in a single array operation, avoiding per-shot Python loops.
Patent pending (see LICENSE)
fuse_scores(lf_score, hf_score, alpha=0.5, threshold=0.65)
¶
α-weighted fusion of LF and HF scores.
combined = α · lf_score + (1 − α) · hf_score
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lf_score
|
float
|
Low-frequency score (0–1). |
required |
hf_score
|
float
|
High-frequency score (0–1). |
required |
alpha
|
float
|
LF weight (0 ≤ α ≤ 1). |
0.5
|
threshold
|
float
|
Accept if combined ≥ threshold. |
0.65
|
Returns:
| Type | Description |
|---|---|
tuple[bool, float]
|
(accepted, combined_score) |
Source code in src/qgate/scoring.py
score_outcome(outcome, alpha=0.5, hf_cycles=None, lf_cycles=None)
¶
Compute LF, HF, and combined scores for a single shot outcome.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome
|
ParityOutcome
|
Parity outcome. |
required |
alpha
|
float
|
LF weight in the combined score. |
0.5
|
hf_cycles
|
Sequence[int] | None
|
Explicit HF cycle indices (default: all). |
None
|
lf_cycles
|
Sequence[int] | None
|
Explicit LF cycle indices (default: even). |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
(lf_score, hf_score, combined_score) |
Source code in src/qgate/scoring.py
score_batch(outcomes, alpha=0.5, hf_cycles=None, lf_cycles=None)
¶
Score every outcome in a batch (vectorised).
When all outcomes share the same shape the scoring is performed as a single NumPy operation on a stacked 3-D array. Falls back to per-shot scoring when shapes differ.
Returns:
| Type | Description |
|---|---|
list[tuple[float, float, float]]
|
List of |
Source code in src/qgate/scoring.py
compute_window_metric(times, values, window=1.0, mode='max')
¶
Compute a metric over a trailing time window.
Examines [t_final − window, t_final] and returns the max or mean of values within that interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
ndarray
|
1-D monotonic time array. |
required |
values
|
ndarray
|
1-D values array (same length). |
required |
window
|
float
|
Width of the trailing window. |
1.0
|
mode
|
Literal['max', 'mean']
|
|
'max'
|
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
(metric, window_start, window_end) |
Source code in src/qgate/scoring.py
qgate.threshold
¶
threshold.py — Dynamic threshold gating strategies.
Provides two adaptive threshold classes:
:class:DynamicThreshold
Rolling z-score gating (legacy rolling_z mode). Operates on
batch-level mean scores.
:class:GaltonAdaptiveThreshold
Distribution-aware gating (galton mode) inspired by diffusion /
central-limit principles. Operates on per-shot combined scores
and supports empirical-quantile and robust z-score sub-modes.
Both classes share the same :class:~qgate.config.DynamicThresholdConfig
and are wired into :class:~qgate.filter.TrajectoryFilter transparently.
Patent pending (see LICENSE)
GaltonSnapshot
dataclass
¶
Telemetry snapshot emitted after every :meth:GaltonAdaptiveThreshold.update.
All fields are populated regardless of the active sub-mode; fields
that do not apply in the current mode are set to None.
Attributes:
| Name | Type | Description |
|---|---|---|
rolling_mean |
float | None
|
Mean of the rolling window. |
rolling_sigma |
float | None
|
Std-dev (or MAD-based σ) of the window. |
rolling_quantile |
float | None
|
Empirical quantile at 1 − target_acceptance. |
effective_threshold |
float
|
Threshold actually used for gating. |
window_size_current |
int
|
Number of scores in the window right now. |
acceptance_rate_rolling |
float | None
|
Fraction of window scores ≥ threshold. |
in_warmup |
bool
|
True if window < min_window_size. |
Source code in src/qgate/threshold.py
DynamicThreshold
¶
Rolling z-score threshold adjuster.
Maintains a sliding window of recent batch scores and computes an
adaptive threshold each time :meth:update is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
DynamicThresholdConfig
|
Threshold configuration parameters. |
required |
Example::
from qgate.config import DynamicThresholdConfig
cfg = DynamicThresholdConfig(enabled=True, baseline=0.65,
z_factor=1.5, window_size=10)
dt = DynamicThreshold(cfg)
dt.update(0.70)
dt.update(0.68)
print(dt.current_threshold)
Source code in src/qgate/threshold.py
current_threshold
property
¶
The most recent threshold value.
history
property
¶
Copy of the rolling score history.
update(batch_score)
¶
Record a new batch score and recompute the threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_score
|
float
|
The mean combined score of the latest batch. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The updated threshold value. |
Source code in src/qgate/threshold.py
GaltonAdaptiveThreshold
¶
Distribution-aware adaptive threshold (Galton / diffusion mode).
Maintains a per-shot rolling window of combined scores and computes a threshold that targets a stable acceptance fraction.
Two sub-modes are available (selected via config.use_quantile):
Quantile mode (default, recommended) Uses the empirical quantile of the window:
.. math:: \theta = Q_{1 - \text{target\_acceptance}}(\text{window})
This is the most robust option — it makes no distributional
assumptions and naturally tracks hardware drift.
Z-score mode (use_quantile=False)
Estimates μ and σ from the window and sets:
.. math:: \theta = \mu + z_{\sigma} \cdot \sigma
When ``robust_stats=True`` (default), the median and
MAD-derived σ are used, making the estimate resilient to
outliers. When ``robust_stats=False``, ordinary mean and
sample std are used.
Warmup: While len(window) < min_window_size the threshold
falls back to config.baseline. This avoids noisy estimates
from too few observations.
All operations are O(1) amortised — the window is backed by a
:class:collections.deque with bounded capacity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
DynamicThresholdConfig
|
:class: |
required |
Example::
from qgate.config import DynamicThresholdConfig
cfg = DynamicThresholdConfig(
mode="galton",
window_size=500,
target_acceptance=0.05,
robust_stats=True,
use_quantile=True,
)
gat = GaltonAdaptiveThreshold(cfg)
for score in batch_scores:
gat.observe(score)
print(gat.current_threshold)
Source code in src/qgate/threshold.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
current_threshold
property
¶
The most recent effective threshold value.
window
property
¶
Copy of the rolling score window.
window_size_current
property
¶
Number of scores currently in the window.
in_warmup
property
¶
True while the window is smaller than min_window_size.
last_snapshot
property
¶
The most recent telemetry snapshot.
observe(score)
¶
Add a single score to the window and recompute the threshold.
Call this once per shot (or per combined score). The threshold is evaluated before the new score is appended, so the returned threshold was computed without the new score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
float
|
A per-shot combined score. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The effective threshold after update. |
Source code in src/qgate/threshold.py
observe_batch(scores)
¶
Convenience: observe a whole batch of scores at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
list[float] | ndarray
|
Iterable of per-shot combined scores. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The effective threshold after the last observation. |
Source code in src/qgate/threshold.py
reset()
¶
Clear the window and reset to baseline.
estimate_diffusion_width(window, robust=True)
¶
Estimate the variance (diffusion width) of a score window.
This is a simple dispersion estimator that can serve as a diagnostic for diffusion-scaling validation in future work.
When robust=True (default) the MAD-based σ² is returned; otherwise
the ordinary sample variance is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
list[float] | ndarray
|
1-D array-like of scores. |
required |
robust
|
bool
|
Use MAD-derived variance estimate. |
True
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated variance (σ²). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If window has fewer than 2 elements. |
Source code in src/qgate/threshold.py
qgate.run_logging
¶
run_logging.py — Structured run logging (JSON / CSV / Parquet).
Every :class:~qgate.filter.TrajectoryFilter run can be logged to
disk for reproducibility and analysis.
Patent pending (see LICENSE)
FilterResult
dataclass
¶
Structured output of a single trajectory-filter run.
Attributes:
| Name | Type | Description |
|---|---|---|
run_id |
str
|
Deterministic 12-char hex digest for deduplication and reproducibility. |
variant |
str
|
Conditioning strategy used. |
total_shots |
int
|
Number of shots executed. |
accepted_shots |
int
|
Number of accepted shots. |
acceptance_probability |
float
|
accepted / total. |
tts |
float
|
Time-to-solution (1 / acceptance_probability). |
mean_combined_score |
float | None
|
Mean combined fusion score across shots. |
threshold_used |
float
|
Threshold at the time of filtering. |
dynamic_threshold_final |
float | None
|
Final dynamic threshold (if enabled). |
scores |
list[float]
|
Per-shot combined scores. |
config_json |
str
|
Serialised GateConfig as JSON string. |
metadata |
dict[str, Any]
|
Free-form metadata. |
timestamp |
str
|
ISO-8601 timestamp. |
Source code in src/qgate/run_logging.py
RunLogger
¶
Append-only logger that writes :class:FilterResult records.
Supports JSON-Lines, CSV, and (optionally) Parquet output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path (suffix determines format:
|
required |
fmt
|
Literal['jsonl', 'csv', 'parquet'] | None
|
Explicit format override ( |
None
|
Source code in src/qgate/run_logging.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
log(result)
¶
flush_all()
¶
Re-write the entire file from the in-memory buffer.
Useful if you want to guarantee the file is in sync.
Source code in src/qgate/run_logging.py
close()
¶
Flush remaining buffered records (especially Parquet) and release resources.
Source code in src/qgate/run_logging.py
compute_run_id(config_json, adapter_name='', circuit_hash='')
¶
Return a deterministic 12-char hex run ID (SHA-256 prefix).
The ID is computed from a canonical JSON blob combining config_json, adapter_name, and an optional circuit_hash. Two runs with identical inputs always produce the same ID, enabling deduplication and reproducibility checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_json
|
str
|
Serialised :class: |
required |
adapter_name
|
str
|
Name/class of the adapter used. |
''
|
circuit_hash
|
str
|
Optional hash of the circuit object for extra specificity. |
''
|
Returns:
| Type | Description |
|---|---|
str
|
12-character lowercase hex string. |
Source code in src/qgate/run_logging.py
Framework Adapters¶
qgate.adapters.base
¶
base.py — Adapter protocol and mock implementation.
Every adapter must implement :class:BaseAdapter so that
:class:~qgate.filter.TrajectoryFilter can work with any quantum
framework.
Patent pending (see LICENSE)
BaseAdapter
¶
Bases: ABC
Abstract base class that all qgate adapters must implement.
The adapter is responsible for
- Building circuits with Bell-pair subsystems and parity checks.
- Executing shots on a backend (simulator or hardware).
- Parsing raw results into
ParityOutcomeobjects.
Source code in src/qgate/adapters/base.py
build_circuit(n_subsystems, n_cycles, **kwargs)
abstractmethod
¶
Construct a circuit with n_subsystems Bell pairs and n_cycles mid-circuit parity checks.
Returns a framework-native circuit object.
Source code in src/qgate/adapters/base.py
run(circuit, shots, **kwargs)
abstractmethod
¶
Execute circuit for shots repetitions.
Returns the framework-native result object.
parse_results(raw_results, n_subsystems, n_cycles)
abstractmethod
¶
Parse framework-native results into a list of
ParityOutcome objects (one per shot).
build_and_run(n_subsystems, n_cycles, shots, circuit_kwargs=None, run_kwargs=None)
¶
Convenience: build → run → parse in one call.
Source code in src/qgate/adapters/base.py
MockAdapter
¶
Bases: BaseAdapter
In-memory adapter that generates synthetic parity outcomes.
Useful for unit tests and demonstrations without a real backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_rate
|
float
|
Per-subsystem per-cycle probability of a parity flip (default 0.05 → 5 %). |
0.05
|
seed
|
int | None
|
Optional random seed for reproducibility. |
None
|
Source code in src/qgate/adapters/base.py
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Return a lightweight descriptor (no real circuit).
run(circuit, shots, **kwargs)
¶
Generate shots synthetic parity matrices.
Source code in src/qgate/adapters/base.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Wrap raw matrices in ParityOutcome.
Source code in src/qgate/adapters/base.py
qgate.adapters.registry
¶
registry.py — Entry-point based adapter discovery.
Discovers adapters registered under the qgate.adapters entry-point
group and provides :func:list_adapters / :func:load_adapter for
programmatic and CLI access.
Example::
from qgate.adapters.registry import list_adapters, load_adapter
print(list_adapters()) # {"mock": "qgate.adapters.base:MockAdapter", ...}
AdapterCls = load_adapter("mock")
adapter = AdapterCls(error_rate=0.05, seed=42)
Patent pending (see LICENSE)
list_adapters()
¶
Return {name: "module:Class"} for all registered adapters.
Reads the qgate.adapters entry-point group.
load_adapter(name, **kwargs)
¶
Load and return the adapter class registered under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Adapter name as registered in entry points (e.g. |
required |
**kwargs
|
Any
|
Currently unused; reserved for future configuration. |
{}
|
Returns:
| Type | Description |
|---|---|
type
|
The adapter class (not an instance). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If name is not a registered adapter. |
ImportError
|
If the adapter's optional dependency is missing. |
Source code in src/qgate/adapters/registry.py
qgate.adapters.qiskit_adapter
¶
qiskit_adapter.py — Full Qiskit adapter for qgate.
Builds dynamic circuits with Bell-pair subsystems, scramble layers, and ancilla-based mid-circuit Z-parity measurements.
Requires the qiskit extra::
pip install qgate[qiskit]
Patent pending (see LICENSE)
QiskitAdapter
¶
Bases: BaseAdapter
Adapter for IBM Qiskit circuits.
Builds dynamic circuits with
- N Bell pairs (2N data qubits)
- W monitoring cycles each containing:
- Random single-qubit scramble rotations
- Ancilla-based Z⊗Z parity measurement per pair
- Ancilla reset & reuse
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Any
|
Qiskit backend or |
None
|
scramble_depth
|
int
|
Number of random-rotation layers per cycle. |
1
|
optimization_level
|
int
|
Transpiler optimization level (0–3). |
1
|
Source code in src/qgate/adapters/qiskit_adapter.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Build a dynamic Qiskit circuit.
Qubit layout
- data qubits : 0 .. 2N-1 (pairs: [0,1], [2,3], …)
- ancilla qubits: 2N .. 3N-1 (one per pair)
Classical registers — one per cycle, each of width N (bit i records the parity of pair i).
Source code in src/qgate/adapters/qiskit_adapter.py
run(circuit, shots, **kwargs)
¶
Execute via the configured backend (Aer if none).
Source code in src/qgate/adapters/qiskit_adapter.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Parse Qiskit Result into ParityOutcome objects.
Source code in src/qgate/adapters/qiskit_adapter.py
Algorithm TSVF Adapters¶
qgate.adapters.grover_adapter
¶
grover_adapter.py — Adapter for Grover / TSVF-Chaotic Grover experiments.
Maps Grover search circuits with an ancilla-based post-selection probe
onto qgate's :class:ParityOutcome model, enabling the full trajectory
filtering pipeline (scoring → thresholding → conditioning) to work on
search algorithms — not only Bell-pair parity monitoring.
Mapping to ParityOutcome:
- n_subsystems = number of search qubits (e.g. 3 for |101⟩).
- n_cycles = number of Grover iterations.
- parity_matrix[cycle, sub] = 0 if qubit sub was in the
correct target state at iteration cycle (via ancilla probe),
1 otherwise. This lets qgate's score_fusion, thresholding, and
hierarchical conditioning rules apply naturally.
The adapter supports two algorithm variants via algorithm_mode:
- "standard" — Oracle + diffusion per iteration.
- "tsvf" — Oracle + chaotic ansatz + weak-measurement ancilla
per iteration (post-selection trajectory filter).
Patent pending (see LICENSE)
GroverTSVFAdapter
¶
Bases: BaseAdapter
Adapter for Grover / TSVF-Chaotic Grover experiments.
This adapter builds Grover-search circuits, executes them on a Qiskit
backend, and maps the raw results onto ParityOutcome objects that
the rest of qgate can score and threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Any
|
A Qiskit backend (Aer or IBM Runtime). |
None
|
algorithm_mode
|
str
|
|
'tsvf'
|
target_state
|
str
|
Target bitstring (default |
'101'
|
seed
|
int
|
RNG seed for the chaotic ansatz. |
42
|
weak_angle_base
|
float
|
Base angle for the post-selection probe (radians). |
pi / 6
|
weak_angle_ramp
|
float
|
Per-iteration angle increase (radians). |
pi / 12
|
optimization_level
|
int
|
Transpilation optimisation level (0-3). |
1
|
Source code in src/qgate/adapters/grover_adapter.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Build the Grover circuit.
n_subsystems = number of search qubits (must match
len(target_state)).
n_cycles = number of Grover iterations.
Returns a :class:QuantumCircuit.
Source code in src/qgate/adapters/grover_adapter.py
run(circuit, shots, **kwargs)
¶
Execute the circuit and return a raw result dict.
Tries SamplerV2 first, falls back to backend.run().
Source code in src/qgate/adapters/grover_adapter.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Parse raw Qiskit results into ParityOutcome objects.
Each shot → one ParityOutcome. The parity matrix records per- iteration, per-qubit: 0 = qubit in target state, 1 = not.
For the TSVF variant the ancilla measurement at each iteration provides the "parity probe". For the standard variant we infer from the final measurement only (all cycles share the same row).
Source code in src/qgate/adapters/grover_adapter.py
get_transpiled_depth(circuit)
¶
Return the depth of the transpiled circuit.
Source code in src/qgate/adapters/grover_adapter.py
extract_target_probability(raw_results, postselect=True)
¶
Extract P(target) from raw results, optionally post-selecting.
Returns (probability, total_shots_used).
Source code in src/qgate/adapters/grover_adapter.py
qgate.adapters.qaoa_adapter
¶
qaoa_adapter.py — Adapter for QAOA / TSVF-QAOA experiments.
Maps QAOA (Quantum Approximate Optimisation Algorithm) circuits with an
ancilla-based post-selection probe onto qgate's :class:ParityOutcome
model, enabling the full trajectory filtering pipeline (scoring →
thresholding → conditioning) to work on combinatorial optimisation —
specifically the MaxCut problem on random graphs.
Mapping to ParityOutcome:
- n_subsystems = number of graph nodes (qubits).
- n_cycles = number of QAOA layers (p).
- parity_matrix[cycle, sub] = 0 if qubit sub contributes to
a satisfying cut at layer cycle (via cost-function probe),
1 otherwise. This lets qgate's score_fusion, thresholding, and
hierarchical conditioning rules apply naturally.
The adapter supports two algorithm variants via algorithm_mode:
- "standard" — Canonical QAOA (cost + mixer layers).
- "tsvf" — QAOA + chaotic entangling ansatz + weak-measurement
ancilla per layer (post-selection trajectory filter).
MaxCut problem:
Given an undirected graph G = (V, E), find a partition of vertices
into two sets that maximises the number of edges crossing the cut.
The QAOA cost operator encodes C = Σ_{(i,j)∈E} ½(1 - Z_i·Z_j).
Patent pending (see LICENSE)
QAOATSVFAdapter
¶
Bases: BaseAdapter
Adapter for QAOA / TSVF-QAOA MaxCut experiments.
This adapter builds QAOA circuits for the MaxCut problem, executes
them on a Qiskit backend, and maps the raw results onto
ParityOutcome objects that the rest of qgate can score and
threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Any
|
A Qiskit backend (Aer or IBM Runtime). |
None
|
algorithm_mode
|
str
|
|
'tsvf'
|
edges
|
list[tuple[int, int]] | None
|
Edge list for the MaxCut graph. |
None
|
n_nodes
|
int
|
Number of graph nodes (qubits). Required. |
4
|
gammas
|
list[float] | float | None
|
Cost layer angles (one per layer, or single float). |
None
|
betas
|
list[float] | float | None
|
Mixer layer angles (one per layer, or single float). |
None
|
seed
|
int
|
RNG seed for chaotic ansatz and graph generation. |
42
|
weak_angle_base
|
float
|
Base angle for the post-selection probe (radians). |
pi / 4
|
weak_angle_ramp
|
float
|
Per-layer angle increase (radians). |
pi / 8
|
optimization_level
|
int
|
Transpilation optimisation level (0-3). |
1
|
Source code in src/qgate/adapters/qaoa_adapter.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | |
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Build the QAOA circuit.
n_subsystems = number of graph nodes (must match n_nodes).
n_cycles = number of QAOA layers (p).
Returns a :class:QuantumCircuit.
Source code in src/qgate/adapters/qaoa_adapter.py
run(circuit, shots, **kwargs)
¶
Execute the circuit and return a raw result dict.
Tries SamplerV2 first, falls back to backend.run().
Source code in src/qgate/adapters/qaoa_adapter.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Parse raw Qiskit results into ParityOutcome objects.
Each shot → one ParityOutcome. The parity matrix records per- layer, per-qubit: 0 if the qubit contributes to a "good" cut partition, 1 otherwise.
For the TSVF variant the ancilla measurement at each layer provides the "cut quality probe". For the standard variant we evaluate from the final measurement against the best-known cut.
Source code in src/qgate/adapters/qaoa_adapter.py
get_transpiled_depth(circuit)
¶
Return the depth of the transpiled circuit.
Source code in src/qgate/adapters/qaoa_adapter.py
extract_cut_quality(raw_results, postselect=True)
¶
Extract the mean cut ratio and approximation ratio.
Returns (mean_cut_ratio, approx_ratio, total_shots_used).
mean_cut_ratio = mean(cut_value) / max_possible_edges.
approx_ratio = mean(cut_value) / best_known_cut.
Source code in src/qgate/adapters/qaoa_adapter.py
extract_best_bitstring(raw_results, postselect=True)
¶
Find the most-sampled bitstring and its cut value.
Returns (bitstring, cut_value, count).
Source code in src/qgate/adapters/qaoa_adapter.py
random_regular_graph(n_nodes, degree=3, seed=None)
¶
Generate a random regular-ish graph as an edge list.
Falls back to an Erdős–Rényi-like model when exact regular graph construction isn't possible (e.g. odd degree × odd nodes).
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
List of (i, j) edges with i < j. |
Source code in src/qgate/adapters/qaoa_adapter.py
maxcut_value(bitstring, edges)
¶
Compute the MaxCut value for a bitstring partition.
Source code in src/qgate/adapters/qaoa_adapter.py
best_maxcut(n_nodes, edges)
¶
Brute-force the best MaxCut solution (only for small graphs).
Source code in src/qgate/adapters/qaoa_adapter.py
qgate.adapters.vqe_adapter
¶
vqe_adapter.py — Adapter for VQE / TSVF-VQE experiments.
Maps Variational Quantum Eigensolver (VQE) circuits with an ancilla-based
post-selection probe onto qgate's :class:ParityOutcome model, enabling
the full trajectory filtering pipeline (scoring → thresholding →
conditioning) to work on ground-state-energy estimation — specifically
the Transverse-Field Ising Model (TFIM).
Problem — Transverse-Field Ising Model (TFIM): H = −J Σ_{} Z_i Z_j − h Σ_i X_i
where J is the coupling strength and h is the transverse field. For a 1D chain of n qubits with open boundary conditions: H = −J Σ_{i=0}^{n-2} Z_i Z_{i+1} − h Σ_{i=0}^{n-1} X_i
The ground-state energy can be computed classically for benchmarking.
Mapping to ParityOutcome:
- n_subsystems = number of qubits in the system.
- n_cycles = number of ansatz layers (depth).
- parity_matrix[cycle, sub] = 0 if qubit sub contributes to
a low-energy configuration at layer cycle (via energy probe),
1 otherwise. This lets qgate's score_fusion, thresholding, and
hierarchical conditioning rules apply naturally.
The adapter supports two algorithm variants via algorithm_mode:
- "standard" — Hardware-efficient ansatz (Ry+Rz + CNOT entangling).
- "tsvf" — Hardware-efficient ansatz + chaotic entangling layers
+ weak-measurement ancilla per layer (post-selection
trajectory filter).
Patent pending (see LICENSE)
VQETSVFAdapter
¶
Bases: BaseAdapter
Adapter for VQE / TSVF-VQE ground-state energy experiments.
This adapter builds VQE circuits for the Transverse-Field Ising
Model (TFIM), executes them on a Qiskit backend, and maps the raw
results onto ParityOutcome objects that the rest of qgate can
score and threshold.
The TFIM Hamiltonian
H = −J Σ Z_i Z_{i+1} − h Σ X_i
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Any
|
A Qiskit backend (Aer or IBM Runtime). |
None
|
algorithm_mode
|
str
|
|
'tsvf'
|
n_qubits
|
int
|
Number of system qubits. |
4
|
j_coupling
|
float
|
ZZ coupling strength J (default 1.0). |
1.0
|
h_field
|
float
|
Transverse field strength h (default 1.0). |
1.0
|
params
|
ndarray | None
|
Variational parameters. If None, random init. |
None
|
seed
|
int
|
RNG seed for parameter init and chaotic ansatz. |
42
|
weak_angle_base
|
float
|
Base angle for the energy probe (radians). |
pi / 4
|
weak_angle_ramp
|
float
|
Per-layer angle increase (radians). |
pi / 8
|
optimization_level
|
int
|
Transpilation optimisation level (0-3). |
1
|
Source code in src/qgate/adapters/vqe_adapter.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 | |
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Build the VQE circuit.
n_subsystems = number of qubits (must match n_qubits).
n_cycles = number of ansatz layers (depth).
Returns a :class:QuantumCircuit.
Source code in src/qgate/adapters/vqe_adapter.py
run(circuit, shots, **kwargs)
¶
Execute the circuit and return a raw result dict.
Tries SamplerV2 first, falls back to backend.run().
Source code in src/qgate/adapters/vqe_adapter.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Parse raw Qiskit results into ParityOutcome objects.
Each shot → one ParityOutcome. The parity matrix records per- layer, per-qubit: 0 if the qubit contributes to a low-energy configuration, 1 otherwise.
For the TSVF variant the ancilla measurement at each layer provides the "energy quality probe". For the standard variant we evaluate from the final measurement against the ground state.
Source code in src/qgate/adapters/vqe_adapter.py
get_transpiled_depth(circuit)
¶
Return the depth of the transpiled circuit.
Source code in src/qgate/adapters/vqe_adapter.py
extract_energy(raw_results, postselect=True)
¶
Extract the estimated ZZ energy from measurement results.
Returns (estimated_energy, total_shots_used).
For TSVF mode with postselect=True, only ancilla=1 shots are used.
Source code in src/qgate/adapters/vqe_adapter.py
extract_energy_ratio(raw_results, postselect=True)
¶
Extract energy ratio relative to exact ground state.
Returns (energy_ratio, energy_error, n_shots_used). energy_ratio = estimated / exact (closer to 1.0 is better).
Source code in src/qgate/adapters/vqe_adapter.py
extract_best_bitstring(raw_results, postselect=True)
¶
Find the most-sampled bitstring and its energy.
Returns (bitstring, energy, count).
Source code in src/qgate/adapters/vqe_adapter.py
get_exact_ground_energy()
¶
Return the exact ground-state energy for this TFIM instance.
tfim_exact_ground_energy(n_qubits, j_coupling=1.0, h_field=1.0)
¶
Compute exact ground-state energy of the 1D TFIM.
H = −J Σ_{i} Z_i Z_{i+1} − h Σ_{i} X_i
Uses sparse Hamiltonian construction + Lanczos (ARPACK) for the ground state, so it scales comfortably to 20+ qubits on a laptop.
For very small systems (≤ 12 qubits) a dense fallback is used because ARPACK can occasionally be slower for tiny matrices.
Returns:
| Type | Description |
|---|---|
float
|
The minimum eigenvalue of H. |
Source code in src/qgate/adapters/vqe_adapter.py
compute_energy_from_bitstring(bitstring, n_qubits, j_coupling=1.0, h_field=0.0)
¶
Compute the diagonal (ZZ) energy of a computational-basis state.
Since X_i terms are off-diagonal, they don't contribute to individual computational-basis expectations. The ZZ part gives: E_ZZ = −J Σ_{i} s_i · s_{i+1} where s_i = +1 if bit=0, −1 if bit=1.
This is the energy that can be estimated from measurement counts.
Returns:
| Type | Description |
|---|---|
float
|
The ZZ contribution to the energy. |
Source code in src/qgate/adapters/vqe_adapter.py
estimate_energy_from_counts(counts, n_qubits, j_coupling=1.0, h_field=0.0)
¶
Estimate the ZZ energy from measurement counts.
Returns the weighted-average diagonal energy.
Source code in src/qgate/adapters/vqe_adapter.py
energy_error(estimated, exact)
¶
energy_ratio(estimated, exact)
¶
Energy ratio: estimated / exact.
For ground-state search, a ratio closer to 1.0 is better (the estimated energy approaches the true ground-state energy). The exact ground-state energy is negative for TFIM, so ratio > 1 means we overestimate (too negative = too good), ratio < 1 means we underestimate (not negative enough).
Source code in src/qgate/adapters/vqe_adapter.py
qgate.adapters.qpe_adapter
¶
qpe_adapter.py — Adapter for QPE / TSVF-QPE experiments.
Maps Quantum Phase Estimation (QPE) circuits with an ancilla-based
post-selection probe onto qgate's :class:ParityOutcome model, enabling
the full trajectory filtering pipeline (scoring → thresholding →
conditioning) to work on eigenvalue estimation.
Problem — Quantum Phase Estimation: Given a unitary U and its eigenstate |ψ⟩ such that U|ψ⟩ = e^{2πiφ}|ψ⟩, QPE estimates the phase φ to t-bit binary precision using a register of t "precision" (counting) qubits.
Target unitary: U = Rz(2πφ), with eigenstate |1⟩ (eigenvalue e^{-iπφ}) or equivalently a diagonal unitary diag(1, e^{2πiφ}).
Mapping to ParityOutcome:
- n_subsystems = number of precision qubits (t).
- n_cycles = 1 (QPE is a single-shot algorithm per run).
- parity_matrix[0, k] = 0 if precision qubit k matches the
correct phase bit, 1 otherwise. This lets qgate's score_fusion,
thresholding, and hierarchical conditioning rules apply naturally.
The adapter supports two algorithm variants via algorithm_mode:
- "standard" — Canonical QPE (Hadamards + controlled-U^{2^k}
+ inverse QFT).
- "tsvf" — QPE + chaotic entangling ansatz + weak-measurement
ancilla (post-selection trajectory filter) that
rewards phase states close to the correct answer.
Patent pending (see LICENSE)
QPETSVFAdapter
¶
Bases: BaseAdapter
Adapter for QPE / TSVF-QPE phase estimation experiments.
This adapter builds QPE circuits for estimating the eigenphase of
a unitary operator, executes them on a Qiskit backend, and maps
the raw results onto ParityOutcome objects that the rest of
qgate can score and threshold.
Target unitary: U = diag(1, e^{2πiφ})
with eigenstate |1⟩ and eigenphase φ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Any
|
A Qiskit backend (Aer or IBM Runtime). |
None
|
algorithm_mode
|
str
|
|
'tsvf'
|
eigenphase
|
float
|
The true phase φ ∈ [0, 1) (default 1/3). |
1.0 / 3.0
|
seed
|
int
|
RNG seed for chaotic ansatz. |
42
|
weak_angle_base
|
float
|
Base angle for the phase probe (radians). |
pi / 4
|
weak_angle_ramp
|
float
|
Per-precision-qubit angle increase (radians). |
pi / 8
|
optimization_level
|
int
|
Transpilation optimisation level (0-3). |
1
|
Source code in src/qgate/adapters/qpe_adapter.py
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 | |
build_circuit(n_subsystems, n_cycles, **kwargs)
¶
Build the QPE circuit.
n_subsystems = number of precision qubits (t).
n_cycles = 1 (QPE is a single-pass algorithm). Accepted
but ignored (always 1 effective cycle).
Returns a :class:QuantumCircuit.
Source code in src/qgate/adapters/qpe_adapter.py
run(circuit, shots, **kwargs)
¶
Execute the circuit and return a raw result dict.
Tries SamplerV2 first, falls back to backend.run().
Source code in src/qgate/adapters/qpe_adapter.py
parse_results(raw_results, n_subsystems, n_cycles)
¶
Parse raw Qiskit results into ParityOutcome objects.
Each shot → one ParityOutcome. The parity matrix records per- precision-qubit: 0 if the qubit matches the correct phase bit, 1 otherwise.
For the TSVF variant the ancilla measurement provides the "phase quality probe". For the standard variant we evaluate from the final measurement against the ideal phase bits.
Source code in src/qgate/adapters/qpe_adapter.py
get_transpiled_depth(circuit)
¶
Return the depth of the transpiled circuit.
Source code in src/qgate/adapters/qpe_adapter.py
get_correct_phase_bits(n_precision)
¶
Return the ideal binary-fraction bitstring for the eigenphase.
extract_phase_metrics(raw_results, n_precision, postselect=True)
¶
Extract comprehensive phase estimation metrics.
Returns a dict with
fidelity: P(correct phase bitstring)mean_phase_error: weighted-mean circular phase errorentropy: Shannon entropy of the phase histogram (bits)measured_phase: most-probable measured phasetrue_phase: the target eigenphasetotal_shots: number of shots used (after post-selection)acceptance_rate: fraction of shots accepted (TSVF only)
Source code in src/qgate/adapters/qpe_adapter.py
extract_best_phase(raw_results, n_precision, postselect=True)
¶
Find the most-sampled phase bitstring.
Returns (bitstring, phase_value, count).
Source code in src/qgate/adapters/qpe_adapter.py
phase_to_binary_fraction(phi, n_bits)
¶
Convert a phase φ ∈ [0, 1) to its best n-bit binary fraction string.
The binary fraction 0.b₁b₂…bₜ represents φ ≈ Σ bₖ / 2ᵏ. We return the string "b₁b₂…bₜ".
Example: φ = 0.375 with n_bits=3 → "011" (0.011₂ = 3/8)
Source code in src/qgate/adapters/qpe_adapter.py
binary_fraction_to_phase(bitstring)
¶
Convert a binary fraction string to a phase value.
"011" → 0.011₂ = 3/8 = 0.375
phase_error(measured_phase, true_phase)
¶
Circular phase error in [0, 0.5].
Accounts for the wraparound: |0.9 − 0.1| should be 0.2 not 0.8.
Source code in src/qgate/adapters/qpe_adapter.py
histogram_entropy(counts)
¶
Shannon entropy of a measurement histogram (in bits).
Lower entropy → sharper distribution (more peaked). For a uniform distribution over 2^t outcomes, entropy = t bits. A perfect delta function has entropy = 0.
Source code in src/qgate/adapters/qpe_adapter.py
phase_fidelity(counts, correct_bitstring)
¶
Fraction of shots that measured the correct phase bitstring.
Source code in src/qgate/adapters/qpe_adapter.py
mean_phase_error(counts, true_phase, n_bits)
¶
Weighted mean circular phase error over all measurement outcomes.
Source code in src/qgate/adapters/qpe_adapter.py
Backward-Compatible Modules¶
qgate.conditioning
¶
conditioning.py — Backward-compatible shim.
.. deprecated:: 0.3.0
The canonical location is :mod:qgate.compat.conditioning.
This module re-exports all public symbols so that existing
from qgate.conditioning import ... statements continue to work.
Usage unchanged::
from qgate.conditioning import ParityOutcome, decide_global
ConditioningStats
dataclass
¶
Aggregated statistics after applying a conditioning rule to many shots.
Source code in src/qgate/compat/conditioning.py
tts
property
¶
Time-to-solution: 1 / acceptance_probability.
ParityOutcome
dataclass
¶
Parsed mid-circuit measurement outcomes for one shot.
Attributes:
| Name | Type | Description |
|---|---|---|
n_subsystems |
int
|
Number of subsystems (Bell pairs or logical units). |
n_cycles |
int
|
Number of monitoring cycles. |
parity_matrix |
Union[ndarray, list]
|
Shape |
Source code in src/qgate/compat/conditioning.py
apply_rule_to_batch(outcomes, variant='global', k_fraction=0.9, alpha=0.5, threshold_combined=0.65)
¶
Apply a conditioning rule to a batch of parity outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcomes
|
Sequence[ParityOutcome]
|
Sequence of ParityOutcome (one per shot). |
required |
variant
|
str
|
|
'global'
|
k_fraction
|
float
|
For hierarchical rule. |
0.9
|
alpha
|
float
|
For score fusion. |
0.5
|
threshold_combined
|
float
|
For score fusion. |
0.65
|
Returns:
| Type | Description |
|---|---|
ConditioningStats
|
ConditioningStats with acceptance statistics. |
Source code in src/qgate/compat/conditioning.py
decide_global(outcome)
¶
Global conditioning — all subsystems pass all cycles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome
|
ParityOutcome
|
Parity outcome for one shot. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the shot should be accepted. |
Example::
outcome = ParityOutcome(n_subsystems=4, n_cycles=2,
parity_matrix=[[0,0,0,0], [0,0,0,0]])
assert decide_global(outcome) is True
Source code in src/qgate/compat/conditioning.py
decide_hierarchical(outcome, k_fraction=0.9)
¶
Hierarchical k-of-N conditioning.
Accepts if at least ⌈k·N⌉ subsystems pass in every cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome
|
ParityOutcome
|
Parity outcome for one shot. |
required |
k_fraction
|
float
|
Required pass fraction (0 < k_fraction ≤ 1). |
0.9
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the shot should be accepted. |
Example::
outcome = ParityOutcome(n_subsystems=4, n_cycles=1,
parity_matrix=[[0, 0, 1, 0]])
# ceil(0.75 * 4) = 3 → 3 passed → accept
assert decide_hierarchical(outcome, k_fraction=0.75) is True
Source code in src/qgate/compat/conditioning.py
decide_score_fusion(outcome, alpha=0.5, threshold_combined=0.65, hf_cycles=None, lf_cycles=None)
¶
Score-fusion conditioning.
Computes a weighted combination of low-frequency (LF) and high-frequency (HF) subsystem pass-rates and compares to a continuous threshold:
combined = α · mean(LF pass-rates) + (1-α) · mean(HF pass-rates)
By default
- HF cycles = every cycle
- LF cycles = every 2nd cycle (0, 2, 4, …)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome
|
ParityOutcome
|
Parity outcome for one shot. |
required |
alpha
|
float
|
Weight for LF component (0 ≤ α ≤ 1). |
0.5
|
threshold_combined
|
float
|
Accept if combined ≥ this value. |
0.65
|
hf_cycles
|
Sequence[int] | None
|
Override which cycles count as HF. |
None
|
lf_cycles
|
Sequence[int] | None
|
Override which cycles count as LF. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[bool, float]
|
(accepted, combined_score) |
Example::
outcome = ParityOutcome(n_subsystems=2, n_cycles=4,
parity_matrix=[[0,0],[0,1],[0,0],[1,0]])
accepted, score = decide_score_fusion(outcome, alpha=0.5)
Source code in src/qgate/compat/conditioning.py
qgate.monitors
¶
monitors.py — Backward-compatible shim.
.. deprecated:: 0.3.0
The canonical location is :mod:qgate.compat.monitors.
This module re-exports all public symbols so that existing
from qgate.monitors import ... statements continue to work.
Usage unchanged::
from qgate.monitors import MultiRateMonitor, score_fusion
MultiRateMonitor
dataclass
¶
Stateful monitor tracking HF and LF parity scores across cycles.
Usage::
mon = MultiRateMonitor(n_subsystems=4, alpha=0.5,
threshold_combined=0.65)
mon.record_cycle(0, pass_rates=0.75) # cycle 0 → HF + LF
mon.record_cycle(1, pass_rates=0.50) # cycle 1 → HF only
mon.record_cycle(2, pass_rates=0.80) # cycle 2 → HF + LF
accepted, score = mon.fused_decision()
Attributes:
| Name | Type | Description |
|---|---|---|
n_subsystems |
int
|
Number of subsystems being monitored. |
alpha |
float
|
LF weight in fusion formula. |
threshold_combined |
float
|
Accept if fused score ≥ this. |
hf_scores |
list[float]
|
Recorded HF scores (every cycle). |
lf_scores |
list[float]
|
Recorded LF scores (even cycles only). |
Source code in src/qgate/compat/monitors.py
record_cycle(cycle_idx, pass_rate)
¶
Record the subsystem pass-rate for a cycle.
The score is always recorded as HF. If the cycle index is even, it is also recorded as LF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cycle_idx
|
int
|
Zero-based cycle index. |
required |
pass_rate
|
float
|
Fraction of subsystems that passed (0–1). |
required |
Source code in src/qgate/compat/monitors.py
fused_decision()
¶
Compute the fused decision from accumulated scores.
Returns:
| Type | Description |
|---|---|
tuple[bool, float]
|
(accepted, combined_score) |
Source code in src/qgate/compat/monitors.py
compute_window_metric(times, values, window=1.0, mode='max')
¶
Compute a metric over a trailing time window.
Examines [t_final − window, t_final] and returns the max or mean of values within that interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
ndarray
|
1-D monotonic time array. |
required |
values
|
ndarray
|
1-D values array (same length). |
required |
window
|
float
|
Width of the trailing window. |
1.0
|
mode
|
Literal['max', 'mean']
|
|
'max'
|
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
(metric, window_start, window_end) |
Source code in src/qgate/scoring.py
score_fusion(lf_score, hf_score, alpha=0.5, threshold=0.65)
¶
Compute α-weighted score fusion and compare to threshold.
combined = α · lf_score + (1 − α) · hf_score
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lf_score
|
float
|
Low-frequency monitoring score (0–1). |
required |
hf_score
|
float
|
High-frequency monitoring score (0–1). |
required |
alpha
|
float
|
Weight for the LF component (0 ≤ α ≤ 1). |
0.5
|
threshold
|
float
|
Accept if combined ≥ threshold. |
0.65
|
Returns:
| Type | Description |
|---|---|
tuple[bool, float]
|
(accepted, combined_score) |
Example::
accepted, score = score_fusion(0.8, 0.6, alpha=0.5, threshold=0.65)
# score = 0.5*0.8 + 0.5*0.6 = 0.70 → accepted = True
Source code in src/qgate/compat/monitors.py
should_abort_batch(probe_pass_rate, theta=0.65)
¶
Decide whether to abort a full batch based on a probe result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe_pass_rate
|
float
|
Fraction of probe shots that passed (0–1). |
required |
theta
|
float
|
Proceed only if probe_pass_rate ≥ θ. |
0.65
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the batch should be aborted (i.e. probe failed). |
Example::
# Probe returned 30% pass-rate → abort
assert should_abort_batch(0.30, theta=0.65) is True