Unified Problem Compiler¶
ProblemCompiler turns one Graph, MIS, MWIS, QUBO, or Ising problem into a Digital, Hybrid, or Analog Native Program. The three modes share canonical problem data, a logical Hamiltonian, Target-aware mapping, bit order, decoding, and execution results.
Run the complete 3x3 MIS example from a source checkout:
PYTHONPATH=src python3 examples/user/problem_compiler_3x3_mis.py \
--output-dir artifacts/problem_compiler_3x3_mis \
--language en
The script evaluates two real parameter points per mode and saves three route reports plus one derived comparison:
problem_3x3_mis_digital.htmlproblem_3x3_mis_hybrid.htmlproblem_3x3_mis_analog.htmlproblem_3x3_mis_route_comparison.html
Each report includes the source problem, logical Hamiltonian, Target mapping, atom layout, term assignment, parameter schema, generated circuit or controls, execution evidence, counts, decoded candidates, objective history, energy decomposition, and bounded classical baseline.
The weighted example runs Digital QAOA, Digital VQE, Hybrid QAOA, and Analog QAA for the same 2x2 MWIS:
PYTHONPATH=src python3 examples/user/problem_compiler_mwis.py \
--output-dir artifacts/problem_compiler_mwis \
--language en
MWISProblemIR minimizes over graph edges. P must be strictly greater than max(min(w_i, w_j)) across all edges. The example's unique exact solution is 1001, selecting weight 9. Its reports show source node weights, each candidate's selected weight, and probability-weighted expected selected weight.
Compile And Run¶
Import the compiler from its owner package:
from cascaqit.algorithms import (
HardwareEfficientAnsatz,
OptimizerConfig,
PauliMeasurementConfig,
SPSAConfig,
SampledSelectionConfig,
)
from cascaqit.problems import ProblemCompiler
compiler = ProblemCompiler()
analysis = compiler.analyze(problem, target=target)
compiled = compiler.compile(
problem,
mode="hybrid",
algorithm="qaoa",
target=target,
layers=2,
)
execution = compiled.run(
params={
"gamma_0": 0.2,
"gamma_1": 0.3,
"beta_0": 0.1,
"beta_1": -0.2,
},
shots=256,
seed=7,
)
execution.report("hybrid-problem.html", language="en")
analyze() does not generate or execute a program. It returns the canonical problem, logical Hamiltonian, layout, typed van der Waals interaction and pair analysis, per-term implementation candidates, resource estimate, and feasibility for all three modes. MIS and MWIS analysis maps every source edge constraint to its canonical quadratic term. MIS proves the unweighted vertex-removal threshold; MWIS proves the weighted threshold defined above.
compile() requires an explicit mode, algorithm, and target. The accepted combinations are:
| Mode | Algorithm | Native Program | Current rule |
|---|---|---|---|
digital |
qaoa |
Circuit |
Uses the existing QAOA circuit path and supports its layer count. |
digital |
vqe |
Circuit |
Accepts the default template, a hardware-efficient Definition, a fixed-cardinality Definition, or a parameterized custom Circuit at a fixed depth. |
hybrid |
qaoa |
HybridProgram |
Accepts a positive layer count and emits exact D-(A-D)^p-measure; each layer has a non-empty Analog contribution and explicit Digital residual. |
analog |
qaa |
AHSProgram |
Requires the complete Hamiltonian to be expressible by the selected Target. |
dad is the Hybrid topology, not an algorithm. ahs is the Analog program model. The public API does not expose a strategy argument.
Unified VQE keeps the source Problem decoder and baseline while changing only the Digital Ansatz:
compiled_vqe = compiler.compile(
problem,
mode="digital",
algorithm="vqe",
target=target,
layers=2,
ansatz=HardwareEfficientAnsatz(("rx", "rz"), "circular"),
)
Import HardwareEfficientAnsatz from cascaqit.algorithms. Rotation axes may be RX, RY, or RZ in a declared unique order; entanglement may be linear or circular CX. The default remains RY then RZ with linear CX. A parameterized custom Circuit can also be passed to the same Unified compile and then used with run(), evaluate(), optimize(), decode(), and Problem reports. Its exact structural payload is saved in the Ansatz contract.
When a Problem requires an exact selection count for one or more variable groups, pass CardinalityPreservingAnsatz:
from cascaqit.algorithms import CardinalityConstraint, CardinalityPreservingAnsatz
fixed_count = CardinalityPreservingAnsatz(
constraints=(
CardinalityConstraint(("x0", "x1", "x2", "x3"), weight=2),
),
free_rotation_axes=("ry",),
)
compiled_vqe = compiler.compile(
problem,
mode="digital",
algorithm="vqe",
target=target,
layers=2,
ansatz=fixed_count,
)
Givens rotations preserve each declared Hamming weight, while ungrouped variables retain free rotations. The caller must declare the groups explicitly; the compiler does not infer constraints from QUBO coefficients or metadata. The Definition does not remove Hamiltonian penalties, and the Problem decoder remains responsible for complete business feasibility.
Run the complete configurable and custom workflow:
PYTHONPATH=src python3 examples/user/unified_vqe_ansatz_workflow.py \
--output-dir artifacts/unified_vqe_ansatz --language en
Execution Results¶
Every compile result provides the same high-level methods:
execution = compiled.run(params=values, shots=256, seed=7)
evaluation = compiled.evaluate(params=values, seed=7)
selected = compiled.optimize(
parameter_sets=(first_values, second_values),
shots=256,
seed=7,
)
continuous = compiled.optimize(
optimizer=OptimizerConfig(
method="COBYLA",
max_iterations=40,
max_evaluations=24,
starts=3,
seed=7,
),
initial_parameters=first_values,
shots=256,
seed=7,
)
sampled_vqe = compiled_vqe.optimize(
optimizer=OptimizerConfig(
method="SPSA",
max_iterations=4,
max_evaluations=50,
max_backend_executions=50,
seed=7,
spsa=SPSAConfig(
learning_rate=0.2,
perturbation=0.1,
objective_repeats=2,
max_objective_repeats=5,
objective_standard_error_target=0.02,
),
),
initial_parameters=first_values,
measurement=PauliMeasurementConfig(
shots_per_group=512,
allocation="coefficient_l1",
),
sampled_selection=SampledSelectionConfig(
candidate_count=3,
repeats_per_candidate=2,
max_repeats_per_candidate=4,
shots_per_group=1024,
),
shots=256,
seed=7,
)
decoded = bound_compiled.decode(existing_result)
optimize() requires exactly one search input. parameter_sets executes the caller's points in order. optimizer runs COBYLA, Nelder-Mead, Powell, or native SPSA through the same Digital, Hybrid, or Analog program path. Digital QAOA and VQE additionally accept L-BFGS-B with GradientConfig; Digital VQE also accepts native Adam. Their run(), evaluate(), gradient(), and optimize() methods accept canonical NoiseModel and SimulationOptions for deterministic exact-density noisy execution. VQE can instead combine finite-shot QWC measurement with SPSA or Adam. Analog and Hybrid reject noisy requests or gradient execution before any Job starts. Every objective or gradient evaluation binds and executes a Native Program, then records its Backend Jobs, result hashes, parameters, statistics, and available noise evidence. starts sets the number of independent optimizer runs; iteration and evaluation budgets apply to each start. ProblemOptimizationIR retains SPSA directions or Adam moments and updates with the shared parameter and objective history.
Digital VQE also accepts measurement with SPSA. SPSAConfig.objective_repeats sets the minimum complete QWC evaluations per logical point. Adding a larger max_objective_repeats and a positive objective_standard_error_target enables bounded adaptive repeats: centers add one evaluation at a time, while plus/minus points add balanced pairs until both errors reach the target, the maximum is reached, or the hard budget prevents another complete step. Gradients, best-point selection, and confirmation candidates use the resulting pooled means; nfev counts every actual repeat. Uniform, coefficient-L1, and pilot-variance allocation keep their per-evaluation semantics. shots controls only the final computational-basis sampling used by the Problem decoder. Optional sampled_selection independently remeasures the strongest pooled optimizer points in fixed or sequential mode. ProblemOptimizationIR.sampled_evaluations keeps every raw repeat, Pauli-group count, uncertainty, stop reason, and cost. The report separates optimization, confirmation, and final sampling. QUBO and Ising Hamiltonians are diagonal and normally form one QWC group, so non-uniform allocation has no effect unless the supplied route contains multiple measurement bases.
The same Unified VQE path accepts SPSAConfig(stopping=SPSAStoppingConfig(...)). It stops at the first complete passing window, stores the decision on each optimizer start, still evaluates the final center, and exposes the checks in the Problem report. Sampled-standard-error stopping additionally requires repeated sampled objectives. The thresholds are user configuration, not a convergence or optimality certificate.
Unified Digital VQE also accepts SPSAConfig(learning_rate=None, learning_rate_calibration=SPSALearningRateCalibrationConfig(...)). Each start calibrates at its own initial point before formal iterations. Calibration directions use the same exact, exact-density, ideal sampled, or noisy sampled Problem objective as the optimizer, and their evaluation and Backend cost enter the same hard limits. ProblemOptimizationIR.starts retains the derived scale and complete direction evidence; JSON restoration and the standard Problem report use those saved facts. The compiler does not derive this setting from QUBO coefficients or business metadata, and calibration does not change the Problem Hamiltonian, penalties, decoder, or candidate-selection rule.
Finite-shot Problem VQE requires native SPSA or Adam, positive final shots, and an unbound Digital VQE compile result. It accepts ideal execution or one run-level NoiseModel and SimulationOptions; supported sampled channels are Digital preparation, gate, idle, crosstalk, and readout, with auto, density_matrix, or trajectory simulation. Optimization, independent confirmation, and final sampling retain the same execution context. SPSA may use bounded standard-error-driven objective repeats. Adam may use fixed or bounded adaptive complete-gradient repeats, complete covariance, and optional update-size plus gradient-uncertainty stopping. These controls do not prove convergence or candidate optimality. SciPy optimizers and parameter_sets fail before partial sampled work starts. optimize_layers() and optimize_layers_repeated() accept the same estimator only when measurement and sampled_selection are supplied together.
Continuous Hybrid optimization can execute independent starts in local worker processes by passing parallel_workers=2 or parallel_workers="auto" to optimize(). The planner limits workers by available CPUs and memory, uses spawn-safe workers on macOS and Windows, fixes native thread pools to one thread per process, and merges results by stable start index. This option does not parallelize one SciPy start. It is rejected for Digital or Analog optimization, caller-supplied parameter_sets, persistent Backends, and Backends configured with kernel_threads > 1.
For a Digital compile result, gradient(params=...) executes the same occurrence-level parameter-shift plan as standalone QAOA or VQE. L-BFGS-B stores those gradients in ProblemOptimizationIR.gradients and preserves the decoded QUBO objective for every shifted Circuit. The result separates nfev, njev, shift Jobs, and total Backend executions. Physical noise runs through an internal wrapper, so parameter history and reports keep both the source Digital Program hash and the runtime Program hash. See QAOA And VQE for the supported channel, estimator, and method boundary.
Explicit optimizer bounds must stay inside the compiled parameter schema. When bounds are omitted, QAOA angles use their standard domains, VQE rotations use [-pi, pi], and Analog parameters use their declared finite bounds. Schema defaults provide start zero when complete; otherwise Digital QAOA/VQE uses a seeded point. Explicit initial_parameters provide start zero, while later starts remain independently seeded.
For a p-layer QAOA compile result, initialization="layerwise" accepts the selected p-1 mapping and interpolates gamma/beta sequences. For built-in VQE, layer transfer belongs to the Ansatz Definition: existing parameters are retained and the last layer is copied for every declared rotation axis. The automatic layer APIs perform this transfer before the optimizer sees the current-layer mapping. Custom VQE and Analog QAA do not define automatic transfer.
Exact search returns the lowest objective actually observed. Sampled VQE final-samples either the lowest observed sample mean or the point selected by independent confirmation. Neither path proves convergence to a global optimum.
Automatic Layer Experiments¶
One Optimization Per Layer¶
Use optimize_layers() when the depth should be selected by a repeatable execution rule instead of an outer Demo loop:
experiment = compiler.optimize_layers(
problem,
mode="hybrid",
algorithm="qaoa",
target=target,
max_layers=4,
optimizer=OptimizerConfig(
method="COBYLA",
max_evaluations=24,
starts=2,
seed=7,
),
min_improvement=1e-3,
patience=1,
shots=256,
seed=7,
)
experiment.report("problem-layer-experiment.html", language="en")
selected = experiment.selected_execution
The compiler analyzes the Problem once, then compiles and optimizes contiguous depths starting at p=1. The first layer uses schema defaults, an explicit initial_parameters mapping, or a seeded point. Every later layer uses the previous layer's selected parameters as its first start; additional starts remain independently seeded. max_iterations, max_evaluations, and starts apply separately to every executed layer, so total_evaluation_count is the cost to inspect before increasing max_layers.
A deeper layer replaces the incumbent only when its layer objective decreases by more than the 1e-12 numeric tolerance and by at least min_improvement. Exact runs use expected Problem objective. Sampled Digital VQE uses the independently confirmed candidate energy, and the confirmed parameters become the next layer's first start. It never substitutes the lowest optimizer sample or the final computational-basis Problem objective. patience counts consecutive layers that fail this test.
Pass measurement and sampled_selection together to run one finite-shot SPSA or Adam optimization per VQE depth:
sampled = compiler.optimize_layers(
problem,
mode="digital",
algorithm="vqe",
target=target,
max_layers=3,
optimizer=OptimizerConfig(
method="SPSA",
max_evaluations=12,
max_backend_executions=12,
seed=7,
),
measurement=PauliMeasurementConfig(shots_per_group=256),
sampled_selection=SampledSelectionConfig(
candidate_count=2,
repeats_per_candidate=2,
shots_per_group=512,
max_backend_executions=4,
),
shots=128,
patience=2,
seed=7,
)
ProblemLayerExperimentResult separates objective, confirmation, and final-sampling Jobs and shots. Its report states the layer objective source and shows both confirmed energy and final decoded Problem objective. JSON restore recomputes the selected depth, parameter transfer, cost totals, and source linkage.
This workflow supports Digital QAOA, Digital VQE with either built-in Definition, and Hybrid QAOA. Sampled execution is limited to ideal or noisy Digital VQE with native SPSA or Adam, positive final shots, and independent candidate confirmation. Analog QAA and custom VQE are unsupported. One explicit optimizer bounds tuple cannot be reused because the parameter dimension changes with depth; omit bounds so each compiled ParameterSchemaIR resolves them. The selected depth is a fixed-budget engineering choice, not a statistical significance result or a proof of optimal depth.
Independent Repeats And Statistical Selection¶
Use optimize_layers_repeated() when one optimizer outcome is not enough evidence for choosing a depth:
experiment = compiler.optimize_layers_repeated(
problem,
mode="digital",
algorithm="qaoa",
target=target,
max_layers=4,
repeats=5,
optimizer=OptimizerConfig(
method="COBYLA",
max_evaluations=40,
),
confidence_level=0.95,
min_improvement=0.01,
patience=2,
seed=7,
)
experiment.report("problem-repeated-layer-experiment.html", language="en")
Digital VQE can run the same repeated experiment with finite-shot objectives by passing an SPSA or Adam optimizer, PauliMeasurementConfig, SampledSelectionConfig, and positive final shots. The measurement and selection configs must be supplied together. Optional noise and options apply unchanged to every layer, repeat, candidate confirmation, and final sampling. Layer statistics use independently confirmed candidate energy, and the next layer warm-starts from that confirmed parameter point.
repeats counts complete, independent optimizer runs at each depth. It is separate from optimizer starts, measurement shots, and noisy-simulation trajectories. The optimizer configuration must leave seed=None; the root seed passed to optimize_layers_repeated() derives a distinct seed for every layer and repeat. The first layer starts from seed-derived explicit points. At later depths, repeat i is warm-started only from repeat i at the previous depth.
Each layer stores the raw executions, sample mean, unbiased sample variance, standard error, and two-sided Student-t confidence interval. A candidate depth is compared with the current incumbent by paired repeat index. It replaces the incumbent only when the one-sided Student-t lower confidence bound for objective improvement clears min_improvement and the numeric tolerance. patience counts consecutive candidates without that evidence.
total_optimization_count counts complete optimizer runs; total_evaluation_count counts objective evaluations. Sampled results additionally expose objective, confirmation, final-sampling, and complete-workflow Backend and shot totals. JSON restore recomputes VQE warm starts, seeds, statistics, paired comparisons, selection, stopping, cost, and experiment identity. This entry supports Digital QAOA, Digital VQE with either built-in Definition, and Hybrid QAOA. It does not support Analog QAA, custom VQE, explicit cross-depth bounds, or caller-supplied initial parameters. The confidence interval describes these repeated local runs under one fixed configuration; it does not prove global optimality, optimal theoretical depth, hardware performance, or quantum advantage.
Optimization Reports And Comparisons¶
ProblemExecutionResult.report() shows the complete Ansatz Definition, parameter layout, required gates, circuit/spec hashes, layer-transfer rule, optimizer-start boundaries, observed objective and running best, parameter trajectories, final sampling, decoded candidates, and the bounded classical baseline. Gradient runs add the parameter-shift plan, component and L2-norm trajectories, nfev/njev, Backend cost, and expandable positive/negative shift evidence. MIS and MWIS reports also show the feasible probability and expected constraint-violation count for every evaluated parameter point. Their static penalty table records the strength, strict threshold, sufficiency margin, and constraint-to-term mapping. Runtime tables split each candidate and complete result distribution into business objective, per-constraint penalty, and total objective. MWIS reports add node weights, candidate selected weight, and expected selected weight.
Plain QUBO and Ising inputs have no explicit source-constraint contract. CASCAQit therefore does not infer that a quadratic coefficient is a penalty: penalty_analysis is None, penalty_model_status is not_applicable, and the complete canonical objective is reported as business_objective with zero inferred penalty energy.
Completed Digital QAOA/VQE or Hybrid QAOA runs with different layer counts can be compared without rerunning them:
from cascaqit import visualize
visualize(
{"p=1": result_p1, "p=2": result_p2},
output="qaoa-layer-comparison.html",
)
The same call can compare Digital QAOA, Digital VQE, Hybrid QAOA, and Analog QAA results. Inputs must share problem_hash and logical order; mode, algorithm, Target, layers, optimizer budget, and shots may differ. The report aligns canonical objective and energy evidence while keeping compile identity, program, convergence, sampling, candidates, and resources separate. Different route units and local timings are descriptive evidence, not an automatic performance ranking.
ProblemExecutionResult retains the original ResultIR, candidates, candidate energy breakdowns, best observed candidate, feasibility, constraint violations, bounded baseline, parameter history, and a serializable ProblemExecutionContextIR. Every ProblemParameterEvaluationIR records the best candidate at that point, total feasible probability, probability-weighted constraint violation count, expected energy breakdown, and expected/best-candidate objective gaps against the bounded baseline. Finite-shot VQE stores its non-decodable Pauli objective Jobs and optional confirmation under ProblemOptimizationIR; its one final computational-basis result remains in parameter_history. Constructors and JSON restore paths recompute both evidence chains and reject mismatched selected parameters, costs, Hamiltonians, measurement plans, or energy decomposition.
The context contains the analysis, term mapping, parameter schema, and exact Native Program snapshot, so a report can be rebuilt after JSON round-trip without the original compiler object.
Mapping Boundary¶
The local mapping model uses public typed Target defaults for C6 and the inclusive cutoff, then evaluates each mapped pair as
Analog QAA and Hybrid D-A-D lowering place that same canonical interaction in every generated AHSProgram; mapping and program hashes therefore remain aligned. These public defaults are reference facts, not production calibration, and untyped Target.metadata["blockade_radius"] does not define finite interaction strength.
- Digital compilation can use gate decomposition when Analog geometry cannot express a term.
- Unified Digital VQE accepts hardware-efficient and fixed-cardinality built-in Definitions plus fixed-depth custom Circuits. Automatic layer experiments require a built-in Definition because custom Circuits declare no cross-depth transfer rule.
- Hybrid compilation requires a non-empty Analog cost contribution. Remaining or compensating coefficients are explicit Digital residual terms.
- Analog compilation cannot hide unsupported terms in a Digital block. Signed or non-geometric couplings fail when the complete Hamiltonian cannot be represented within tolerance.
- Generated Hybrid and Analog programs are executable by the local simulator, but
hardware_executableremains false without production Target, calibration, placement, scheduling, endpoint, and live execution evidence.
The Hybrid compiler accepts any positive QAOA layer count. It prepares the uniform superposition once, then repeats an Analog cost block and its Digital residual/mixer for every layer before terminal measurement. Every gamma_i must be strictly positive because it also defines an AHS duration. The compiler does not provide non-commuting Trotter splits, alternative Hybrid topologies, general minor embedding, gadget construction, automatic layout search, or a global-optimality guarantee.