query-complexity 0.1.0__tar.gz → 0.1.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {query_complexity-0.1.0/src/query_complexity.egg-info → query_complexity-0.1.2}/PKG-INFO +42 -2
- {query_complexity-0.1.0 → query_complexity-0.1.2}/README.md +41 -1
- {query_complexity-0.1.0 → query_complexity-0.1.2}/pyproject.toml +1 -1
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity/__init__.py +1 -1
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity/core.py +354 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2/src/query_complexity.egg-info}/PKG-INFO +42 -2
- {query_complexity-0.1.0 → query_complexity-0.1.2}/tests/test_smoke.py +6 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/LICENSE +0 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/setup.cfg +0 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/SOURCES.txt +0 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/dependency_links.txt +0 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/requires.txt +0 -0
- {query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: query-complexity
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Adversary-bound SDP and space-efficient transducer tools for Boolean query complexity
|
|
5
5
|
Author: Ke Li
|
|
6
6
|
License: MIT
|
|
@@ -129,7 +129,8 @@ for r, data in blocks.items():
|
|
|
129
129
|
## Main API
|
|
130
130
|
|
|
131
131
|
- `solve_adversary_sdp(...)`: full one-vector adversary SDP for arbitrary Boolean domains.
|
|
132
|
-
- `
|
|
132
|
+
- `solve_symmetric_value(...)`: value-only rescaled primal Schrijver/Terwilliger SDP for symmetric functions.
|
|
133
|
+
- `solve_symmetric_orbit_sdp(...)`: compact dual/orbit SDP for symmetric functions, used when you want witnesses/transducers.
|
|
133
134
|
- `solve_symmetric_adversary_sdp(...)`: symmetric solver plus expansion to the Boolean input basis.
|
|
134
135
|
- `build_adversary_transducer(...)`: construct the input-independent transducer unitary.
|
|
135
136
|
- `adversary_query(...)`: build the input-dependent phase oracle on the witness space.
|
|
@@ -138,3 +139,42 @@ for r, data in blocks.items():
|
|
|
138
139
|
- `qiskit_adversary_circuit(...)`: optional dense-unitary Qiskit circuit export.
|
|
139
140
|
- `analytic_or_solution(...)`: closed-form adversary solution for OR.
|
|
140
141
|
- `threshold_eta_blocks(...)`: closed-form rank-one Schrijver blocks for thresholds.
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
## Value-only SDP solvers
|
|
145
|
+
|
|
146
|
+
If you only need the adversary bound and do not want the second trace-minimization pass, use the value-only APIs.
|
|
147
|
+
|
|
148
|
+
For a general Boolean function:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
import query_complexity as qc
|
|
152
|
+
|
|
153
|
+
inputs = qc.all_binary_inputs(3)
|
|
154
|
+
outputs = [int(any(x)) for x in inputs]
|
|
155
|
+
|
|
156
|
+
res = qc.solve_adversary_value_sdp(inputs, outputs, solver="MOSEK")
|
|
157
|
+
print(res.objective_value) # phase-normalized value T
|
|
158
|
+
print(res.usual_adversary_value) # usual adversary value 2T
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
For a symmetric function using the rescaled primal Schrijver/Terwilliger SDP:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
res = qc.solve_symmetric_value(
|
|
165
|
+
10,
|
|
166
|
+
qc.THRESHOLD_layers(10, 4),
|
|
167
|
+
solver="MOSEK",
|
|
168
|
+
)
|
|
169
|
+
print(res["value"]) # usual adversary value Adv^pm(f)
|
|
170
|
+
print(res["objective_convention"]) # full symmetric primal objective
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`solve_symmetric_value` uses the primal variables from the original rescaled solver:
|
|
174
|
+
|
|
175
|
+
```text
|
|
176
|
+
alpha_k = binom(n, k) beta_k
|
|
177
|
+
eta_{a,b,t} = N_{a,b,t} gamma_{a,b,t}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
and imposes PSD through Schrijver/Terwilliger blocks. It skips witness extraction and trace minimization.
|
|
@@ -95,7 +95,8 @@ for r, data in blocks.items():
|
|
|
95
95
|
## Main API
|
|
96
96
|
|
|
97
97
|
- `solve_adversary_sdp(...)`: full one-vector adversary SDP for arbitrary Boolean domains.
|
|
98
|
-
- `
|
|
98
|
+
- `solve_symmetric_value(...)`: value-only rescaled primal Schrijver/Terwilliger SDP for symmetric functions.
|
|
99
|
+
- `solve_symmetric_orbit_sdp(...)`: compact dual/orbit SDP for symmetric functions, used when you want witnesses/transducers.
|
|
99
100
|
- `solve_symmetric_adversary_sdp(...)`: symmetric solver plus expansion to the Boolean input basis.
|
|
100
101
|
- `build_adversary_transducer(...)`: construct the input-independent transducer unitary.
|
|
101
102
|
- `adversary_query(...)`: build the input-dependent phase oracle on the witness space.
|
|
@@ -104,3 +105,42 @@ for r, data in blocks.items():
|
|
|
104
105
|
- `qiskit_adversary_circuit(...)`: optional dense-unitary Qiskit circuit export.
|
|
105
106
|
- `analytic_or_solution(...)`: closed-form adversary solution for OR.
|
|
106
107
|
- `threshold_eta_blocks(...)`: closed-form rank-one Schrijver blocks for thresholds.
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
## Value-only SDP solvers
|
|
111
|
+
|
|
112
|
+
If you only need the adversary bound and do not want the second trace-minimization pass, use the value-only APIs.
|
|
113
|
+
|
|
114
|
+
For a general Boolean function:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
import query_complexity as qc
|
|
118
|
+
|
|
119
|
+
inputs = qc.all_binary_inputs(3)
|
|
120
|
+
outputs = [int(any(x)) for x in inputs]
|
|
121
|
+
|
|
122
|
+
res = qc.solve_adversary_value_sdp(inputs, outputs, solver="MOSEK")
|
|
123
|
+
print(res.objective_value) # phase-normalized value T
|
|
124
|
+
print(res.usual_adversary_value) # usual adversary value 2T
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
For a symmetric function using the rescaled primal Schrijver/Terwilliger SDP:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
res = qc.solve_symmetric_value(
|
|
131
|
+
10,
|
|
132
|
+
qc.THRESHOLD_layers(10, 4),
|
|
133
|
+
solver="MOSEK",
|
|
134
|
+
)
|
|
135
|
+
print(res["value"]) # usual adversary value Adv^pm(f)
|
|
136
|
+
print(res["objective_convention"]) # full symmetric primal objective
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`solve_symmetric_value` uses the primal variables from the original rescaled solver:
|
|
140
|
+
|
|
141
|
+
```text
|
|
142
|
+
alpha_k = binom(n, k) beta_k
|
|
143
|
+
eta_{a,b,t} = N_{a,b,t} gamma_{a,b,t}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
and imposes PSD through Schrijver/Terwilliger blocks. It skips witness extraction and trace minimization.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "query-complexity"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.2"
|
|
8
8
|
description = "Adversary-bound SDP and space-efficient transducer tools for Boolean query complexity"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -95,6 +95,15 @@ class OrbitSolution:
|
|
|
95
95
|
input_costs_by_layer: dict[int, float]
|
|
96
96
|
|
|
97
97
|
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class SdpValueResult:
|
|
100
|
+
"""Value-only SDP result, with no trace minimization or witness extraction."""
|
|
101
|
+
|
|
102
|
+
objective_value: float # phase-normalized adversary value T
|
|
103
|
+
usual_adversary_value: float # standard adversary value 2T
|
|
104
|
+
status: str
|
|
105
|
+
|
|
106
|
+
|
|
98
107
|
@dataclass(frozen=True)
|
|
99
108
|
class AdversaryTransducer:
|
|
100
109
|
"""Input-independent adversary transducer unitary."""
|
|
@@ -361,6 +370,61 @@ def normalize_instance(
|
|
|
361
370
|
return xs, ys
|
|
362
371
|
|
|
363
372
|
|
|
373
|
+
def solve_adversary_value_sdp(
|
|
374
|
+
inputs: Sequence[Sequence[Any]],
|
|
375
|
+
outputs: Sequence[Any] | None = None,
|
|
376
|
+
f: Callable[[tuple[int, ...]], Any] | None = None,
|
|
377
|
+
*,
|
|
378
|
+
solver: str | None = None,
|
|
379
|
+
solver_kwargs: Mapping[str, Any] | None = None,
|
|
380
|
+
verbose: bool = False,
|
|
381
|
+
) -> SdpValueResult:
|
|
382
|
+
"""
|
|
383
|
+
Solve only the minimax adversary SDP value for a general Boolean function.
|
|
384
|
+
|
|
385
|
+
This runs only the first pass of :func:`solve_adversary_sdp`. It does not
|
|
386
|
+
perform trace minimization and does not factor Gram matrices, so use it when
|
|
387
|
+
you only need the adversary bound or when the trace-minimization pass is
|
|
388
|
+
numerically fragile.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
SdpValueResult where ``objective_value`` is the phase-normalized value
|
|
392
|
+
T and ``usual_adversary_value`` is ``2*T``.
|
|
393
|
+
"""
|
|
394
|
+
require_cvxpy()
|
|
395
|
+
xs, ys = normalize_instance(inputs, outputs, f)
|
|
396
|
+
m = len(xs)
|
|
397
|
+
n = len(xs[0])
|
|
398
|
+
|
|
399
|
+
X = [cp.Variable((m, m), symmetric=True, name=f"X_{i}") for i in range(n)]
|
|
400
|
+
T = cp.Variable(name="T")
|
|
401
|
+
|
|
402
|
+
constraints: list[Any] = [T >= 0]
|
|
403
|
+
constraints.extend(Xi >> 0 for Xi in X)
|
|
404
|
+
|
|
405
|
+
for x_idx in range(m):
|
|
406
|
+
cost = 0.5 * cp.sum([X[i][x_idx, x_idx] for i in range(n)])
|
|
407
|
+
constraints.append(cost <= T)
|
|
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
|
+
problem = cp.Problem(cp.Minimize(T), constraints)
|
|
417
|
+
value = float(solve_problem(problem, solver, solver_kwargs, verbose))
|
|
418
|
+
if problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
|
|
419
|
+
raise RuntimeError(f"adversary value SDP failed with status {problem.status}")
|
|
420
|
+
|
|
421
|
+
return SdpValueResult(
|
|
422
|
+
objective_value=value,
|
|
423
|
+
usual_adversary_value=2.0 * value,
|
|
424
|
+
status=str(problem.status),
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
|
|
364
428
|
def solve_adversary_sdp(
|
|
365
429
|
inputs: Sequence[Sequence[Any]],
|
|
366
430
|
outputs: Sequence[Any] | None = None,
|
|
@@ -513,6 +577,296 @@ def orbit_keys(N: int, allowed_layers: Iterable[int]) -> list[OrbitKey]:
|
|
|
513
577
|
return keys
|
|
514
578
|
|
|
515
579
|
|
|
580
|
+
def full_layer_size(n: int, k: int) -> int:
|
|
581
|
+
"""Number of Boolean inputs of length n with Hamming weight k."""
|
|
582
|
+
return binom_safe(int(n), int(k))
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def num_pairs_in_orbit(n: int, a: int, b: int, t: int) -> int:
|
|
586
|
+
"""
|
|
587
|
+
Number of ordered pairs (x,y) with |x|=a, |y|=b, and |x\cap y|=t.
|
|
588
|
+
"""
|
|
589
|
+
n = int(n)
|
|
590
|
+
a = int(a)
|
|
591
|
+
b = int(b)
|
|
592
|
+
t = int(t)
|
|
593
|
+
if not (0 <= a <= n and 0 <= b <= n):
|
|
594
|
+
return 0
|
|
595
|
+
if not (max(0, a + b - n) <= t <= min(a, b)):
|
|
596
|
+
return 0
|
|
597
|
+
return binom_safe(n, a) * binom_safe(a, t) * binom_safe(n - a, b - t)
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def gamma_objective_multiplicity(n: int, a: int, b: int, t: int) -> int:
|
|
601
|
+
"""Multiplicity of the stored symmetric gamma variable with a <= b."""
|
|
602
|
+
if a == b:
|
|
603
|
+
return num_pairs_in_orbit(n, a, b, t)
|
|
604
|
+
return num_pairs_in_orbit(n, a, b, t) + num_pairs_in_orbit(n, b, a, t)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _gamma_key(a: int, b: int, t: int) -> tuple[int, int, int]:
|
|
608
|
+
aa, bb = min(int(a), int(b)), max(int(a), int(b))
|
|
609
|
+
return (aa, bb, int(t))
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _active_primal_key(key: tuple[int, int, int, int, int], layer_values: Mapping[int, int]) -> bool:
|
|
613
|
+
"""Whether an H-orbit coefficient can appear in M_1 = diag(beta)-Gamma o Delta_1."""
|
|
614
|
+
x1, y1, a, b, t = key
|
|
615
|
+
if x1 == y1 and a == b == t:
|
|
616
|
+
return True
|
|
617
|
+
if x1 != y1 and layer_values[a] != layer_values[b]:
|
|
618
|
+
return True
|
|
619
|
+
return False
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _split_components_by_active_pattern(block: Mapping[str, Any], layer_values: Mapping[int, int]) -> list[list[int]]:
|
|
623
|
+
size = int(block["size"])
|
|
624
|
+
adj = [set([i]) for i in range(size)]
|
|
625
|
+
for row, col, key, coeff in block["terms"]:
|
|
626
|
+
if coeff != 0.0 and _active_primal_key(key, layer_values):
|
|
627
|
+
adj[row].add(col)
|
|
628
|
+
adj[col].add(row)
|
|
629
|
+
|
|
630
|
+
seen = [False] * size
|
|
631
|
+
components: list[list[int]] = []
|
|
632
|
+
for v in range(size):
|
|
633
|
+
if seen[v]:
|
|
634
|
+
continue
|
|
635
|
+
stack = [v]
|
|
636
|
+
seen[v] = True
|
|
637
|
+
comp: list[int] = []
|
|
638
|
+
while stack:
|
|
639
|
+
u = stack.pop()
|
|
640
|
+
comp.append(u)
|
|
641
|
+
for w in adj[u]:
|
|
642
|
+
if not seen[w]:
|
|
643
|
+
seen[w] = True
|
|
644
|
+
stack.append(w)
|
|
645
|
+
components.append(sorted(comp))
|
|
646
|
+
return components
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _primal_terwilliger_blocks(n: int, allowed_layers: Iterable[int]) -> list[dict[str, Any]]:
|
|
650
|
+
"""
|
|
651
|
+
Schrijver/Terwilliger blocks for the primal matrix
|
|
652
|
+
M_1 = diag(beta) - Gamma o Delta_1.
|
|
653
|
+
"""
|
|
654
|
+
allowed_set = set(int(s) for s in allowed_layers)
|
|
655
|
+
m = int(n) - 1
|
|
656
|
+
blocks: list[dict[str, Any]] = []
|
|
657
|
+
for r in range(m // 2 + 1):
|
|
658
|
+
labels = [
|
|
659
|
+
(eps, i)
|
|
660
|
+
for eps in (0, 1)
|
|
661
|
+
for i in range(r, m - r + 1)
|
|
662
|
+
if eps + i in allowed_set
|
|
663
|
+
]
|
|
664
|
+
if not labels:
|
|
665
|
+
continue
|
|
666
|
+
terms: list[tuple[int, int, tuple[int, int, int, int, int], float]] = []
|
|
667
|
+
for row, (x1, i) in enumerate(labels):
|
|
668
|
+
for col, (y1, j) in enumerate(labels):
|
|
669
|
+
for tau in valid_intersections(i, j, m):
|
|
670
|
+
coeff = terwilliger_coeff(m, i, j, r, tau)
|
|
671
|
+
if coeff == 0.0:
|
|
672
|
+
continue
|
|
673
|
+
a = x1 + i
|
|
674
|
+
b = y1 + j
|
|
675
|
+
t = x1 * y1 + tau
|
|
676
|
+
terms.append((row, col, (x1, y1, a, b, t), float(coeff)))
|
|
677
|
+
blocks.append({"r": r, "indices": labels, "size": len(labels), "terms": terms})
|
|
678
|
+
return blocks
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _coefficient_scale_for_primal_term(n: int, kind: str, data: Any) -> float:
|
|
682
|
+
"""Denominator converting rescaled primal variables back to beta/gamma."""
|
|
683
|
+
if kind == "beta":
|
|
684
|
+
return float(full_layer_size(n, int(data)))
|
|
685
|
+
if kind == "gamma":
|
|
686
|
+
mult = gamma_objective_multiplicity(n, *data)
|
|
687
|
+
if mult <= 0:
|
|
688
|
+
raise ValueError(f"zero gamma multiplicity for {data}")
|
|
689
|
+
return float(mult)
|
|
690
|
+
raise ValueError(f"unknown term kind {kind!r}")
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def _primal_block_row_scales(
|
|
694
|
+
n: int,
|
|
695
|
+
m_block: int,
|
|
696
|
+
terms: list[tuple[int, int, float, str, Any]],
|
|
697
|
+
enabled: bool,
|
|
698
|
+
) -> list[float]:
|
|
699
|
+
"""Heuristic diagonal congruence scaling DBD for numerical conditioning."""
|
|
700
|
+
if not enabled:
|
|
701
|
+
return [1.0] * m_block
|
|
702
|
+
row_mass = [0.0] * m_block
|
|
703
|
+
for row, col, coeff, kind, data in terms:
|
|
704
|
+
denom = _coefficient_scale_for_primal_term(n, kind, data)
|
|
705
|
+
c = abs(float(coeff)) / denom
|
|
706
|
+
row_mass[row] += c
|
|
707
|
+
if col != row:
|
|
708
|
+
row_mass[col] += c
|
|
709
|
+
scales = []
|
|
710
|
+
for mass in row_mass:
|
|
711
|
+
scales.append(1.0 if mass <= 0 else 1.0 / sqrt(max(mass, 1e-300)))
|
|
712
|
+
return scales
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def solve_symmetric_value(
|
|
716
|
+
n: int,
|
|
717
|
+
layer_values: Mapping[int, Any],
|
|
718
|
+
*,
|
|
719
|
+
solver: str | None = None,
|
|
720
|
+
solver_kwargs: Mapping[str, Any] | None = None,
|
|
721
|
+
verbose: bool = False,
|
|
722
|
+
split_blocks: bool = True,
|
|
723
|
+
diagonal_blocks_as_inequalities: bool = True,
|
|
724
|
+
balance_psd_blocks: bool = True,
|
|
725
|
+
) -> dict[str, Any]:
|
|
726
|
+
"""
|
|
727
|
+
Solve the rescaled primal adversary SDP for a symmetric Boolean function.
|
|
728
|
+
|
|
729
|
+
This is the Schrijver/Terwilliger block-diagonalized primal SDP. It returns
|
|
730
|
+
only the value and primal variables; it does not run trace minimization,
|
|
731
|
+
does not construct one-vector witnesses, and does not build a transducer.
|
|
732
|
+
|
|
733
|
+
Variables are rescaled exactly as in the old rescaled implementation:
|
|
734
|
+
|
|
735
|
+
alpha_k = C(n,k) beta_k
|
|
736
|
+
eta_{a,b,t} = N_{a,b,t} gamma_{a,b,t}
|
|
737
|
+
|
|
738
|
+
where N_{a,b,t} is the ordered-pair multiplicity in the full objective.
|
|
739
|
+
Therefore the objective is simply sum eta, and the returned ``value`` is
|
|
740
|
+
the usual adversary bound Adv^pm(f), not the phase-normalized half-value.
|
|
741
|
+
"""
|
|
742
|
+
require_cvxpy()
|
|
743
|
+
n = int(n)
|
|
744
|
+
if n < 0:
|
|
745
|
+
raise ValueError("n must be non-negative")
|
|
746
|
+
|
|
747
|
+
lv = normalize_layer_values(layer_values)
|
|
748
|
+
if not lv:
|
|
749
|
+
raise ValueError("layer_values must be non-empty")
|
|
750
|
+
allowed = tuple(sorted(lv.keys()))
|
|
751
|
+
if min(allowed) < 0 or max(allowed) > n:
|
|
752
|
+
raise ValueError("layer outside 0..n")
|
|
753
|
+
zero_layers = [s for s in allowed if lv[s] == 0]
|
|
754
|
+
one_layers = [s for s in allowed if lv[s] == 1]
|
|
755
|
+
if not zero_layers or not one_layers:
|
|
756
|
+
raise ValueError("function/promise must contain both outputs")
|
|
757
|
+
|
|
758
|
+
alpha = {s: cp.Variable(nonneg=True, name=f"alpha_{s}") for s in allowed}
|
|
759
|
+
|
|
760
|
+
gamma_keys: set[tuple[int, int, int]] = set()
|
|
761
|
+
for a in allowed:
|
|
762
|
+
for b in allowed:
|
|
763
|
+
if lv[a] == lv[b]:
|
|
764
|
+
continue
|
|
765
|
+
aa, bb = min(a, b), max(a, b)
|
|
766
|
+
for t in range(max(0, aa + bb - n), min(aa, bb) + 1):
|
|
767
|
+
gamma_keys.add((aa, bb, t))
|
|
768
|
+
gamma_keys_sorted = sorted(gamma_keys)
|
|
769
|
+
eta = {key: cp.Variable(name=f"eta_{key[0]}_{key[1]}_{key[2]}") for key in gamma_keys_sorted}
|
|
770
|
+
|
|
771
|
+
constraints: list[Any] = [
|
|
772
|
+
cp.sum([alpha[s] for s in zero_layers]) == 0.5,
|
|
773
|
+
cp.sum([alpha[s] for s in one_layers]) == 0.5,
|
|
774
|
+
]
|
|
775
|
+
|
|
776
|
+
raw_blocks = _primal_terwilliger_blocks(n, allowed)
|
|
777
|
+
final_block_sizes: list[int] = []
|
|
778
|
+
psd_cone_sizes: list[int] = []
|
|
779
|
+
scalar_inequality_count = 0
|
|
780
|
+
|
|
781
|
+
for block in raw_blocks:
|
|
782
|
+
components = _split_components_by_active_pattern(block, lv) if split_blocks else [list(range(int(block["size"])))]
|
|
783
|
+
for comp in components:
|
|
784
|
+
local = {old: new for new, old in enumerate(comp)}
|
|
785
|
+
active_terms: list[tuple[int, int, float, str, Any]] = []
|
|
786
|
+
|
|
787
|
+
for row, col, key, coeff in block["terms"]:
|
|
788
|
+
if row not in local or col not in local:
|
|
789
|
+
continue
|
|
790
|
+
x1, y1, a, b, t = key
|
|
791
|
+
if x1 == y1 and a == b == t:
|
|
792
|
+
active_terms.append((local[row], local[col], float(coeff), "beta", int(a)))
|
|
793
|
+
elif x1 != y1 and lv[a] != lv[b]:
|
|
794
|
+
active_terms.append((local[row], local[col], -float(coeff), "gamma", _gamma_key(a, b, t)))
|
|
795
|
+
|
|
796
|
+
if not active_terms:
|
|
797
|
+
continue
|
|
798
|
+
|
|
799
|
+
m_block = len(comp)
|
|
800
|
+
row_scales = _primal_block_row_scales(n, m_block, active_terms, balance_psd_blocks)
|
|
801
|
+
final_block_sizes.append(m_block)
|
|
802
|
+
|
|
803
|
+
if diagonal_blocks_as_inequalities and all(row == col for row, col, *_ in active_terms):
|
|
804
|
+
diag_entries = [0 for _ in range(m_block)]
|
|
805
|
+
for row, _col, coeff, kind, data in active_terms:
|
|
806
|
+
var = alpha[int(data)] if kind == "beta" else eta[data]
|
|
807
|
+
denom = _coefficient_scale_for_primal_term(n, kind, data)
|
|
808
|
+
c = float(coeff) / denom
|
|
809
|
+
c *= row_scales[row] * row_scales[row]
|
|
810
|
+
diag_entries[row] = diag_entries[row] + c * var
|
|
811
|
+
for expr in diag_entries:
|
|
812
|
+
if isinstance(expr, Number) and abs(float(expr)) == 0.0:
|
|
813
|
+
continue
|
|
814
|
+
constraints.append(expr >= 0)
|
|
815
|
+
scalar_inequality_count += 1
|
|
816
|
+
continue
|
|
817
|
+
|
|
818
|
+
entries = [[0 for _ in range(m_block)] for __ in range(m_block)]
|
|
819
|
+
for row, col, coeff, kind, data in active_terms:
|
|
820
|
+
var = alpha[int(data)] if kind == "beta" else eta[data]
|
|
821
|
+
denom = _coefficient_scale_for_primal_term(n, kind, data)
|
|
822
|
+
c = float(coeff) / denom
|
|
823
|
+
c *= row_scales[row] * row_scales[col]
|
|
824
|
+
entries[row][col] = entries[row][col] + c * var
|
|
825
|
+
|
|
826
|
+
B = scalar_bmat(entries)
|
|
827
|
+
B = 0.5 * (B + B.T)
|
|
828
|
+
if m_block == 1:
|
|
829
|
+
constraints.append(B[0, 0] >= 0)
|
|
830
|
+
scalar_inequality_count += 1
|
|
831
|
+
else:
|
|
832
|
+
constraints.append(B >> 0)
|
|
833
|
+
psd_cone_sizes.append(m_block)
|
|
834
|
+
|
|
835
|
+
objective = cp.sum([eta[key] for key in gamma_keys_sorted])
|
|
836
|
+
problem = cp.Problem(cp.Maximize(objective), constraints)
|
|
837
|
+
value = float(solve_problem(problem, solver, solver_kwargs, verbose))
|
|
838
|
+
if problem.status not in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}:
|
|
839
|
+
raise RuntimeError(f"symmetric primal value SDP failed with status {problem.status}")
|
|
840
|
+
|
|
841
|
+
alpha_values = {k: None if v.value is None else float(v.value) for k, v in alpha.items()}
|
|
842
|
+
eta_values = {key: None if v.value is None else float(v.value) for key, v in eta.items()}
|
|
843
|
+
beta_values = {k: None if alpha_values[k] is None else alpha_values[k] / float(full_layer_size(n, k)) for k in alpha}
|
|
844
|
+
gamma_values = {
|
|
845
|
+
key: None if eta_values[key] is None else eta_values[key] / float(gamma_objective_multiplicity(n, *key))
|
|
846
|
+
for key in eta
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
return {
|
|
850
|
+
"value": value,
|
|
851
|
+
"usual_adversary_value": value,
|
|
852
|
+
"objective_convention": "usual_adversary_full_symmetric_sum",
|
|
853
|
+
"status": str(problem.status),
|
|
854
|
+
"alpha": alpha_values,
|
|
855
|
+
"eta": eta_values,
|
|
856
|
+
"beta": beta_values,
|
|
857
|
+
"gamma": gamma_values,
|
|
858
|
+
"allowed_layers": allowed,
|
|
859
|
+
"block_sizes": final_block_sizes,
|
|
860
|
+
"psd_cone_sizes": psd_cone_sizes,
|
|
861
|
+
"scalar_inequality_count": scalar_inequality_count,
|
|
862
|
+
"num_blocks": len(final_block_sizes),
|
|
863
|
+
"num_psd_cones": len(psd_cone_sizes),
|
|
864
|
+
"num_alpha_variables": len(alpha),
|
|
865
|
+
"num_eta_variables": len(eta),
|
|
866
|
+
"solver_stats": problem.solver_stats,
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
|
|
516
870
|
def solve_symmetric_orbit_sdp(
|
|
517
871
|
n: int,
|
|
518
872
|
layer_values: Mapping[int, Any],
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: query-complexity
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Adversary-bound SDP and space-efficient transducer tools for Boolean query complexity
|
|
5
5
|
Author: Ke Li
|
|
6
6
|
License: MIT
|
|
@@ -129,7 +129,8 @@ for r, data in blocks.items():
|
|
|
129
129
|
## Main API
|
|
130
130
|
|
|
131
131
|
- `solve_adversary_sdp(...)`: full one-vector adversary SDP for arbitrary Boolean domains.
|
|
132
|
-
- `
|
|
132
|
+
- `solve_symmetric_value(...)`: value-only rescaled primal Schrijver/Terwilliger SDP for symmetric functions.
|
|
133
|
+
- `solve_symmetric_orbit_sdp(...)`: compact dual/orbit SDP for symmetric functions, used when you want witnesses/transducers.
|
|
133
134
|
- `solve_symmetric_adversary_sdp(...)`: symmetric solver plus expansion to the Boolean input basis.
|
|
134
135
|
- `build_adversary_transducer(...)`: construct the input-independent transducer unitary.
|
|
135
136
|
- `adversary_query(...)`: build the input-dependent phase oracle on the witness space.
|
|
@@ -138,3 +139,42 @@ for r, data in blocks.items():
|
|
|
138
139
|
- `qiskit_adversary_circuit(...)`: optional dense-unitary Qiskit circuit export.
|
|
139
140
|
- `analytic_or_solution(...)`: closed-form adversary solution for OR.
|
|
140
141
|
- `threshold_eta_blocks(...)`: closed-form rank-one Schrijver blocks for thresholds.
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
## Value-only SDP solvers
|
|
145
|
+
|
|
146
|
+
If you only need the adversary bound and do not want the second trace-minimization pass, use the value-only APIs.
|
|
147
|
+
|
|
148
|
+
For a general Boolean function:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
import query_complexity as qc
|
|
152
|
+
|
|
153
|
+
inputs = qc.all_binary_inputs(3)
|
|
154
|
+
outputs = [int(any(x)) for x in inputs]
|
|
155
|
+
|
|
156
|
+
res = qc.solve_adversary_value_sdp(inputs, outputs, solver="MOSEK")
|
|
157
|
+
print(res.objective_value) # phase-normalized value T
|
|
158
|
+
print(res.usual_adversary_value) # usual adversary value 2T
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
For a symmetric function using the rescaled primal Schrijver/Terwilliger SDP:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
res = qc.solve_symmetric_value(
|
|
165
|
+
10,
|
|
166
|
+
qc.THRESHOLD_layers(10, 4),
|
|
167
|
+
solver="MOSEK",
|
|
168
|
+
)
|
|
169
|
+
print(res["value"]) # usual adversary value Adv^pm(f)
|
|
170
|
+
print(res["objective_convention"]) # full symmetric primal objective
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`solve_symmetric_value` uses the primal variables from the original rescaled solver:
|
|
174
|
+
|
|
175
|
+
```text
|
|
176
|
+
alpha_k = binom(n, k) beta_k
|
|
177
|
+
eta_{a,b,t} = N_{a,b,t} gamma_{a,b,t}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
and imposes PSD through Schrijver/Terwilliger blocks. It skips witness extraction and trace minimization.
|
|
@@ -11,3 +11,9 @@ def test_analytic_or_transducer_builds():
|
|
|
11
11
|
def test_new_api_names():
|
|
12
12
|
assert hasattr(qc, "solve_adversary_sdp")
|
|
13
13
|
assert not hasattr(qc, "solve_phase_sdp")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_symmetric_value_api_name():
|
|
17
|
+
assert hasattr(qc, "solve_symmetric_value")
|
|
18
|
+
assert not hasattr(qc, "solve_symmetric_orbit_value_sdp")
|
|
19
|
+
assert not hasattr(qc, "solve_symmetric_adversary_value_sdp")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/requires.txt
RENAMED
|
File without changes
|
{query_complexity-0.1.0 → query_complexity-0.1.2}/src/query_complexity.egg-info/top_level.txt
RENAMED
|
File without changes
|