mr.piron.Back to the research desk
QUANTUM FRONTIERS

Constrained Portfolio Optimization: QUBO Penalties, QAOA Feasibility and Classical Benchmarks

An illustrative five-asset example of QUBO penalty scaling, XY mixers and finite-depth accessibility for cardinality-constrained portfolio selection, with a short Python program that prints its results.

TECHNICAL RESEARCHResearch10 primary sources3,317 words
MR. PIRON / RESEARCH DESK16 min read
01020304050607080912345678910ARTICLE, IN READING ORDER →↑ NUMBERED SOURCES01020304050607080912345678910ARTICLE, IN READING ORDER →↑ NUMBERED SOURCES01020304050607080912345678910ARTICLE, IN READING ORDER →↑ SOURCES
FIG. 0 EVIDENCE MAP · 9 SECTIONS · 10/10 SOURCES CITED · 10 CITATIONS · 4 EQUATIONS · 1 CODE LISTINGComputed from this article. Each bar is a section, as long as its share of the words. A curve joins a passage to a source it cites; a circle grows with the number of passages that cite it. Diamonds mark equations and squares mark code.
Sources cited, equations and code listings per section
SectionSources citedEquationsCode listings
1. Map the cardinality-constrained Markowitz problem to a QUBO Hamiltonian with explicit penalty scaling1010
2. Select constraint-preserving XY mixers to eliminate soft penalty distortions prior to variational execution5, 900
3. Derive approximate counterdiabatic corrections from commutators of portfolio and mixer operators400
4. Schedule multi-ramp penalties as internal QAOA parameters for joint feasibility optimization300
5. Benchmark finite-depth reachable quality against an exact classical reference110
6. Validate the weight conservation behind post-selection feasibility using the deterministic synthetic program200
7. Document structural assumptions failure modes and risk controls for penalty-based encodings700
8. Project regime probabilities onto asset weights via linear mappings610
9. Reproduce all conservation invariants with the self-verifying Python fixture811

01 /Map the cardinality-constrained Markowitz problem to a QUBO Hamiltonian with explicit penalty scaling

The decision clock is fixed prior to mapping by discretizing the investment horizon into exactly 252 trading periods per year. Each period tt indexes a binary selection vector xt∈{0,1}Nx_t \in \{0,1\}^N where NN denotes the number of candidate assets and the exactly KK entries equal to one enforce cardinality. The expected return vector μ\mu lies in RN\mathbb{R}^N with units of return per period while the covariance matrix Σ\Sigma resides in RN×N\mathbb{R}^{N \times N} carrying units of squared return per period. A risk-aversion scalar qq with units of inverse return per period multiplies the risk term. With it, every term of the objective is a return per period, and the penalty coefficient introduced next carries the same unit.

The QUBO Hamiltonian is assembled as the sum of three terms. The return term is linear in xx, and the risk term is the quadratic form xTΣxx^T \Sigma x multiplied by qq. The cardinality constraint is encoded by the squared penalty P(1Tx−K)2P (\mathbf{1}^T x - K)^2, where PP is a scalar coefficient. On binary vectors xi2=xix_i^2 = x_i, so the linear terms sit on the diagonal of the QUBO matrix and the expression is a quadratic form plus the constant PK2P K^2. Every term carries units of return per period.

A sufficient penalty follows from the range of the unpenalized objective f(x)=q xTΣx−μTxf(x) = q\,x^T \Sigma x - \mu^T x over the Boolean hypercube. An infeasible state misses the cardinality by at least one, so any PP larger than fmax⁡−fmin⁡f_{\max} - f_{\min} places every infeasible state above every feasible state. The bound is sufficient, not minimal. The penalized and the constrained problem share their minimizers once PP exceeds PcritP_{\text{crit}}, the largest value of (fopt−f(x))/(1Tx−K)2(f_{\text{opt}} - f(x)) / (\mathbf{1}^T x - K)^2 over infeasible xx, where foptf_{\text{opt}} is the feasible optimum. Inside the feasible subspace the penalty is zero, so it leaves the mean-variance trade-off unchanged.

Reference [10] documents benchmarking of QAOA variants on portfolio optimization instances formulated as cardinality-constrained quadratic binary problems and tests the influence of statistical sampling errors together with gate and readout noise. Its analysis of easy versus hard instances applies to its suite of synthetic and DAX30-derived covariances; the penalty scaling above uses the same QUBO structure and sets the coefficient by the range bound.

Penalized selection objectiveEQ. 1.1
H(x)=−μTx+q xTΣx+P(1Tx−K)2H(x) = -\mu^T x + q\, x^T \Sigma x + P (\mathbf{1}^T x - K)^2

x∈{0,1}Nx \in \{0,1\}^N is the selection vector, μ\mu the expected returns (return per period), Σ\Sigma the covariance matrix (squared return per period), qq the risk aversion (inverse return per period), PP the penalty coefficient (return per period) and KK the target cardinality. The first two terms are the unpenalized objective f(x)f(x). Every term is a return per period.

02 /Select constraint-preserving XY mixers to eliminate soft penalty distortions prior to variational execution

Constraint-preserving mixers are constructed from the XY Hamiltonian restricted to the subspace of fixed Hamming weight KK. The mixer operator is assembled as the sum over all pairs of qubits ii and jj of Pauli XiXj+YiYjX_i X_j + Y_i Y_j terms scaled by coefficients that respect the feasible subspace. The mixer commutes with the Hamming-weight operator and maps every weight sector to itself. A state prepared at weight KK therefore remains feasible at every layer depth. This removes the need for a large external penalty coefficient, which would otherwise dominate the energy scale of the cost Hamiltonian.

The initial state is chosen as the uniform superposition over all weight-KK binary strings. With equal positive pair coefficients it is the highest-energy eigenstate of the XY mixer in the fixed-weight subspace, and the ground state once the sign of the mixer is reversed. This Dicke state can be prepared by a sequence of Givens rotations or by adiabatic evolution within the fixed-excitation subspace. The resulting QAOA ansatz therefore never measures infeasible bitstrings eliminating the need for post-selection on cardinality. All subsequent parameter optimization occurs exclusively inside the feasible manifold preserving the original objective landscape without penalty-induced conditioning issues.

Reference [5] documents a QAOA formulation utilizing Dicke-state initialization together with an XY-mixer Hamiltonian that strictly preserves Hamming weight for cardinality-constrained portfolio optimization and introduces a Trotterized parameter initialization schedule inspired by adiabatic evolution. Its reported workflow applies to its illustrative direct-indexing example; the mixer construction adopted here follows the identical Hamming-weight preservation algebra without reference to any backtest metrics.

Reference [9] documents expression of a cardinality-constrained three-objective portfolio problem as a set of weighted Hamiltonians solved by a single QAOA circuit whose angles trace a Pareto front and employs an XY mixer to enforce the exactly-K constraint exactly so that post-selection alone guarantees feasibility. Its workflow on the eight-asset and forty-asset synthetic universes applies to its simulator and hardware runs; the present mixer schedule extends the same XY algebra while embedding additional counterdiabatic terms.

03 /Derive approximate counterdiabatic corrections from commutators of portfolio and mixer operators

Counterdiabatic driving augments the standard QAOA by adding gauge-potential terms obtained from nested commutators of the cost Hamiltonian and the XY mixer. The leading-order adiabatic gauge potential is proportional to the commutator of the portfolio Hamiltonian with the mixer Hamiltonian projected back onto the feasible subspace. Higher-order terms are generated recursively by further nested commutators truncated at a fixed operator length to remain hardware-compatible. Each term is accompanied by a variational coefficient that is optimized jointly with the standard QAOA angles.

Because the XY mixer commutes with the total excitation operator all counterdiabatic corrections automatically preserve the cardinality manifold. The resulting variational ansatz therefore remains strictly feasible at every depth. The added terms are meant to suppress diabatic transitions that would otherwise move probability mass toward lower-quality feasible states. For a cost Hamiltonian with one-body and two-body ZZ terms, the first-order term [HC,HM][H_C, H_M] is a sum of two-body and three-body Pauli strings whose coefficients are linear in the expected returns and covariances. The penalty depends only on the total weight, commutes with the mixer and contributes nothing.

No commutator is expanded numerically and no spectral gap is computed here. The operator content stated above follows from the Pauli algebra. A ZZ or ZZZZ term fails to commute with an XY term exactly when one, and only one, of its qubits lies in the pair that term acts on. The program in the final section tests only the property the construction rests on: every pair exchange keeps the Hamming weight. The construction adds terms to each layer without adding qubits or leaving the fixed-weight subspace.

Reference [4] documents a counterdiabatic extension of QAOA that incorporates approximate gauge potentials generated from nested commutators of the Ising portfolio Hamiltonian and the Hamming-weight-preserving XY mixer and benchmarks the resulting CCD-QAOA against standard XY, Grover and penalty-based QAOA. Its numerical simulations on constrained portfolio instances apply to its chosen synthetic Hamiltonians; the outline here follows the same nested-commutator approach and stops at the first-order term.

04 /Schedule multi-ramp penalties as internal QAOA parameters for joint feasibility optimization

Penalty coefficients are promoted from fixed hyperparameters to time-dependent variational schedules inside the QAOA circuit. Each constraint term is assigned its own linear ramp parameter vector that is optimized concurrently with the phase and mixer angles. The composite Hamiltonian at layer k therefore reads gamma_k times cost plus beta_k times mixer plus lambda_k times penalty where lambda_k itself follows a piecewise-linear schedule. This converts the classical penalty-tuning loop into a single higher-dimensional variational optimization that directly trades off feasibility against objective quality.

The feasibility-driven loss is defined as the expectation of the objective restricted to the measured feasible subset plus a soft penalty on the observed infeasibility rate. Because the XY mixer already guarantees zero infeasibility rate the loss reduces to the pure objective expectation inside the fixed-K subspace. The joint optimization landscape is smoothed by the ramp parameters which gradually emphasize the constraint term only in early layers before handing control to the return and risk terms in later layers.

An explicit linear operator maps the vector of ramp parameters onto the instantaneous penalty strength at each Trotter step. The operator is a lower-triangular matrix of size pp by pp whose entries are chosen so that the integrated penalty exposure equals a target integrated strength derived from the range bound of the first section. With equal positive entries on and below the diagonal, every ramp parameter after the first sets the step in penalty strength from one layer to the next. The schedule is monotonic when those steps share one sign, and non-positive steps give the early emphasis described above while their sizes stay variational.

Reference [3] documents two extensions of linear-ramp QAOA that assign each penalty term its own linear-ramp schedule turning penalty weights into variational parameters and introduces a feasibility-driven loss together with a filtered variant to tune the feasibility-optimality trade-off. Its numerical results on Earth-observation satellite planning as budget-constrained Maximum Weight Independent Set apply to its benchmark instances; the ramp-scheduling algebra here adopts the identical promotion of penalties to internal parameters while specializing the loss to portfolio cardinality.

05 /Benchmark finite-depth reachable quality against an exact classical reference

The finite-depth accessible set Rp(M,x0)R_p(M, x_0) holds every computational-basis state that can carry amplitude after pp layers of a mixer schedule MM applied to a feasible basis state x0x_0. A Dicke-state start covers the whole feasible set at depth zero, so the diagnostic concerns a basis-state start. An XY gate maps a basis state to itself or to a superposition with its pair-exchanged partner, and cost unitaries are diagonal, so supports propagate gate by gate. With ff minimized, the best reachable value is fR⋆=min⁡x∈Rpf(x)f_R^\star = \min_{x \in R_p} f(x), and QRQ_R states how much of the gap between feasible average and feasible optimum it closes. No depth-pp circuit with this schedule attains an expected objective below fR⋆f_R^\star, whatever its variational parameters.

The reference value foptf_{\text{opt}} comes from a classical exact solver. In the five-asset example of the final section, exhaustive enumeration of the ten feasible states plays that role. On larger instances a mixed-integer programming solver returns the optimum together with a certificate of optimality when the instance lies inside its tractability regime. A fair comparison gives that solver a time budget matched to the classical wall-clock cost of QAOA parameter optimization. The gap 1−QR1 - Q_R then states how much of the attainable improvement remains inaccessible to the finite-depth circuit.

No instance ensemble is generated here; the only computed instance is the five-asset example. A benchmark of this kind would draw the covariance matrix and the return vector from a fixed random seed and keep the covariance positive semidefinite. For NN from eight to twenty with K=3K = 3 the feasible sets hold between 56 and 1,140 states, the binomial coefficients (83)\binom{8}{3} and (203)\binom{20}{3}. Exhaustive enumeration is therefore an exact classical reference across that whole range, and no measured hardware performance enters the comparison.

Reference [1] documents the finite-depth accessible set R_p(M,x_0) for constraint-preserving mixers in QAOA and defines the normalized reachable-quality diagnostic Q_R that separates accessible volume from objective quality. Its evaluation using block-local XY mixer schedules on 207 favorable-tail CVaR configurations for constrained portfolio optimization applies to its synthetic quadratic problems. The accessible set above follows that description. The formula for QRQ_R below is this article's own normalization; the abstract of that work names the diagnostic without stating a formula.

Reachable-quality ratioEQ. 5.1
QR=⟨f⟩F−fR⋆⟨f⟩F−foptQ_R = \frac{\langle f \rangle_F - f_R^\star}{\langle f \rangle_F - f_{\text{opt}}}

fR⋆=min⁡x∈Rp(M,x0)f(x)f_R^\star = \min_{x \in R_p(M, x_0)} f(x) is the best objective inside the reachable set, ⟨f⟩F\langle f \rangle_F the average of ff over the feasible set FF and foptf_{\text{opt}} its minimum over FF. QRQ_R is dimensionless and at most one, with equality exactly when an optimal state is reachable. It is negative when the best reachable state is worse than the feasible average.

06 /Validate the weight conservation behind post-selection feasibility using the deterministic synthetic program

The program in the final section builds every binary vector for N=5N = 5 and keeps the ten of weight K=2K = 2. For each vector it computes the unpenalized objective and the penalized energy. It simulates no circuit and samples no bitstring, so it reports no feasibility rate. What it tests is the algebraic fact behind the feasibility guarantee: exchanging the entries of any two positions maps a basis state to a state of the same weight, in every weight sector.

On hardware, post-selection discards any measured string whose Hamming weight deviates from KK. The probability mass on discarded strings is the infeasibility leakage, and it is zero for an ideal XY evolution. The program contains no sampler and reports no leakage. Its closest counterpart is the reachable-set computation, run under the nearest-neighbor gate schedule of the final section. Starting from the state holding assets three and five, the sets after zero to three layers hold 1, 5, 9 and 10 states, and each is a subset of the feasible set.

Conservation of the Hamming weight is asserted at the level of basis states, for every state and every pair of positions. The program also counts the non-zero matrix elements of the pair-exchange mixer in each sector of Hamming weight hh and compares the counts with (Nh) h (N−h)\binom{N}{h}\,h\,(N - h). They are 0, 20, 60, 60, 20 and 0 for hh from zero to five. The weight-one sector carries 20 of them, so the mixer acts inside that sector as well. The test is combinatorial and exercises no compiled circuit.

Reference [2] documents reformulation of binary optimization problems possessing complex non-quadratic constraints as multi-objective QUBO problems where constraints are evaluated classically on the Pareto set rather than encoded as penalties. Its demonstration on binary portfolio optimization under Conditional Value-at-Risk using Quantum Approximate Multi-Objective Optimization on an illustrative 100-asset instance applies to its IBM Quantum hardware runs; the program here likewise evaluates its constraint classically, on enumerated states, and restricts attention to cardinality instead of CVaR.

07 /Document structural assumptions failure modes and risk controls for penalty-based encodings

A single scalar penalty coefficient can enforce several equality constraints at once in exact minimization. On a finite set of states it suffices that the coefficient exceed the objective range divided by the smallest non-zero squared violation. The weakness is that one coefficient cannot weight heterogeneous constraints separately, and a variational circuit at finite depth does not inherit the exact guarantee. The failure mode to plan for is a measured state that satisfies cardinality yet violates sector bounds once decoded to continuous weights. Risk controls therefore include explicit post-decoding feasibility repair together with a secondary classical projection onto the full constraint polytope.

Another assumption is that the covariance matrix remains positive semidefinite after QUBO embedding. Numerical rounding during matrix construction can introduce tiny negative eigenvalues. On binary vectors the quadratic form stays bounded, because the hypercube is finite, but the matrix is no longer a valid covariance: some real-valued combination has negative variance. The control consists of projecting Σ\Sigma onto the positive-semidefinite cone by clipping negative eigenvalues at machine epsilon before assembling the QUBO matrix. Clipping raises the trace by the size of the clipped eigenvalues, so the projection is accompanied by a check that the trace of the clipped matrix equals the original trace within six decimal places.

The assumption that variational parameters initialized from a linear ramp remain inside the basin of attraction of the global minimum is not guaranteed, and no depth threshold is measured here. One failure mode is a barren plateau, where the variance of the gradient becomes too small to resolve with a practical number of measurements. The prescribed risk control is to seed the optimizer with Trotterized adiabatic parameters obtained from a short classical simulated-annealing trajectory on the same QUBO before launching the quantum variational loop.

Reference [7] documents a slack-variable embedding that maps inequality constraints directly into ancilla qubits transforming the constrained Markowitz problem into a mixed-binary optimization suitable for QAOA and validates the model through simulation showing consistent discovery of optimal portfolios where penalty-based QAOA fails. Its Hamiltonian construction applies to its chosen synthetic Markowitz instances; the risk controls above stay with the penalty encoding and list its failure modes.

08 /Project regime probabilities onto asset weights via linear mappings

The multi-objective QUBO produces a Pareto front of non-dominated binary vectors each carrying a triple of risk return and diversification scores. An explicit linear operator MM of shape NN by JJ, where JJ is the number of latent regimes, maps the probability simplex over the regimes onto the NN-dimensional asset-weight vector. Each column of MM is the portfolio of one latent regime, with non-negative entries that sum to one, so MM is column-stochastic. Matrix-vector multiplication then yields continuous weights w=Mπw = M \pi, a convex combination of the columns, where π\pi lies in the probability simplex.

Because MM is column-stochastic, the mapping sends the simplex into the simplex: every weight lies between zero and one and the weights sum to one, for every π\pi. The weights are then scaled by total capital BB, which gives notional amounts in USD that sum to BB. All operations are differentiable and can be inserted into an outer classical optimizer that selects the preferred point on the Pareto front according to an investor-specific utility.

The units are simple. The entries of MM and of π\pi are dimensionless, so the weights are dimensionless, and multiplying by the budget BB in USD gives notional amounts per asset. Conservation of total capital is asserted in the program of the final section: the weights sum to one before scaling and the notional amounts sum to BB after scaling, both to floating-point tolerance.

Reference [6] documents formulation of the portfolio rebalancing schedule itself as a QUBO problem solved by QAOA inside a walk-forward framework that eliminates lookahead bias and employs Ledoit-Wolf shrinkage with hierarchical clustering to select decorrelated assets. Its hybrid classical-quantum architecture on S&P 500 data applies to its training period 2010-2024 and out-of-sample 2025 window; the mapping here is a fixed linear map from regime probabilities to weights and decodes no QUBO solution.

Regime-to-weight linear mappingEQ. 8.1
w=Mπ,w∈RN,  π∈ΔJ−1w = M \pi, \quad w \in \mathbb{R}^N, \; \pi \in \Delta^{J-1}

M∈RN×JM \in \mathbb{R}^{N \times J} is column-stochastic: its entries are non-negative and each column sums to one. JJ is the number of regimes, π\pi the regime-probability vector and ww the asset-weight vector; MM, π\pi and ww are dimensionless. The entries of ww are non-negative and sum to one.

09 /Reproduce all conservation invariants with the self-verifying Python fixture

The program below works on a synthetic universe of N=5N = 5 assets with K=2K = 2 and risk aversion q=0.8q = 0.8. It evaluates the penalized energy in two ways, directly from its definition and from the expanded QUBO coefficients, and asserts that the two agree on every binary vector for three penalty values. It also computes the pair exchanges of the XY mixer, the reachable sets of a nearest-neighbor gate schedule and the linear projection onto weights. Each layer of that schedule applies XY gates to the neighboring pairs of assets (1,2)(1,2), (2,3)(2,3), (3,4)(3,4) and (4,5)(4,5), in that order; the program numbers them from zero. Each result quoted in this section is printed by the program; the inputs are the constants in its first lines.

Ten binary vectors are feasible. The constrained minimizer holds assets one and four, with fopt=−0.15f_{\text{opt}} = -0.15. Without the constraint the minimizer adds asset five and reaches −0.168-0.168, so the constraint binds. The exact threshold is Pcrit=0.018P_{\text{crit}} = 0.018 and the range bound is 0.1680.168. With P=0.01P = 0.01 the penalized minimizer is that infeasible three-asset state. With P=0.02P = 0.02 it is the constrained minimizer, although the lowest infeasible energy, −0.148-0.148, still lies below the worst feasible objective, −0.01-0.01. With P=0.2P = 0.2, above the range bound, the lowest infeasible energy is 0.0320.032 and every infeasible state lies above every feasible one.

From the start state holding assets three and five, that gate order reaches 1, 5, 9 and 10 states after zero to three layers. With a feasible average of −0.0888-0.0888, the ratio QRQ_R takes the values −0.2092-0.2092, 0.77120.7712, 11 and 11. Two layers already reach the optimum while one feasible state remains inaccessible, which separates objective quality from accessible volume. The mapping matrix MM has one column per regime, and the example uses J=2J = 2 regimes. With regime probabilities π=(0.6,0.4)\pi = (0.6, 0.4) the weights are 0.280.28, 0.260.26, 0.220.22, 0.140.14 and 0.10.1. They sum to one, and with B=1,000,000B = 1{,}000{,}000 USD the notional amounts sum to BB.

Reference [8] documents extension of QUBO portfolio models with slack variables for sector and balance-sheet constraints together with hybrid solver implementations on D-Wave hardware and direct comparison against CPLEX on the identical constrained quadratic problems. Its analysis of QUBO versus CQM formulations applies to its chosen balance-sheet metrics and sector-band instances; the program here uses a slack-free cardinality penalty and adds projection and conservation asserts of its own.

Capital conservation after scalingEQ. 9.1
∑i=1Nwi=1,a=B w,∑i=1Nai=B\sum_{i=1}^N w_i = 1, \quad a = B\,w, \quad \sum_{i=1}^N a_i = B

w=Mπw = M \pi is the dimensionless weight vector of the regime mapping, BB the budget in USD and aa the vector of notional amounts in USD. The first identity holds for every π\pi in the simplex when MM is column-stochastic; the second follows by linearity.

python60 LINES EXECUTED · PYTHON 3.12.3 · 11 ASSERTS PASSED
# Synthetic unit-check fixture; illustrative only, no live market data or performance claims.
import itertools
import math
n, k, q, budget = 5, 2, 0.8, 1000000.0  # assets, cardinality, risk aversion, capital in USD
mu = [0.08, 0.12, 0.05, 0.15, 0.09]
cov = [[0.04, 0.01, 0.02, 0.00, 0.01], [0.01, 0.09, 0.03, 0.02, 0.01],
       [0.02, 0.03, 0.05, 0.01, 0.00], [0.00, 0.02, 0.01, 0.06, 0.02],
       [0.01, 0.01, 0.00, 0.02, 0.03]]
mix, regime = [[0.4, 0.1], [0.3, 0.2], [0.1, 0.4], [0.1, 0.2], [0.1, 0.1]], [0.6, 0.4]
weak, tight, safe = pens = 0.01, 0.02, 0.2  # penalty coefficients
states = list(itertools.product([0, 1], repeat=n))
pairs = list(itertools.combinations(range(n), 2))

def f(x):  # unpenalized objective, to be minimized
    risk = sum(cov[i][j] * x[i] * x[j] for i in range(n) for j in range(n))
    return q * risk - sum(mu[i] * x[i] for i in range(n))
def energy(x, p): return f(x) + p * (sum(x) - k) ** 2  # penalized form
def qubo(x, p):  # the same energy from expanded QUBO coefficients
    lin = sum((q * cov[i][i] - mu[i] + p * (1 - 2 * k)) * x[i] for i in range(n))
    return lin + sum(2 * (q * cov[i][j] + p) * x[i] * x[j] for i, j in pairs) + p * k * k
def swap(x, i, j): return tuple(x[j] if m == i else x[i] if m == j else x[m] for m in range(n))

feasible = [x for x in states if sum(x) == k]
best, free = min(feasible, key=f), min(states, key=f)
f_opt, f_top, f_mean = f(best), max(map(f, feasible)), math.fsum(map(f, feasible)) / len(feasible)
f_range = max(map(f, states)) - f(free)
p_crit = max((f_opt - f(x)) / (sum(x) - k) ** 2 for x in states if sum(x) != k)
arg_weak, arg_tight = [min(states, key=lambda x: energy(x, p)) for p in (weak, tight)]
low = {p: min(energy(x, p) for x in states if sum(x) != k) for p in (p_crit, tight, f_range, safe)}
links = [sum(x[i] != x[j] for x in states if sum(x) == h for i, j in pairs) for h in range(n + 1)]
reach = [{(0, 0, 1, 0, 1)}]
for depth in range(3):  # one layer: XY gates on neighbors (0,1), (1,2), (2,3), (3,4) in order
    reach.append(set(reach[-1]))
    for i in range(n - 1):
        reach[-1] |= {swap(x, i, i + 1) for x in reach[-1]}
ratio = [(f_mean - min(map(f, r))) / (f_mean - f_opt) for r in reach]
weights = [sum(m * r for m, r in zip(row, regime)) for row in mix]
notional = [budget * w for w in weights]

assert len(feasible) == math.comb(n, k) and reach[-1] == set(feasible)
assert math.isclose(10 * f_mean, (n - 2) * sum(f(x) for x in states if sum(x) == 1) + f(states[-1]))
assert all(math.isclose(energy(x, p), qubo(x, p), abs_tol=1e-12) for x in states for p in pens)
assert weak < p_crit < tight < f_range < safe and math.isclose(low[p_crit], f_opt)
assert sum(arg_weak) != k and arg_tight == best and low[tight] < f_top <= low[f_range] < low[safe]
assert all(sum(swap(x, i, j)) == sum(x) for x in states for i, j in pairs)
assert all(links[h] == math.comb(n, h) * h * (n - h) for h in range(n + 1))
assert all(r < s and a <= b <= 1 for r, s, a, b in zip(reach, reach[1:], ratio, ratio[1:]))
assert all((best in r) == math.isclose(v, 1) for r, v in zip(reach, ratio)) and ratio[0] < 0
assert all(math.isclose(sum(col), 1) and min(col) >= 0 for col in zip(*mix))
assert min(weights) >= 0 and math.isclose(sum(weights), 1) and math.isclose(sum(notional), budget)
out = dict(count_n5_k2=len(feasible), count_n8_k3=math.comb(8, 3), count_n20_k3=math.comb(20, 3),
           best=best, f_opt=f_opt, f_mean=f_mean, f_top=f_top, free=free, f_free=f(free),
           f_range=f_range, p_crit=p_crit, arg_weak=arg_weak, arg_tight=arg_tight,
           low_tight=low[tight], low_safe=low[safe], weight_sum=sum(weights), capital=sum(notional))
for key, value in out.items():
    print(f"RESULT {key} = {round(value, 6) if isinstance(value, float) else value}")
print(f"SERIES mixer_links = {links}", f"SERIES reach_sizes = {[len(r) for r in reach]}", sep="\n")
print(f"SERIES quality_ratio = {[round(v, 4) for v in ratio]}")
print(f"SERIES weights = {[round(w, 4) for w in weights]}")
print("OK")
CAPTURED OUTPUT22 LINES · 11 ASSERT STATEMENTS, 11 EVALUATIONS PASSED · RUN NOV 13, 2026 · SHA-256 6ec053c3ddab…
RESULT count_n5_k2 = 10
RESULT count_n8_k3 = 56
RESULT count_n20_k3 = 1140
RESULT best = (1, 0, 0, 1, 0)
RESULT f_opt = -0.15
RESULT f_mean = -0.0888
RESULT f_top = -0.01
RESULT free = (1, 0, 0, 1, 1)
RESULT f_free = -0.168
RESULT f_range = 0.168
RESULT p_crit = 0.018
RESULT arg_weak = (1, 0, 0, 1, 1)
RESULT arg_tight = (1, 0, 0, 1, 0)
RESULT low_tight = -0.148
RESULT low_safe = 0.032
RESULT weight_sum = 1.0
RESULT capital = 1000000.0
SERIES mixer_links = [0, 20, 60, 60, 20, 0]
SERIES reach_sizes = [1, 5, 9, 10]
SERIES quality_ratio = [-0.2092, 0.7712, 1.0, 1.0]
SERIES weights = [0.28, 0.26, 0.22, 0.14, 0.1]
OK

Standard output of the program above, captured when it was run in the journal's sandbox on Nov 13, 2026. The SHA-256 of the program text shown here equals the hash stored with that run. All inputs are synthetic.

∎

Research is complete only when the assumptions, experiment, and limitations can be reconstructed.

This perspective is research commentary. It does not constitute investment advice or evidence of live strategy performance. Experimental methods require project-specific testing. Equations and code illustrate research formulations, not measured live returns.

More perspectivesExplore the engineering atlas