query-complexity 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.
@@ -0,0 +1,5 @@
1
+ """Adversary-bound SDP and transducer tools for Boolean query complexity."""
2
+
3
+ from .core import *
4
+
5
+ __version__ = "0.1.0"
@@ -0,0 +1,1126 @@
1
+ """
2
+ core.py
3
+
4
+ A compact implementation of adversary-bound SDPs and space-efficient
5
+ phase-oracle transducers for Boolean query complexity.
6
+
7
+ Kept from the old codebase:
8
+ - one-vector adversary SDP for arbitrary Boolean functions;
9
+ - Terwilliger/orbit-reduced adversary SDP for symmetric Boolean functions;
10
+ - adversary transducer extraction;
11
+ - repeated transducer simulation and optional Qiskit circuit export;
12
+ - analytic threshold helpers for the rank-one Schrijver blocks.
13
+
14
+ Removed:
15
+ - two-vector SDP;
16
+ - direct-sum/bit-flip transducer;
17
+ - primal-only and polynomial-method experiments;
18
+ - duplicate main scripts and rescaled variants.
19
+
20
+ Conventions:
21
+ - Boolean inputs are tuples in {0,1}^n.
22
+ - The phase oracle is Q_x |i> = (-1)^{x_i} |i>.
23
+ - The SDP uses X_i[x,y] = <z_{x,i}, z_{y,i}> and catalyst pieces
24
+ w_{x,i} = z_{x,i}/sqrt(2).
25
+ - The phase-normalized objective is max_x 1/2 sum_i ||z_{x,i}||^2.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from dataclasses import dataclass
31
+ from functools import lru_cache
32
+ from math import comb, factorial, sqrt
33
+ from numbers import Number
34
+ from typing import Any, Callable, Iterable, Mapping, Sequence
35
+
36
+ import numpy as np
37
+ import scipy.linalg as la
38
+
39
+ try:
40
+ import cvxpy as cp
41
+ except Exception as exc: # pragma: no cover
42
+ cp = None
43
+ _CVXPY_IMPORT_ERROR = exc
44
+ else:
45
+ _CVXPY_IMPORT_ERROR = None
46
+
47
+
48
+ Array = np.ndarray
49
+ LayerValues = dict[int, int]
50
+ OrbitKey = tuple[int, int, int, int, int] # alpha, beta, a, b, t
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Dataclasses
55
+ # ---------------------------------------------------------------------------
56
+
57
+ @dataclass(frozen=True)
58
+ class AdversarySolution:
59
+ """Explicit one-vector adversary solution in the Boolean input basis."""
60
+
61
+ inputs: list[tuple[int, ...]]
62
+ outputs: list[int]
63
+ objective_value: float # first-pass minimax value
64
+ trace_value: float # second-pass sum objective
65
+ status: str
66
+
67
+ # z[i][x_idx, :] is z_{x,i}; catalyst uses z/sqrt(2).
68
+ z: list[Array]
69
+ grams: list[Array]
70
+ input_costs: Array
71
+
72
+ public_dim: int
73
+ witness_dims: list[int]
74
+ private_dim: int
75
+
76
+ # Optional provenance when expanded from an orbit solution.
77
+ orbit_solution: OrbitSolution | None = None
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class OrbitSolution:
82
+ """Compact Terwilliger/orbit solution for symmetric Boolean functions."""
83
+
84
+ n: int
85
+ layer_values: LayerValues
86
+ allowed_layers: tuple[int, ...]
87
+ objective_value: float # first-pass minimax value
88
+ trace_value: float # second-pass weighted trace value
89
+ cap: float
90
+ status: str
91
+
92
+ orbit_values: dict[OrbitKey, float]
93
+ block_values: list[Array]
94
+ block_labels: list[list[tuple[int, int]]]
95
+ input_costs_by_layer: dict[int, float]
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class AdversaryTransducer:
100
+ """Input-independent adversary transducer unitary."""
101
+
102
+ U: Array
103
+ source_states: Array # columns |0> + Q_x|w_x>
104
+ target_states: Array # columns |f(x)> + |w_x>
105
+ inputs: list[tuple[int, ...]]
106
+ outputs: list[int]
107
+
108
+ public_dim: int
109
+ private_dim: int
110
+ witness_dims: list[int]
111
+ private_slices: dict[int, slice]
112
+
113
+ catalyst_norms: Array
114
+ gram_error: float
115
+ map_error: float
116
+ unitarity_error: float
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # Basic helpers
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def require_cvxpy() -> None:
124
+ if cp is None: # pragma: no cover
125
+ raise ImportError("cvxpy is required. Install it with `pip install cvxpy`.") from _CVXPY_IMPORT_ERROR
126
+
127
+
128
+ def normalize_bit_tuple(x: Any) -> tuple[int, ...]:
129
+ """Convert a Boolean input to a tuple in {0,1}^n."""
130
+ if isinstance(x, str):
131
+ bits = tuple(int(c) for c in x)
132
+ if not set(bits).issubset({0, 1}):
133
+ raise ValueError(f"string input {x!r} is not binary")
134
+ return bits
135
+
136
+ bits = tuple(int(v) for v in x)
137
+ vals = set(bits)
138
+ if vals.issubset({0, 1}):
139
+ return bits
140
+ if vals.issubset({-1, 1}):
141
+ return tuple(1 if v == 1 else 0 for v in bits)
142
+ raise ValueError(f"input {x!r} is not Boolean")
143
+
144
+
145
+ def normalize_output(y: Any) -> int:
146
+ return 0 if y in (-1, 0, False) else 1
147
+
148
+
149
+ def hamming_weight(x: Sequence[int]) -> int:
150
+ return int(sum(int(b) for b in x))
151
+
152
+
153
+ def all_binary_inputs(n: int) -> list[tuple[int, ...]]:
154
+ if n < 0:
155
+ raise ValueError("n must be non-negative")
156
+ return [tuple((k >> (n - 1 - j)) & 1 for j in range(n)) for k in range(2**n)]
157
+
158
+
159
+ def representative_for_weight(n: int, weight: int) -> tuple[int, ...]:
160
+ weight = int(weight)
161
+ if weight < 0 or weight > n:
162
+ raise ValueError("weight must be in 0..n")
163
+ return tuple([1] * weight + [0] * (n - weight))
164
+
165
+
166
+ @lru_cache(maxsize=None)
167
+ def binom_safe(n: int, k: int) -> int:
168
+ if k < 0 or k > n:
169
+ return 0
170
+ return comb(n, k)
171
+
172
+
173
+ def normalize_layer_values(layer_values: Mapping[int, Any]) -> LayerValues:
174
+ out: LayerValues = {}
175
+ for k, v in layer_values.items():
176
+ out[int(k)] = normalize_output(v)
177
+ return dict(sorted(out.items()))
178
+
179
+
180
+ # Common symmetric Boolean functions.
181
+ def OR_layers(n: int) -> LayerValues:
182
+ return {s: int(s > 0) for s in range(n + 1)}
183
+
184
+
185
+ def AND_layers(n: int) -> LayerValues:
186
+ return {s: int(s == n) for s in range(n + 1)}
187
+
188
+
189
+ def THRESHOLD_layers(n: int, k: int) -> LayerValues:
190
+ return {s: int(s >= int(k)) for s in range(n + 1)}
191
+
192
+
193
+ def EXACT_layers(n: int, k: int) -> LayerValues:
194
+ return {s: int(s == int(k)) for s in range(n + 1)}
195
+
196
+
197
+ def PARITY_layers(n: int) -> LayerValues:
198
+ return {s: int(s % 2) for s in range(n + 1)}
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # Numerical linear algebra
203
+ # ---------------------------------------------------------------------------
204
+
205
+ def psd_factor(M: Array, tol: float = 1e-8) -> Array:
206
+ """Return R with M approximately equal to R @ R.T."""
207
+ M = np.asarray(M, dtype=float)
208
+ M = 0.5 * (M + M.T)
209
+ vals, vecs = la.eigh(M)
210
+ max_val = float(np.max(np.abs(vals))) if vals.size else 0.0
211
+ cutoff = max(tol, tol * max(1.0, max_val))
212
+ if vals.size and float(np.min(vals)) < -100 * cutoff:
213
+ raise ValueError(f"PSD factorization failed: min eigenvalue {np.min(vals):.3e}")
214
+ keep = vals > cutoff
215
+ if not np.any(keep):
216
+ return np.zeros((M.shape[0], 0), dtype=float)
217
+ return vecs[:, keep] * np.sqrt(vals[keep])[None, :]
218
+
219
+
220
+ def complete_basis(Q: Array, tol: float = 1e-10) -> Array:
221
+ """Complete an orthonormal basis Q to a square unitary matrix."""
222
+ Q = np.asarray(Q, dtype=complex)
223
+ n, r = Q.shape
224
+ if r == n:
225
+ return Q
226
+ N = la.null_space(Q.conj().T, rcond=tol)
227
+ E = np.hstack([Q, N])
228
+ if E.shape == (n, n):
229
+ return E
230
+
231
+ # Robust fallback.
232
+ cols: list[Array] = []
233
+ for j in range(r):
234
+ v = Q[:, j].copy()
235
+ for q in cols:
236
+ v -= q * np.vdot(q, v)
237
+ nv = la.norm(v)
238
+ if nv > tol:
239
+ cols.append(v / nv)
240
+ for j in range(n):
241
+ v = np.zeros(n, dtype=complex)
242
+ v[j] = 1.0
243
+ for q in cols:
244
+ v -= q * np.vdot(q, v)
245
+ nv = la.norm(v)
246
+ if nv > tol:
247
+ cols.append(v / nv)
248
+ if len(cols) == n:
249
+ break
250
+ return np.column_stack(cols)
251
+
252
+
253
+ def unitary_from_state_pairs(
254
+ source: Array,
255
+ target: Array,
256
+ *,
257
+ gram_tol: float = 1e-7,
258
+ eig_tol: float = 1e-9,
259
+ ) -> tuple[Array, float, float, float]:
260
+ """Return a unitary U such that U @ source approximately equals target."""
261
+ source = np.asarray(source, dtype=complex)
262
+ target = np.asarray(target, dtype=complex)
263
+ if source.shape != target.shape:
264
+ raise ValueError("source and target must have the same shape")
265
+
266
+ d, _ = source.shape
267
+ Gs = source.conj().T @ source
268
+ Gt = target.conj().T @ target
269
+ gram_error = float(la.norm(Gs - Gt, ord="fro"))
270
+
271
+ G = 0.5 * (Gs + Gs.conj().T)
272
+ vals, vecs = la.eigh(G)
273
+ scale = max(1.0, float(np.max(np.abs(vals))) if vals.size else 1.0)
274
+ keep = vals > eig_tol * scale
275
+ if not np.any(keep):
276
+ U = np.eye(d, dtype=complex)
277
+ return U, gram_error, float(la.norm(U @ source - target, ord="fro")), 0.0
278
+
279
+ vals_keep = vals[keep]
280
+ V = vecs[:, keep]
281
+ Qs = source @ V @ np.diag(1.0 / np.sqrt(vals_keep))
282
+ Qt = target @ V @ np.diag(1.0 / np.sqrt(vals_keep))
283
+
284
+ Qs_qr, R = la.qr(Qs, mode="economic")
285
+ Qt = Qt @ la.inv(R)
286
+ Qs = Qs_qr
287
+
288
+ H = Qt.conj().T @ Qt
289
+ if H.size and la.norm(H - np.eye(H.shape[0]), ord="fro") > max(gram_tol, 10 * gram_error):
290
+ vals_h, vecs_h = la.eigh(0.5 * (H + H.conj().T))
291
+ vals_h = np.clip(vals_h, 1e-15, None)
292
+ Qt = Qt @ (vecs_h @ np.diag(1.0 / np.sqrt(vals_h)) @ vecs_h.conj().T)
293
+
294
+ Es = complete_basis(Qs)
295
+ Et = complete_basis(Qt)
296
+ U = Et @ Es.conj().T
297
+ map_error = float(la.norm(U @ source - target, ord="fro"))
298
+ unitarity_error = float(la.norm(U.conj().T @ U - np.eye(d), ord="fro"))
299
+ return U, gram_error, map_error, unitarity_error
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # CVXPY helpers
304
+ # ---------------------------------------------------------------------------
305
+
306
+ def default_solver():
307
+ require_cvxpy()
308
+ installed = set(cp.installed_solvers())
309
+ if "MOSEK" in installed:
310
+ return cp.MOSEK
311
+ if "CLARABEL" in installed:
312
+ return "CLARABEL"
313
+ if "SDPA" in installed:
314
+ return cp.SDPA
315
+ return cp.SCS
316
+
317
+
318
+ def solve_problem(problem: Any, solver: str | None = None, solver_kwargs: Mapping[str, Any] | None = None, verbose: bool = False):
319
+ require_cvxpy()
320
+ opts = dict(solver_kwargs or {})
321
+ chosen = solver if solver is not None else default_solver()
322
+ if chosen == cp.SCS or chosen == "SCS":
323
+ opts.setdefault("eps", 1e-6)
324
+ opts.setdefault("max_iters", 200000)
325
+ return problem.solve(solver=chosen, verbose=verbose, **opts)
326
+
327
+
328
+ def scalar_to_1x1(expr: Any):
329
+ if isinstance(expr, Number):
330
+ expr = cp.Constant(float(expr))
331
+ return cp.reshape(expr, (1, 1), order="C")
332
+
333
+
334
+ def scalar_bmat(entries: list[list[Any]]):
335
+ return cp.bmat([[scalar_to_1x1(e) for e in row] for row in entries])
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # General adversary SDP
340
+ # ---------------------------------------------------------------------------
341
+
342
+ def normalize_instance(
343
+ inputs: Sequence[Sequence[Any]],
344
+ outputs: Sequence[Any] | None = None,
345
+ f: Callable[[tuple[int, ...]], Any] | None = None,
346
+ ) -> tuple[list[tuple[int, ...]], list[int]]:
347
+ xs = [normalize_bit_tuple(x) for x in inputs]
348
+ if not xs:
349
+ raise ValueError("inputs must be non-empty")
350
+ n = len(xs[0])
351
+ if any(len(x) != n for x in xs):
352
+ raise ValueError("all inputs must have the same length")
353
+ if outputs is None:
354
+ if f is None:
355
+ raise ValueError("provide outputs or f")
356
+ ys = [normalize_output(f(x)) for x in xs]
357
+ else:
358
+ if len(outputs) != len(xs):
359
+ raise ValueError("len(outputs) must equal len(inputs)")
360
+ ys = [normalize_output(y) for y in outputs]
361
+ return xs, ys
362
+
363
+
364
+ def solve_adversary_sdp(
365
+ inputs: Sequence[Sequence[Any]],
366
+ outputs: Sequence[Any] | None = None,
367
+ f: Callable[[tuple[int, ...]], Any] | None = None,
368
+ *,
369
+ epsilon: float = 1e-6,
370
+ solver: str | None = None,
371
+ solver_kwargs: Mapping[str, Any] | None = None,
372
+ psd_tol: float = 1e-8,
373
+ verbose: bool = False,
374
+ ) -> AdversarySolution:
375
+ """
376
+ Solve the one-vector adversary SDP and factor the Gram matrices.
377
+
378
+ First pass computes the minimax value. Second pass minimizes the sum of
379
+ input costs under the cap value + epsilon to encourage lower-rank factors.
380
+ """
381
+ require_cvxpy()
382
+ xs, ys = normalize_instance(inputs, outputs, f)
383
+ m = len(xs)
384
+ n = len(xs[0])
385
+
386
+ def build_problem(mode: str, cap: float | None = None):
387
+ X = [cp.Variable((m, m), symmetric=True, name=f"X_{i}") for i in range(n)]
388
+ constraints: list[Any] = [Xi >> 0 for Xi in X]
389
+ costs = []
390
+ for x_idx in range(m):
391
+ c = 0.5 * cp.sum([X[i][x_idx, x_idx] for i in range(n)])
392
+ costs.append(c)
393
+
394
+ if mode == "max":
395
+ T = cp.Variable(name="T")
396
+ constraints.append(T >= 0)
397
+ for c in costs:
398
+ constraints.append(c <= T)
399
+ objective = cp.Minimize(T)
400
+ elif mode == "sum":
401
+ if cap is None:
402
+ raise ValueError("cap is required for second pass")
403
+ for c in costs:
404
+ constraints.append(c <= cap)
405
+ objective = cp.Minimize(cp.sum(costs))
406
+ else:
407
+ raise ValueError("mode must be 'max' or 'sum'")
408
+
409
+ for a, x in enumerate(xs):
410
+ for b, y in enumerate(xs):
411
+ terms = [X[i][a, b] for i in range(n) if x[i] != y[i]]
412
+ lhs = cp.sum(terms) if terms else 0
413
+ rhs = 1.0 if ys[a] != ys[b] else 0.0
414
+ constraints.append(lhs == rhs)
415
+
416
+ return cp.Problem(objective, constraints), X, costs
417
+
418
+ first_problem, _, _ = build_problem("max")
419
+ first_value = float(solve_problem(first_problem, solver, solver_kwargs, verbose))
420
+ if first_problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
421
+ raise RuntimeError(f"first pass failed with status {first_problem.status}")
422
+
423
+ cap = first_value + epsilon
424
+ second_problem, X_vars, costs = build_problem("sum", cap=cap)
425
+ trace_value = float(solve_problem(second_problem, solver, solver_kwargs, verbose))
426
+ if second_problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
427
+ raise RuntimeError(f"second pass failed with status {second_problem.status}")
428
+
429
+ grams: list[Array] = []
430
+ z_vecs: list[Array] = []
431
+ witness_dims: list[int] = []
432
+ for Xi in X_vars:
433
+ G = np.asarray(Xi.value, dtype=float)
434
+ G = 0.5 * (G + G.T)
435
+ R = psd_factor(G, tol=psd_tol)
436
+ grams.append(G)
437
+ z_vecs.append(R)
438
+ witness_dims.append(int(R.shape[1]))
439
+
440
+ input_costs = np.array([float(c.value) for c in costs], dtype=float)
441
+ public_dim = max(max(ys) + 1, 1)
442
+ private_dim = int(sum(witness_dims))
443
+
444
+ return AdversarySolution(
445
+ inputs=xs,
446
+ outputs=ys,
447
+ objective_value=first_value,
448
+ trace_value=trace_value,
449
+ status=str(second_problem.status),
450
+ z=z_vecs,
451
+ grams=grams,
452
+ input_costs=input_costs,
453
+ public_dim=public_dim,
454
+ witness_dims=witness_dims,
455
+ private_dim=private_dim,
456
+ orbit_solution=None,
457
+ )
458
+
459
+
460
+ # ---------------------------------------------------------------------------
461
+ # Schrijver/Terwilliger coefficients
462
+ # ---------------------------------------------------------------------------
463
+
464
+ @lru_cache(maxsize=None)
465
+ def valid_intersections(a: int, b: int, N: int) -> tuple[int, ...]:
466
+ lo = max(0, int(a) + int(b) - int(N))
467
+ hi = min(int(a), int(b))
468
+ return tuple(range(lo, hi + 1))
469
+
470
+
471
+ @lru_cache(maxsize=None)
472
+ def beta_schrijver(N: int, i: int, j: int, r: int, t: int) -> int:
473
+ total = 0
474
+ for u in range(r, N - r + 1):
475
+ c1 = binom_safe(u, t)
476
+ c2 = binom_safe(N - 2 * r, u - r)
477
+ c3 = binom_safe(N - r - u, i - u)
478
+ c4 = binom_safe(N - r - u, j - u)
479
+ if c1 and c2 and c3 and c4:
480
+ total += (-1 if ((u - t) % 2) else 1) * c1 * c2 * c3 * c4
481
+ return int(total)
482
+
483
+
484
+ @lru_cache(maxsize=None)
485
+ def terwilliger_coeff(N: int, i: int, j: int, r: int, t: int) -> float:
486
+ denom_i = binom_safe(N - 2 * r, i - r)
487
+ denom_j = binom_safe(N - 2 * r, j - r)
488
+ if denom_i == 0 or denom_j == 0:
489
+ return 0.0
490
+ beta = beta_schrijver(N, i, j, r, t)
491
+ if beta == 0:
492
+ return 0.0
493
+ return float(beta) / sqrt(float(denom_i * denom_j))
494
+
495
+
496
+ # ---------------------------------------------------------------------------
497
+ # Symmetric Terwilliger/orbit SDP
498
+ # ---------------------------------------------------------------------------
499
+
500
+ def orbit_keys(N: int, allowed_layers: Iterable[int]) -> list[OrbitKey]:
501
+ allowed = set(int(s) for s in allowed_layers)
502
+ keys: list[OrbitKey] = []
503
+ for alpha in (0, 1):
504
+ for beta in (0, 1):
505
+ for a in range(N + 1):
506
+ if alpha + a not in allowed:
507
+ continue
508
+ for b in range(N + 1):
509
+ if beta + b not in allowed:
510
+ continue
511
+ for t in valid_intersections(a, b, N):
512
+ keys.append((alpha, beta, a, b, t))
513
+ return keys
514
+
515
+
516
+ def solve_symmetric_orbit_sdp(
517
+ n: int,
518
+ layer_values: Mapping[int, Any],
519
+ *,
520
+ epsilon: float = 1e-6,
521
+ solver: str | None = None,
522
+ solver_kwargs: Mapping[str, Any] | None = None,
523
+ verbose: bool = False,
524
+ ) -> OrbitSolution:
525
+ """
526
+ Solve the orbit-reduced adversary SDP for a symmetric Boolean function.
527
+
528
+ Variables are orbit entries X_1[(alpha,A),(beta,B)]. PSD is imposed by
529
+ Schrijver/Terwilliger blocks.
530
+ """
531
+ require_cvxpy()
532
+ n = int(n)
533
+ if n <= 0:
534
+ raise ValueError("n must be positive")
535
+ N = n - 1
536
+ lv = normalize_layer_values(layer_values)
537
+ allowed = tuple(sorted(lv.keys()))
538
+ allowed_set = set(allowed)
539
+ if len({lv[s] for s in allowed}) < 2:
540
+ raise ValueError("function/promise must contain both outputs")
541
+ if min(allowed) < 0 or max(allowed) > n:
542
+ raise ValueError("layer outside 0..n")
543
+
544
+ keys = orbit_keys(N, allowed)
545
+ key_set = set(keys)
546
+
547
+ def xexpr(var_map: dict[OrbitKey, Any], key: OrbitKey):
548
+ if key not in var_map:
549
+ raise KeyError(f"invalid orbit key {key}")
550
+ return var_map[key]
551
+
552
+ def cost_expr(var_map: dict[OrbitKey, Any], alpha: int, a: int):
553
+ expr = xexpr(var_map, (alpha, alpha, a, a, a))
554
+ if a > 0:
555
+ s = alpha + a - 1
556
+ expr += a * xexpr(var_map, (1, 1, s, s, s))
557
+ if N - a > 0:
558
+ s = alpha + a
559
+ expr += (N - a) * xexpr(var_map, (0, 0, s, s, s))
560
+ return 0.5 * expr
561
+
562
+ def equality_lhs(var_map: dict[OrbitKey, Any], alpha: int, beta: int, a: int, b: int, t: int):
563
+ expr = 0
564
+ if alpha != beta:
565
+ expr += xexpr(var_map, (alpha, beta, a, b, t))
566
+ if a - t > 0:
567
+ expr += (a - t) * xexpr(var_map, (1, 0, alpha + a - 1, beta + b, alpha * beta + t))
568
+ if b - t > 0:
569
+ expr += (b - t) * xexpr(var_map, (0, 1, alpha + a, beta + b - 1, alpha * beta + t))
570
+ return expr
571
+
572
+ def build_psd_constraints(var_map: dict[OrbitKey, Any]):
573
+ constraints: list[Any] = []
574
+ for r in range(N // 2 + 1):
575
+ labels = [
576
+ (alpha, a)
577
+ for alpha in (0, 1)
578
+ for a in range(r, N - r + 1)
579
+ if alpha + a in allowed_set
580
+ ]
581
+ if not labels:
582
+ continue
583
+ entries = [[0 for _ in labels] for __ in labels]
584
+ has_term = False
585
+ for row, (alpha, a) in enumerate(labels):
586
+ for col, (beta, b) in enumerate(labels):
587
+ e = 0
588
+ for t in valid_intersections(a, b, N):
589
+ key = (alpha, beta, a, b, t)
590
+ if key not in key_set:
591
+ continue
592
+ coeff = terwilliger_coeff(N, a, b, r, t)
593
+ if coeff != 0.0:
594
+ e = e + coeff * xexpr(var_map, key)
595
+ has_term = True
596
+ entries[row][col] = e
597
+ if has_term:
598
+ B = scalar_bmat(entries)
599
+ B = 0.5 * (B + B.T)
600
+ constraints.append(B[0, 0] >= 0 if len(labels) == 1 else B >> 0)
601
+ return constraints
602
+
603
+ def solve_pass(mode: str, cap: float | None = None):
604
+ var_map = {key: cp.Variable(name=f"x_{key[0]}_{key[1]}_{key[2]}_{key[3]}_{key[4]}") for key in keys}
605
+ constraints: list[Any] = []
606
+
607
+ # Symmetry X[x,y] = X[y,x].
608
+ for key in keys:
609
+ alpha, beta, a, b, t = key
610
+ kt = (beta, alpha, b, a, t)
611
+ if kt in key_set and key <= kt:
612
+ constraints.append(xexpr(var_map, key) == xexpr(var_map, kt))
613
+
614
+ constraints.extend(build_psd_constraints(var_map))
615
+
616
+ costs: list[tuple[int, int, Any]] = []
617
+ for alpha in (0, 1):
618
+ for a in range(N + 1):
619
+ if alpha + a in allowed_set:
620
+ costs.append((alpha, a, cost_expr(var_map, alpha, a)))
621
+
622
+ if mode == "max":
623
+ T = cp.Variable(name="T")
624
+ constraints.append(T >= 0)
625
+ for _, _, c in costs:
626
+ constraints.append(c <= T)
627
+ objective = cp.Minimize(T)
628
+ elif mode == "sum":
629
+ if cap is None:
630
+ raise ValueError("cap is required")
631
+ for _, _, c in costs:
632
+ constraints.append(c <= cap)
633
+ weighted = 0
634
+ for _, a, c in costs:
635
+ weighted += binom_safe(N, a) * c
636
+ objective = cp.Minimize(weighted)
637
+ else:
638
+ raise ValueError("mode must be 'max' or 'sum'")
639
+
640
+ for alpha in (0, 1):
641
+ for beta in (0, 1):
642
+ for a in range(N + 1):
643
+ if alpha + a not in allowed_set:
644
+ continue
645
+ for b in range(N + 1):
646
+ if beta + b not in allowed_set:
647
+ continue
648
+ for t in valid_intersections(a, b, N):
649
+ rhs = 1.0 if lv[alpha + a] != lv[beta + b] else 0.0
650
+ constraints.append(equality_lhs(var_map, alpha, beta, a, b, t) == rhs)
651
+
652
+ problem = cp.Problem(objective, constraints)
653
+ value = float(solve_problem(problem, solver, solver_kwargs, verbose))
654
+ if problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
655
+ raise RuntimeError(f"orbit SDP {mode} pass failed with status {problem.status}")
656
+ values = {key: float(var.value) for key, var in var_map.items()}
657
+ return value, values, str(problem.status), costs
658
+
659
+ first_value, _, first_status, _ = solve_pass("max")
660
+ cap = first_value + epsilon
661
+ trace_value, orbit_values, second_status, _ = solve_pass("sum", cap=cap)
662
+
663
+ # Numerical block values and input costs.
664
+ block_values: list[Array] = []
665
+ block_labels: list[list[tuple[int, int]]] = []
666
+ for r in range(N // 2 + 1):
667
+ labels = [(alpha, a) for alpha in (0, 1) for a in range(r, N - r + 1) if alpha + a in allowed_set]
668
+ if not labels:
669
+ continue
670
+ B = np.zeros((len(labels), len(labels)), dtype=float)
671
+ for row, (alpha, a) in enumerate(labels):
672
+ for col, (beta, b) in enumerate(labels):
673
+ val = 0.0
674
+ for t in valid_intersections(a, b, N):
675
+ key = (alpha, beta, a, b, t)
676
+ if key in orbit_values:
677
+ val += terwilliger_coeff(N, a, b, r, t) * orbit_values[key]
678
+ B[row, col] = val
679
+ block_values.append(0.5 * (B + B.T))
680
+ block_labels.append(labels)
681
+
682
+ input_costs_by_layer: dict[int, float] = {}
683
+ for s in allowed:
684
+ # Use representative alpha=0 if possible, else alpha=1.
685
+ if s <= N:
686
+ alpha, a = 0, s
687
+ else:
688
+ alpha, a = 1, s - 1
689
+ # Direct numeric version of cost_expr.
690
+ c = orbit_values[(alpha, alpha, a, a, a)]
691
+ if a > 0:
692
+ r0 = alpha + a - 1
693
+ c += a * orbit_values[(1, 1, r0, r0, r0)]
694
+ if N - a > 0:
695
+ r0 = alpha + a
696
+ c += (N - a) * orbit_values[(0, 0, r0, r0, r0)]
697
+ input_costs_by_layer[s] = 0.5 * c
698
+
699
+ return OrbitSolution(
700
+ n=n,
701
+ layer_values=lv,
702
+ allowed_layers=allowed,
703
+ objective_value=first_value,
704
+ trace_value=trace_value,
705
+ cap=cap,
706
+ status=f"{second_status}; first_pass={first_status}",
707
+ orbit_values=orbit_values,
708
+ block_values=block_values,
709
+ block_labels=block_labels,
710
+ input_costs_by_layer=input_costs_by_layer,
711
+ )
712
+
713
+
714
+ def expand_orbit_solution(orbit: OrbitSolution, *, psd_tol: float = 1e-8) -> AdversarySolution:
715
+ """Expand a compact orbit solution into full Boolean input-basis matrices."""
716
+ n = orbit.n
717
+ allowed = set(orbit.allowed_layers)
718
+ xs = [x for x in all_binary_inputs(n) if hamming_weight(x) in allowed]
719
+ ys = [orbit.layer_values[hamming_weight(x)] for x in xs]
720
+ m = len(xs)
721
+
722
+ grams: list[Array] = []
723
+ z_vecs: list[Array] = []
724
+ witness_dims: list[int] = []
725
+
726
+ for coord in range(n):
727
+ rest = [j for j in range(n) if j != coord]
728
+ G = np.zeros((m, m), dtype=float)
729
+ for a_idx, x in enumerate(xs):
730
+ alpha = x[coord]
731
+ A = {j for j in rest if x[j] == 1}
732
+ for b_idx, y in enumerate(xs):
733
+ beta = y[coord]
734
+ B = {j for j in rest if y[j] == 1}
735
+ key = (alpha, beta, len(A), len(B), len(A & B))
736
+ G[a_idx, b_idx] = orbit.orbit_values[key]
737
+ G = 0.5 * (G + G.T)
738
+ R = psd_factor(G, tol=psd_tol)
739
+ grams.append(G)
740
+ z_vecs.append(R)
741
+ witness_dims.append(int(R.shape[1]))
742
+
743
+ input_costs = []
744
+ for x_idx in range(m):
745
+ input_costs.append(0.5 * sum(float(grams[i][x_idx, x_idx]) for i in range(n)))
746
+
747
+ public_dim = max(max(ys) + 1, 1)
748
+ return AdversarySolution(
749
+ inputs=xs,
750
+ outputs=ys,
751
+ objective_value=orbit.objective_value,
752
+ trace_value=orbit.trace_value,
753
+ status=f"expanded from orbit; {orbit.status}",
754
+ z=z_vecs,
755
+ grams=grams,
756
+ input_costs=np.array(input_costs, dtype=float),
757
+ public_dim=public_dim,
758
+ witness_dims=witness_dims,
759
+ private_dim=int(sum(witness_dims)),
760
+ orbit_solution=orbit,
761
+ )
762
+
763
+
764
+ def solve_symmetric_adversary_sdp(
765
+ n: int,
766
+ layer_values: Mapping[int, Any],
767
+ *,
768
+ epsilon: float = 1e-6,
769
+ solver: str | None = None,
770
+ solver_kwargs: Mapping[str, Any] | None = None,
771
+ psd_tol: float = 1e-8,
772
+ verbose: bool = False,
773
+ ) -> AdversarySolution:
774
+ """Convenience wrapper: solve the symmetric orbit adversary SDP and expand to full basis."""
775
+ orbit = solve_symmetric_orbit_sdp(
776
+ n,
777
+ layer_values,
778
+ epsilon=epsilon,
779
+ solver=solver,
780
+ solver_kwargs=solver_kwargs,
781
+ verbose=verbose,
782
+ )
783
+ return expand_orbit_solution(orbit, psd_tol=psd_tol)
784
+
785
+
786
+ # ---------------------------------------------------------------------------
787
+ # Adversary transducer extraction and simulation
788
+ # ---------------------------------------------------------------------------
789
+
790
+ def build_adversary_state_matrices(solution: AdversarySolution) -> tuple[Array, Array, int, dict[int, slice]]:
791
+ xs, ys = solution.inputs, solution.outputs
792
+ m = len(xs)
793
+ n = len(xs[0])
794
+ public_dim = solution.public_dim
795
+
796
+ private_slices: dict[int, slice] = {}
797
+ offset = 0
798
+ for i, dim in enumerate(solution.witness_dims):
799
+ private_slices[i] = slice(offset, offset + dim)
800
+ offset += dim
801
+ private_dim = offset
802
+ total_dim = public_dim + private_dim
803
+
804
+ source = np.zeros((total_dim, m), dtype=float)
805
+ target = np.zeros((total_dim, m), dtype=float)
806
+ for x_idx, x in enumerate(xs):
807
+ source[0, x_idx] = 1.0
808
+ target[ys[x_idx], x_idx] = 1.0
809
+ for i in range(n):
810
+ piece = solution.z[i][x_idx, :] / np.sqrt(2.0)
811
+ sl = private_slices[i]
812
+ full = slice(public_dim + sl.start, public_dim + sl.stop)
813
+ sign = -1.0 if x[i] else 1.0
814
+ source[full, x_idx] += sign * piece
815
+ target[full, x_idx] += piece
816
+ return source, target, public_dim, private_slices
817
+
818
+
819
+ def build_adversary_transducer(
820
+ solution: AdversarySolution,
821
+ *,
822
+ gram_tol: float = 1e-7,
823
+ eig_tol: float = 1e-9,
824
+ ) -> AdversaryTransducer:
825
+ source, target, public_dim, private_slices = build_adversary_state_matrices(solution)
826
+ U, gram_error, map_error, unitarity_error = unitary_from_state_pairs(
827
+ source,
828
+ target,
829
+ gram_tol=gram_tol,
830
+ eig_tol=eig_tol,
831
+ )
832
+ catalyst_norms = np.sum(np.abs(target[public_dim:, :]) ** 2, axis=0)
833
+ return AdversaryTransducer(
834
+ U=U,
835
+ source_states=source,
836
+ target_states=target,
837
+ inputs=solution.inputs,
838
+ outputs=solution.outputs,
839
+ public_dim=public_dim,
840
+ private_dim=source.shape[0] - public_dim,
841
+ witness_dims=solution.witness_dims,
842
+ private_slices=private_slices,
843
+ catalyst_norms=catalyst_norms,
844
+ gram_error=gram_error,
845
+ map_error=map_error,
846
+ unitarity_error=unitarity_error,
847
+ )
848
+
849
+
850
+ def adversary_query(transducer: AdversaryTransducer, x: Sequence[int]) -> Array:
851
+ """Return Q_x = I_H ⊕ ⊕_i (-1)^{x_i} I_{W_i}."""
852
+ x = tuple(int(b) for b in x)
853
+ h, l = transducer.public_dim, transducer.private_dim
854
+ Q = np.eye(h + l, dtype=complex)
855
+ for i, bit in enumerate(x):
856
+ if i not in transducer.private_slices:
857
+ continue
858
+ sl = transducer.private_slices[i]
859
+ full = slice(h + sl.start, h + sl.stop)
860
+ if bit == 1:
861
+ Q[full, full] *= -1.0
862
+ return Q
863
+
864
+
865
+ def adversary_step(transducer: AdversaryTransducer, x: Sequence[int]) -> Array:
866
+ """Return S_x = U Q_x."""
867
+ return transducer.U @ adversary_query(transducer, x)
868
+
869
+
870
+ def catalyst_norm_bound(transducer: AdversaryTransducer) -> float:
871
+ return float(np.max(transducer.catalyst_norms)) if transducer.catalyst_norms.size else 0.0
872
+
873
+
874
+ def choose_repetitions(W: float, epsilon: float, safety_factor: float = 4.0) -> int:
875
+ if W < -1e-12:
876
+ raise ValueError("W must be non-negative")
877
+ if epsilon <= 0:
878
+ raise ValueError("epsilon must be positive")
879
+ return max(1, int(np.ceil(safety_factor * max(0.0, W) / (epsilon**2))))
880
+
881
+
882
+ def public_spread(public_dim: int, private_dim: int, K: int) -> Array:
883
+ if K <= 0:
884
+ raise ValueError("K must be positive")
885
+ omega = np.exp(2j * np.pi / K)
886
+ F = np.array([[omega ** (a * b) for b in range(K)] for a in range(K)], dtype=complex) / np.sqrt(K)
887
+ return la.block_diag(np.kron(F, np.eye(public_dim, dtype=complex)), np.eye(private_dim, dtype=complex))
888
+
889
+
890
+ def lift_step_to_slot(S: Array, public_dim: int, private_dim: int, K: int, slot: int) -> Array:
891
+ if not 0 <= slot < K:
892
+ raise ValueError("slot out of range")
893
+ h, l = public_dim, private_dim
894
+ if S.shape != (h + l, h + l):
895
+ raise ValueError("S has incompatible shape")
896
+ N = K * h + l
897
+ out = np.eye(N, dtype=complex)
898
+ ps = slice(slot * h, (slot + 1) * h)
899
+ ls = slice(K * h, K * h + l)
900
+ out[ps, ps] = S[:h, :h]
901
+ out[ps, ls] = S[:h, h:]
902
+ out[ls, ps] = S[h:, :h]
903
+ out[ls, ls] = S[h:, h:]
904
+ return out
905
+
906
+
907
+ def repeated_algorithm_unitary(S: Array, public_dim: int, private_dim: int, K: int) -> Array:
908
+ spread = public_spread(public_dim, private_dim, K)
909
+ A = spread.copy()
910
+ for slot in range(K):
911
+ A = lift_step_to_slot(S, public_dim, private_dim, K, slot) @ A
912
+ return spread.conj().T @ A
913
+
914
+
915
+ def run_adversary_algorithm(
916
+ transducer: AdversaryTransducer,
917
+ x: Sequence[int],
918
+ K: int,
919
+ initial_public_state: Array | None = None,
920
+ ) -> dict[str, Array | float]:
921
+ h, l = transducer.public_dim, transducer.private_dim
922
+ if initial_public_state is None:
923
+ psi = np.zeros(h, dtype=complex)
924
+ psi[0] = 1.0
925
+ else:
926
+ psi = np.asarray(initial_public_state, dtype=complex)
927
+ if psi.shape != (h,):
928
+ raise ValueError("initial_public_state has incompatible shape")
929
+ Sx = adversary_step(transducer, x)
930
+ A = repeated_algorithm_unitary(Sx, h, l, K)
931
+ init = np.zeros(K * h + l, dtype=complex)
932
+ init[:h] = psi
933
+ final = A @ init
934
+ output = final[:h]
935
+ return {
936
+ "algorithm_unitary": A,
937
+ "final_state": final,
938
+ "output_slot": output,
939
+ "output_probabilities": np.abs(output) ** 2,
940
+ "garbage_norm": float(la.norm(final[h:])),
941
+ }
942
+
943
+
944
+ # ---------------------------------------------------------------------------
945
+ # Optional Qiskit export
946
+ # ---------------------------------------------------------------------------
947
+
948
+ def next_power_of_two(d: int) -> int:
949
+ if d <= 0:
950
+ raise ValueError("dimension must be positive")
951
+ return 1 << int(np.ceil(np.log2(d)))
952
+
953
+
954
+ def qiskit_adversary_circuit(transducer: AdversaryTransducer, x: Sequence[int], K: int, *, measure_all: bool = False):
955
+ """Build a dense-unitary Qiskit circuit for the repeated adversary-transducer algorithm."""
956
+ from qiskit import QuantumCircuit
957
+
958
+ h, l = transducer.public_dim, transducer.private_dim
959
+ Sx = adversary_step(transducer, x)
960
+ logical_dim = K * h + l
961
+ padded_dim = next_power_of_two(logical_dim)
962
+ num_qubits = int(np.log2(padded_dim))
963
+ qc = QuantumCircuit(num_qubits)
964
+ qubits = list(range(num_qubits))
965
+
966
+ def append_logical(M: Array, label: str):
967
+ padded = np.eye(padded_dim, dtype=complex)
968
+ padded[:logical_dim, :logical_dim] = M
969
+ qc.unitary(padded, qubits, label=label)
970
+
971
+ spread = public_spread(h, l, K)
972
+ append_logical(spread, "Spread")
973
+ for slot in range(K):
974
+ append_logical(lift_step_to_slot(Sx, h, l, K, slot), f"S[{slot}]")
975
+ append_logical(spread.conj().T, "Unspread")
976
+ if measure_all:
977
+ qc.measure_all()
978
+ metadata = {
979
+ "logical_dim": logical_dim,
980
+ "padded_dim": padded_dim,
981
+ "num_qubits": num_qubits,
982
+ "public_dim": h,
983
+ "private_dim": l,
984
+ "K": K,
985
+ }
986
+ return qc, metadata
987
+
988
+
989
+ def decode_statevector(statevector: Any, *, public_dim: int, logical_dim: int) -> dict[str, Array | float]:
990
+ data = np.asarray(statevector.data, dtype=complex)
991
+ probs = np.abs(data) ** 2
992
+ return {
993
+ "output_probabilities": probs[:public_dim],
994
+ "garbage_probability": float(np.sum(probs[public_dim:logical_dim])),
995
+ "padding_probability": float(np.sum(probs[logical_dim:])),
996
+ "total_probability": float(np.sum(probs)),
997
+ }
998
+
999
+
1000
+ # ---------------------------------------------------------------------------
1001
+ # Diagnostics and analytic threshold helpers
1002
+ # ---------------------------------------------------------------------------
1003
+
1004
+ def show_catalysts(solution: AdversarySolution, *, decimals: int = 8) -> None:
1005
+ """Print w_{x,i}=z_{x,i}/sqrt(2) and ||w_x||^2 for each input."""
1006
+ for x_idx, x in enumerate(solution.inputs):
1007
+ parts = []
1008
+ norm_sq = 0.0
1009
+ print(f"x={x}, f(x)={solution.outputs[x_idx]}")
1010
+ for i, Z in enumerate(solution.z):
1011
+ w = Z[x_idx, :] / np.sqrt(2.0)
1012
+ parts.append(w)
1013
+ norm_sq += float(np.vdot(w, w).real)
1014
+ print(f" i={i}: {np.array2string(w, precision=decimals, suppress_small=True)}")
1015
+ full = np.concatenate(parts) if parts else np.array([])
1016
+ print(f" ||w_x||^2 = {norm_sq:.{decimals}g}")
1017
+ print(f" full = {np.array2string(full, precision=decimals, suppress_small=True)}\n")
1018
+
1019
+
1020
+ def show_block_factors(orbit: OrbitSolution, *, tol: float = 1e-8, decimals: int = 8) -> dict[int, dict[str, Any]]:
1021
+ """Print numerical rank-one factors of Schrijver blocks."""
1022
+ report: dict[int, dict[str, Any]] = {}
1023
+ for r, B in enumerate(orbit.block_values):
1024
+ B = 0.5 * (np.asarray(B, dtype=float) + np.asarray(B, dtype=float).T)
1025
+ vals, vecs = la.eigh(B)
1026
+ scale = max(1.0, float(np.max(np.abs(vals))) if vals.size else 1.0)
1027
+ keep = vals > tol * scale
1028
+ factors = []
1029
+ for lam, q in zip(vals[keep], vecs[:, keep].T):
1030
+ eta = np.sqrt(max(float(lam), 0.0)) * q
1031
+ if eta.size:
1032
+ pivot = int(np.argmax(np.abs(eta)))
1033
+ if eta[pivot] < 0:
1034
+ eta = -eta
1035
+ factors.append(eta)
1036
+ labels = orbit.block_labels[r]
1037
+ print(f"r={r}, shape={B.shape}, rank={len(factors)}, labels={labels}")
1038
+ for j, eta in enumerate(factors):
1039
+ print(f" eta[{j}]:")
1040
+ for lab, val in zip(labels, eta):
1041
+ print(f" {lab}: {val:.{decimals}g}")
1042
+ report[r] = {"rank": len(factors), "eigenvalues": vals, "labels": labels, "factors": factors}
1043
+ return report
1044
+
1045
+
1046
+ def threshold_adversary_value(n: int, k: int) -> float:
1047
+ """Usual adversary value for THRESHOLD^k_n."""
1048
+ return sqrt(k * (n - k + 1))
1049
+
1050
+
1051
+ def threshold_gamma(n: int, k: int) -> float:
1052
+ """Fourth-root scale used in the analytic threshold eta formulas."""
1053
+ return (k * (n - k + 1)) ** 0.25
1054
+
1055
+
1056
+ def threshold_P_entry(n: int, k: int, r: int, a: int, b: int) -> float:
1057
+ """Closed form for P_r(a,b) in the threshold cross-kernel expansion."""
1058
+ N = n - 1
1059
+ if not (0 <= r <= N // 2 and r <= a <= N - r and r <= b <= N - r):
1060
+ return 0.0
1061
+ numerator = factorial(r) * factorial(N - 2 * r) * binom_safe(N - r + 1, a - r)
1062
+ denominator = (
1063
+ factorial(b + 1)
1064
+ * factorial(N - r - b)
1065
+ * sqrt(binom_safe(N - 2 * r, a - r) * binom_safe(N - 2 * r, b - r))
1066
+ )
1067
+ return numerator / denominator
1068
+
1069
+
1070
+ def threshold_eta_blocks(n: int, k: int) -> dict[int, dict[str, Any]]:
1071
+ """Analytic rank-one Schrijver block factors for THRESHOLD^k_n."""
1072
+ N = n - 1
1073
+ d = min(k - 1, n - k)
1074
+ Gamma = threshold_gamma(n, k)
1075
+ out: dict[int, dict[str, Any]] = {}
1076
+ for r in range(d + 1):
1077
+ labels = [(alpha, a) for alpha in (0, 1) for a in range(r, N - r + 1)]
1078
+ C = threshold_P_entry(n, k, r, k - 1, k - 1)
1079
+ eta = []
1080
+ for alpha, a in labels:
1081
+ if alpha == 0 and a <= k - 1:
1082
+ val = sqrt(k / C) / Gamma * threshold_P_entry(n, k, r, a, k - 1)
1083
+ elif alpha == 1 and a >= k - 1:
1084
+ val = Gamma / sqrt(k * C) * threshold_P_entry(n, k, r, k - 1, a)
1085
+ else:
1086
+ val = 0.0
1087
+ eta.append(val)
1088
+ eta_arr = np.array(eta, dtype=float)
1089
+ out[r] = {"labels": labels, "eta": eta_arr, "B": np.outer(eta_arr, eta_arr)}
1090
+ return out
1091
+
1092
+
1093
+ def analytic_or_solution(n: int) -> AdversarySolution:
1094
+ """Closed-form rank-one adversary solution for OR_n, useful for tests/examples."""
1095
+ n = int(n)
1096
+ xs = all_binary_inputs(n)
1097
+ ys = [int(any(x)) for x in xs]
1098
+ gamma = n ** 0.25
1099
+ m = len(xs)
1100
+ z_vecs: list[Array] = []
1101
+ grams: list[Array] = []
1102
+ for i in range(n):
1103
+ z = np.zeros((m, 1), dtype=float)
1104
+ for idx, x in enumerate(xs):
1105
+ s = hamming_weight(x)
1106
+ if s == 0:
1107
+ z[idx, 0] = 1.0 / gamma
1108
+ elif x[i] == 1:
1109
+ z[idx, 0] = gamma / s
1110
+ z_vecs.append(z)
1111
+ grams.append(z @ z.T)
1112
+ costs = np.array([0.5 * sum(G[idx, idx] for G in grams) for idx in range(m)], dtype=float)
1113
+ return AdversarySolution(
1114
+ inputs=xs,
1115
+ outputs=ys,
1116
+ objective_value=float(np.max(costs)),
1117
+ trace_value=float(np.sum(costs)),
1118
+ status="analytic_or_solution",
1119
+ z=z_vecs,
1120
+ grams=grams,
1121
+ input_costs=costs,
1122
+ public_dim=2,
1123
+ witness_dims=[1] * n,
1124
+ private_dim=n,
1125
+ orbit_solution=None,
1126
+ )
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: query-complexity
3
+ Version: 0.1.0
4
+ Summary: Adversary-bound SDP and space-efficient transducer tools for Boolean query complexity
5
+ Author: Ke Li
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/your-org/query-complexity
8
+ Project-URL: Repository, https://github.com/your-org/query-complexity
9
+ Project-URL: Issues, https://github.com/your-org/query-complexity/issues
10
+ Keywords: quantum,query complexity,adversary bound,sdp,semidefinite programming
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.23
23
+ Requires-Dist: scipy>=1.9
24
+ Requires-Dist: cvxpy>=1.3
25
+ Provides-Extra: mosek
26
+ Requires-Dist: mosek; extra == "mosek"
27
+ Provides-Extra: qiskit
28
+ Requires-Dist: qiskit; extra == "qiskit"
29
+ Provides-Extra: dev
30
+ Requires-Dist: build; extra == "dev"
31
+ Requires-Dist: pytest; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # query-complexity
36
+
37
+ `query-complexity` is a small Python package for computing adversary-bound SDPs and building the associated space-efficient phase-oracle transducers for Boolean query complexity.
38
+
39
+ The package intentionally keeps the compact one-vector transducer construction and removes the older direct-sum bit-flip implementation.
40
+
41
+ ## Install
42
+
43
+ From the repository root:
44
+
45
+ ```bash
46
+ pip install -e .
47
+ ```
48
+
49
+ For development tools:
50
+
51
+ ```bash
52
+ pip install -e .[dev]
53
+ ```
54
+
55
+ For MOSEK or Qiskit support:
56
+
57
+ ```bash
58
+ pip install -e .[mosek,qiskit]
59
+ ```
60
+
61
+ ## General Boolean functions
62
+
63
+ Use `solve_adversary_sdp` for arbitrary, non-symmetric Boolean functions.
64
+
65
+ ```python
66
+ import query_complexity as qc
67
+
68
+ inputs = qc.all_binary_inputs(3)
69
+ outputs = [int(x[0] and x[1] and x[2]) for x in inputs]
70
+
71
+ sol = qc.solve_adversary_sdp(
72
+ inputs,
73
+ outputs,
74
+ solver="MOSEK",
75
+ epsilon=1e-5,
76
+ )
77
+
78
+ td = qc.build_adversary_transducer(sol)
79
+
80
+ print("adversary objective:", sol.objective_value)
81
+ print("private dimension:", td.private_dim)
82
+ print("map error:", td.map_error)
83
+ ```
84
+
85
+ ## Symmetric Boolean functions
86
+
87
+ For functions that depend only on Hamming weight, use the Terwilliger/orbit-reduced solver and expand it to the full Boolean basis:
88
+
89
+ ```python
90
+ import query_complexity as qc
91
+
92
+ n = 4
93
+ k = 2
94
+
95
+ sol = qc.solve_symmetric_adversary_sdp(
96
+ n,
97
+ qc.THRESHOLD_layers(n, k),
98
+ solver="MOSEK",
99
+ epsilon=1e-5,
100
+ )
101
+
102
+ td = qc.build_adversary_transducer(sol)
103
+
104
+ print("adversary objective:", sol.objective_value)
105
+ print("witness dimensions:", sol.witness_dims)
106
+ print("private dimension:", td.private_dim)
107
+ ```
108
+
109
+ If you only want the compact orbit-level SDP solution, use:
110
+
111
+ ```python
112
+ orbit = qc.solve_symmetric_orbit_sdp(n, qc.THRESHOLD_layers(n, k))
113
+ ```
114
+
115
+ ## Analytic helpers
116
+
117
+ ```python
118
+ import query_complexity as qc
119
+
120
+ sol = qc.analytic_or_solution(2)
121
+ td = qc.build_adversary_transducer(sol)
122
+ qc.show_catalysts(sol)
123
+
124
+ blocks = qc.threshold_eta_blocks(4, 2)
125
+ for r, data in blocks.items():
126
+ print(r, data["labels"], data["eta"])
127
+ ```
128
+
129
+ ## Main API
130
+
131
+ - `solve_adversary_sdp(...)`: full one-vector adversary SDP for arbitrary Boolean domains.
132
+ - `solve_symmetric_orbit_sdp(...)`: compact Terwilliger/orbit-reduced SDP for symmetric functions.
133
+ - `solve_symmetric_adversary_sdp(...)`: symmetric solver plus expansion to the Boolean input basis.
134
+ - `build_adversary_transducer(...)`: construct the input-independent transducer unitary.
135
+ - `adversary_query(...)`: build the input-dependent phase oracle on the witness space.
136
+ - `adversary_step(...)`: return the single-query transducer step.
137
+ - `run_adversary_algorithm(...)`: simulate the repeated transducer algorithm.
138
+ - `qiskit_adversary_circuit(...)`: optional dense-unitary Qiskit circuit export.
139
+ - `analytic_or_solution(...)`: closed-form adversary solution for OR.
140
+ - `threshold_eta_blocks(...)`: closed-form rank-one Schrijver blocks for thresholds.
@@ -0,0 +1,7 @@
1
+ query_complexity/__init__.py,sha256=UcC3IcdLywfZTVtG3Ug34kBQEDvbidkRQPH2uOVNLew,121
2
+ query_complexity/core.py,sha256=IwUgIG3g_pKmoot_d33wQEbj6fI9ipy6qfKbpEJvWXY,39183
3
+ query_complexity-0.1.0.dist-info/licenses/LICENSE,sha256=JE4HaMS4bdKoCEiW68TMyO7ORvLitVQLyfmqbYYaMek,1062
4
+ query_complexity-0.1.0.dist-info/METADATA,sha256=WTg46GV8z8QBQErxauJKCCvFnIgXmZpDGZQh4IdIG2I,4174
5
+ query_complexity-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ query_complexity-0.1.0.dist-info/top_level.txt,sha256=pl4lL_fCY8jSyRpdlMiiZ3D5-T8Ljp4s0YmoT6RtEc0,17
7
+ query_complexity-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ke Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ query_complexity