Gathering Results
After running optimize!(model), you can retrieve various information about the solutions and the solving process.
Solution Status
Termination Status
The termination status indicates how the optimization process ended:
status = termination_status(model)Common termination statuses include:
OPTIMAL: The solver found an optimal solutionLOCALLY_SOLVED: A locally optimal solution was foundTIME_LIMIT: The solver stopped due to time limitITERATION_LIMIT: The solver stopped due to iteration limit
Primal Status
The primal status indicates the quality of the primal solution:
pstatus = primal_status(model)A status of FEASIBLE_POINT indicates that a valid solution was found.
Solution Summary
For a quick overview of the optimization result:
solution_summary(model)Retrieving Variable Values
Single Solution
Get the value of a single variable:
x_value = value(x)Get values of an array of variables:
x_values = value.(x)Multiple Solutions
Many QUBO solvers, especially quantum annealers and samplers, return multiple solutions. Access them using the result keyword:
# Number of solutions found
n_solutions = result_count(model)
# Access the i-th solution
for i in 1:n_solutions
xi = value.(x, result = i)
println("Solution $i: $xi")
endFeasibility and Constraint Violations
For constrained models, inspect feasibility separately from the objective value. violations reports the source constraints violated by a sampled result after projecting the QUBO solution back to the source variables. is_feasible checks one result, and feasibility_report summarizes one or more results.
violated = ToQUBO.violations(model; result = 1, atol = 1e-6)
ok = ToQUBO.is_feasible(model; result = 1)
report = ToQUBO.feasibility_report(model)For JuMP models, pass the JuMP.Model directly. For low-level MOI usage, pass the ToQUBO.Optimizer.
using JuMP
using QUBODrivers
using ToQUBO
using ToQUBO: Attributes
model = Model(() -> ToQUBO.Optimizer(ExactSampler.Optimizer))
@variable(model, x[1:2], Bin)
@objective(model, Max, 3x[1] + 3x[2])
capacity = @constraint(model, x[1] + x[2] <= 1)
# Deliberately undersize this penalty to demonstrate infeasibility reporting.
set_attribute(capacity, Attributes.ConstraintEncodingPenaltyHint(), -0.1)
optimize!(model)
violated = ToQUBO.violations(model; result = 1)
first(violated).violation1.0The feasibility helpers use the same result indexing as value and objective_value, so sampling runs can be summarized as rates:
report = ToQUBO.feasibility_report(model; result = 1:result_count(model))
report.feasible_count / report.result_count0.75Feasibility in Solve Results
Samplers solve the unconstrained target model, so on their own they report FEASIBLE_POINT for every sample. By default, ToQUBO re-checks each queried result against the source constraints and reports INFEASIBLE_POINT for samples that violate them:
primal_status(model) # result 1 violates the capacity constraintINFEASIBLE_POINT::ResultStatusCode = 3Set Attributes.PrimalFeasibilityCheck() to false to restore the sampler's raw status. Like any JuMP model modification, setting the attribute marks the model dirty, so re-optimize before querying results again:
set_attribute(model, Attributes.PrimalFeasibilityCheck(), false)
optimize!(model)
primal_status(model)FEASIBLE_POINT::ResultStatusCode = 1objective_value reports the target QUBO energy, which includes the penalty terms introduced by the reformulation. source_objective_value evaluates the original objective function on the decoded solution instead, so the two differ exactly when a penalty is active:
(objective_value(model), ToQUBO.source_objective_value(model))(5.9, 6.0)To check every sampling run automatically, enable Attributes.AutoFeasibilityReport(). After each solve, ToQUBO computes a ToQUBO.feasibility_report over all results, caches it for later feasibility_report calls, and warns when any sample is infeasible. The warning respects Attributes.Warnings().
set_attribute(model, Attributes.AutoFeasibilityReport(), true)
optimize!(model)
# ┌ Warning: 1 of 16 sampled result(s) violate source constraints ...Constraint violations are measured as follows:
| Source constraint type | Violation measure |
|---|---|
Variable bounds and scalar affine/quadratic EqualTo, LessThan, GreaterThan, Interval | MOI.Utilities.distance_to_set(value, set) |
VectorOfVariables in SOS1 | Sum of absolute values outside the largest-magnitude entry |
Affine/quadratic Indicator | Zero when inactive; otherwise the inner scalar-set violation |
Each ConstraintViolation includes the source constraint index, function type, set type, evaluated source-function value, raw residual, nonnegative violation magnitude, projected values for variables referenced by that constraint, and whether the constraint was marked with ToQUBO.Attributes.SoftConstraint (soft::Bool). For encoded integer variables, the projected source values are the compiler's decoded values for the sampled binary state; continuous discretizations report the decoded grid value.
Soft Constraints and Penalized Preferences
Constraints that represent soft preferences rather than hard feasibility requirements can be marked with ToQUBO.Attributes.SoftConstraint:
set_attribute(preference, Attributes.SoftConstraint(), true)
set_attribute(preference, Attributes.ConstraintEncodingPenaltyHint(), -0.5)Marking a constraint with SoftConstraint() does not remove its compiled penalty term from the QUBO Hamiltonian or reduce its initial automatically inferred penalty coefficient. To give a soft constraint a bounded preference weight instead of an exact-penalty coefficient, pair SoftConstraint() with ToQUBO.Attributes.ConstraintPenaltyScale, ToQUBO.Attributes.ConstraintPenaltyOffset, or an explicit ToQUBO.Attributes.ConstraintEncodingPenaltyHint.
Soft constraints still have their residuals and violation magnitudes measured:
ToQUBO.violations(model; result = i)includes violated soft constraints by default withv.soft == true(passinclude_soft = falseto filter to hard constraints only).ToQUBO.is_feasible,FeasibilityResult.feasible,primal_status,Attributes.AutoFeasibilityReport(), and iterative penalty refinement underAttributes.MaxPenaltyUpdates()reflect hard constraints only.FeasibilityResultexposessoft_violation_count,soft_max_violation,soft_total_violation, andsoft_by_constraint_typealongside the hard-constraint fields (violation_count,max_violation,total_violation,by_constraint_type), andFeasibilityReportexposessoft_violation_count,soft_max_violation, andsoft_total_violationacross the summarized results.
Objective Value
Single Solution
Get the objective value of the best solution:
obj = objective_value(model)Multiple Solutions
Get the objective value for a specific solution:
obj_i = objective_value(model, result = i)Multi-Objective Scalarization and Per-Objective Values
When a model defines a vector objective (@objective(model, Min, [f1, f2])), ToQUBO scalarizes the components into the target QUBO using per-objective weights (ToQUBO.Attributes.ObjectiveWeights / ToQUBO.Attributes.ObjectiveWeight) and per-objective optimization senses (ToQUBO.Attributes.ObjectiveSenses / ToQUBO.Attributes.ObjectiveSense). After solving, query each component's unweighted value on any sampled result via ToQUBO.source_objective_values, ToQUBO.Attributes.ObjectiveFunctionValues, or ToQUBO.Attributes.ObjectiveFunctionValue, while ToQUBO.source_objective_value (with no component index) reports the scalarized penalty-free source objective:
set_attribute(model, Attributes.ObjectiveWeights(), [2.0, 0.5])
set_attribute(model, Attributes.ObjectiveSenses(), [MOI.MIN_SENSE, MOI.MAX_SENSE])
optimize!(model)
component_values = ToQUBO.source_objective_values(model; result = 1)
first_component = ToQUBO.source_objective_value(model, 1; result = 1)
scalarized_value = ToQUBO.source_objective_value(model; result = 1)Compilation Information
ToQUBO.jl provides attributes to inspect the compilation process:
using MathOptInterface as MOI
using ToQUBO: AttributesCompilation Time
Get the time spent converting your model to QUBO form:
comp_time = MOI.get(model, Attributes.CompilationTime())Compilation Status
Check the status of the compilation:
comp_status = MOI.get(model, Attributes.CompilationStatus())Source and Target Models
Access the intermediate models created during compilation:
# Original model (with MOI bridges applied)
source = MOI.get(model, Attributes.SourceModel())
# QUBO formulation
target = MOI.get(model, Attributes.TargetModel())Formulation Introspection
Advanced users can inspect the pseudo-boolean functions generated by the compiler:
# Parsed source objective, before penalties are added
f = MOI.get(model, Attributes.CompiledObjectiveFunction())
# Final compiled Hamiltonian, after penalties and quadratization
H = MOI.get(model, Attributes.CompiledHamiltonian())
# Target QUBO variables and expansion for a source variable
y = MOI.get(model, Attributes.VariableTargetVariables(), variable_ref)
xi = MOI.get(model, Attributes.VariableEncodingFunction(), variable_ref)
# Penalty function for a source constraint, before multiplying by rho
g = MOI.get(model, Attributes.ConstraintEncodingFunction(), constraint_ref)
# Slack-variable information generated for an inequality constraint, if any
z = MOI.get(model, Attributes.SlackVariableTargetVariables(), constraint_ref)
zeta = MOI.get(model, Attributes.SlackVariableEncodingFunction(), constraint_ref)Reformulation Metadata
ToQUBO records JSON-compatible reformulation metadata for downstream tools that need to interpret full QUBO states. The metadata uses string-keyed dictionaries, arrays, primitive values, and finite numeric values. It is available directly from the optimizer. QUBOTools.backend does not attach the full metadata payload by default, so public QUBO extraction can avoid materializing large JSON-compatible term dictionaries. Opt in with full_metadata = true when the returned QUBOTools model needs embedded metadata under metadata["toqubo"]["reformulation"].
using ToQUBO: QUBOTools
metadata = ToQUBO.reformulation_metadata(JuMP.unsafe_backend(model))
qubo_model = QUBOTools.backend(model; full_metadata = true)
metadata = ToQUBO.reformulation_metadata(qubo_model)
original = ToQUBO.original_variables(metadata)
auxiliary = ToQUBO.auxiliary_variables(metadata)
qubo_state = [0, 1, 0, 1]
source_state = ToQUBO.project_original_state(metadata, qubo_state)The metadata guarantees the original source variable order, target QUBO variable order, source-to-target expansion_variables and expansion_terms, constraint/slack ownership for generated target variables, penalty terms recorded by the compiler, and an applied_penalties section with the applied constraint, variable-encoding, and slack-variable penalty coefficients. applied_penalties is a convenience view of values also stored on the corresponding metadata records. Slack-variable penalty entries are keyed by the source constraint that generated the slack variable. This is enough to project a full QUBO state back to original variables. Exact auxiliary consistency checks and repair remain encoding-specific and are not guaranteed by this metadata contract.
Full reformulation metadata is intentionally generated on request. Dense models can create one metadata record per source-to-target expansion term and per constraint-encoding term, so the JSON-compatible payload may allocate gigabytes on large TSP-style formulations. Use the default QUBOTools.backend(model) path when you only need the compiled QUBO, and use QUBOTools.backend(model; full_metadata = true) or ToQUBO.reformulation_metadata(JuMP.unsafe_backend(model)) when you need projection and interpretation metadata.
ToQUBO.reformulation_metadata — Function
reformulation_metadata(model_or_metadata)Return JSON-compatible ToQUBO reformulation metadata. For a live ToQUBO.Optimizer, the metadata is generated from the compiled virtual model. For a QUBOTools.AbstractModel or a metadata dictionary, the metadata is read from metadata["toqubo"]["reformulation"]. QUBOTools.backend skips this full metadata payload by default; call QUBOTools.backend(model; full_metadata = true) when a returned QUBOTools model needs embedded reformulation metadata.
The applied_penalties section is a convenience view. Its entries duplicate the applied penalty coefficients also attached to the corresponding variable, constraint, and slack-variable metadata records. Slack-variable penalties are keyed by the source constraint that generated the slack variable.
ToQUBO.original_variables — Function
original_variables(model_or_metadata)Return the original source variable identities in compiler order.
For a live ToQUBO.Optimizer, the result is a vector of MOI.VariableIndex values. For serialized metadata or a QUBOTools.AbstractModel, the result is a vector of integer variable ids.
ToQUBO.auxiliary_variables — Function
auxiliary_variables(model_or_metadata)Return target QUBO variables that are not owned by original source variables.
For a live ToQUBO.Optimizer, the result is a vector of MOI.VariableIndex values. For serialized metadata or a QUBOTools.AbstractModel, the result is a vector of integer target variable ids.
ToQUBO.project_original_state — Function
project_original_state(model_or_metadata, qubo_state)Project a full QUBO state onto the original source variables using the stored encoding expansions.
qubo_state may be a vector indexed by target QUBO variable id, or a dictionary keyed by integer target ids, string target ids, or MOI.VariableIndex values. For a live ToQUBO.Optimizer, the result is keyed by MOI.VariableIndex. For serialized metadata or a QUBOTools.AbstractModel, the result is keyed by integer source variable ids.
ToQUBO.qubo — Function
qubo(model, args...; kwargs...)Return the compiled QUBO representation for a model supported by QUBOTools.
This is a thin public ToQUBO re-export of QUBOTools.qubo. For a JuMP model using ToQUBO.Optimizer, call optimize! first, then pass the JuMP.Model directly.
ToQUBO.ConstraintViolation — Type
ConstraintViolationA measured source-constraint residual for one sampled result.
constraint is the source MOI.ConstraintIndex, function_type and set_type identify the constraint family, value is the original constraint function evaluated on the projected source-variable values, raw_residual is the set-specific residual before applying tolerances, violation is the nonnegative distance to the set, variable_values contains the projected values for variables referenced by the constraint function, and soft indicates whether the constraint was marked with Attributes.SoftConstraint.
ToQUBO.FeasibilityResult — Type
FeasibilityResultSummary of source-constraint feasibility for one sampled result.
feasible, violation_count, max_violation, total_violation, and by_constraint_type summarize hard source constraints (soft == false). soft_violation_count, soft_max_violation, soft_total_violation, and soft_by_constraint_type summarize constraints marked with Attributes.SoftConstraint.
ToQUBO.FeasibilityReport — Type
FeasibilityReportPer-result source-constraint feasibility summary returned by feasibility_report.
feasible_count, max_violation, and total_violation summarize hard source constraints across the selected results, while soft_violation_count, soft_max_violation, and soft_total_violation summarize constraints marked with Attributes.SoftConstraint.
ToQUBO.violations — Function
violations(model; result::Int = 1, atol::Real = _FEASIBILITY_ATOL, include_soft::Bool = true)Return source constraints violated by sampled result result.
The sampled QUBO result is projected back to the original source variables using the compiler's virtual mapping, then each source constraint is evaluated and measured against its MOI set. Scalar sets use MOI.Utilities.distance_to_set. Indicator constraints are considered violated only when their activation value triggers the inner set; SOS1 constraints use the distance to the nearest one-nonzero vector under the $\ell_1$ projection convention.
Violated constraints marked with Attributes.SoftConstraint have measurement.soft == true and are included by default (include_soft = true). Pass include_soft = false to return only hard-constraint violations.
ToQUBO.is_feasible — Function
is_feasible(model; result::Int = 1, atol::Real = _FEASIBILITY_ATOL)Return true if every hard source constraint (those not marked with Attributes.SoftConstraint) is satisfied by sampled result result within absolute tolerance atol.
ToQUBO.feasibility_report — Function
feasibility_report(model; result = nothing, atol::Real = _FEASIBILITY_ATOL)Return a FeasibilityReport summarizing source-constraint feasibility.
If result is nothing, all available solver results are summarized. Pass an integer or iterable of result indices to summarize selected samples.
ToQUBO.source_objective_value — Function
source_objective_value(model; result::Integer = 1)
source_objective_value(model, objective_index::Integer; result::Integer = 1)Return the source-model objective function evaluated at the projected source-variable values of sampled result result.
When objective_index is omitted, returns the scalar (or scalarized) penalty-free source objective value. When objective_index is provided, returns the unweighted value of the objective_index-th objective component.
Unlike objective_value/MOI.ObjectiveValue, which report the target QUBO energy including penalty terms introduced by the reformulation, this value is penalty-free: it is the original objective at the decoded solution.
ToQUBO.source_objective_values — Function
source_objective_values(model; result::Integer = 1)Return the vector of unweighted component source-objective values on sampled result result, evaluated by applying each compiled component pseudo-boolean function to the sampled target state.
ToQUBO.Attributes.CompilationTime — Type
CompilationTime()ToQUBO.Attributes.CompilationStatus — Type
CompilationStatus()ToQUBO.Attributes.SourceModel — Type
SourceModel()ToQUBO.Attributes.TargetModel — Type
TargetModel()ToQUBO.Attributes.CompiledObjectiveFunction — Type
CompiledObjectiveFunction()Return the pseudo-boolean objective parsed from the source model, before penalty terms are added.
ToQUBO.Attributes.CompiledObjectiveFunctions — Type
CompiledObjectiveFunctions()Return the vector of pseudo-boolean component objectives parsed from the source model in their original unweighted, un-flipped form, before scalarization and penalty terms are added.
For a scalar source objective, the returned vector has length 1 after compilation. For a vector source objective, the returned vector has one entry per objective component.
ToQUBO.Attributes.CompiledHamiltonian — Type
CompiledHamiltonian()Return the final pseudo-boolean function written to the target QUBO model, after penalties and quadratization are applied.
ToQUBO.Attributes.VariableTargetVariables — Type
VariableTargetVariables()Return the target QUBO variables generated for a source variable.
ToQUBO.Attributes.VariableEncodingFunction — Type
VariableEncodingFunction()Return the pseudo-boolean expansion used to represent a source variable in terms of target QUBO variables.
ToQUBO.Attributes.VariableEncodingPenaltyFunction — Type
VariableEncodingPenaltyFunction()Return the pseudo-boolean penalty function generated by a variable encoding, if that encoding requires one.
ToQUBO.Attributes.ConstraintEncodingFunction — Type
ConstraintEncodingFunction()Return the pseudo-boolean penalty function generated for a source constraint, before multiplying by its penalty coefficient.
ToQUBO.Attributes.AppliedPenalty — Type
AppliedPenalty()Return the applied source-constraint penalty coefficient after compilation.
This is an alias for ConstraintEncodingPenalty intended for reporting code that wants a generic "applied penalty" query.
ToQUBO.Attributes.SlackVariableTargetVariables — Type
SlackVariableTargetVariables()Return the target QUBO variables generated for a constraint slack variable.
ToQUBO.Attributes.SlackVariableEncodingFunction — Type
SlackVariableEncodingFunction()Return the pseudo-boolean expansion used to represent a constraint slack variable in terms of target QUBO variables.
ToQUBO.Attributes.SlackVariableEncodingPenaltyFunction — Type
SlackVariableEncodingPenaltyFunction()Return the pseudo-boolean penalty function generated by a slack-variable encoding, if that encoding requires one.
Penalty Information
Constraints are converted to penalty terms in QUBO. You can retrieve the penalty coefficients used:
Constraint Penalties
# Get the penalty used for a specific constraint
rho = MOI.get(model, Attributes.ConstraintEncodingPenalty(), constraint_ref)
# Equivalent reporting-oriented alias
rho = MOI.get(model, Attributes.AppliedPenalty(), constraint_ref)Variable Encoding Penalties
For encoded variables:
# Get the penalty used for variable encoding
theta = MOI.get(model, Attributes.VariableEncodingPenalty(), variable_ref)Example: Complete Results Retrieval
using JuMP
using ToQUBO
using QUBODrivers # Provides ExactSampler and other solvers
# Create and solve a model
model = Model(() -> ToQUBO.Optimizer(ExactSampler.Optimizer))
@variable(model, x[1:3], Bin)
@constraint(model, c1, x[1] + x[2] <= 1)
@objective(model, Max, x[1] + 2*x[2] + 3*x[3])
optimize!(model)
# Check status
println("Termination: ", termination_status(model))
println("Primal: ", primal_status(model))
# Get best solution
if primal_status(model) == FEASIBLE_POINT
println("Best solution: ", value.(x))
println("Best objective: ", objective_value(model))
end
# Iterate over all solutions
println("\nAll solutions:")
for i in 1:result_count(model)
println(" Solution $i: x = $(value.(x, result = i)), obj = $(objective_value(model, result = i))")
endTermination: OPTIMAL
Primal: FEASIBLE_POINT
Best solution: [0.0, 1.0, 1.0]
Best objective: 5.0
All solutions:
Solution 1: x = [0.0, 1.0, 1.0], obj = 5.0
Solution 2: x = [1.0, 0.0, 1.0], obj = 4.0
Solution 3: x = [0.0, 0.0, 1.0], obj = 3.0
Solution 4: x = [0.0, 1.0, 0.0], obj = 2.0
Solution 5: x = [1.0, 0.0, 0.0], obj = 1.0
Solution 6: x = [0.0, 0.0, 0.0], obj = -0.0
Solution 7: x = [1.0, 1.0, 1.0], obj = -1.0
Solution 8: x = [0.0, 1.0, 1.0], obj = -2.0
Solution 9: x = [1.0, 0.0, 1.0], obj = -3.0
Solution 10: x = [1.0, 1.0, 0.0], obj = -4.0
Solution 11: x = [0.0, 0.0, 1.0], obj = -4.0
Solution 12: x = [0.0, 1.0, 0.0], obj = -5.0
Solution 13: x = [1.0, 0.0, 0.0], obj = -6.0
Solution 14: x = [0.0, 0.0, 0.0], obj = -7.0
Solution 15: x = [1.0, 1.0, 1.0], obj = -22.0
Solution 16: x = [1.0, 1.0, 0.0], obj = -25.0Working with QUBOTools
ToQUBO.jl integrates with QUBOTools.jl for advanced QUBO manipulation. You can extract the compiled QUBO from a JuMP model after optimize!:
using JuMP
using ToQUBO
using ToQUBO: QUBOTools
model = Model(ToQUBO.Optimizer)
@variable(model, x[1:2], Bin)
@constraint(model, x[1] + x[2] <= 1)
@objective(model, Min, x[1] - 2x[2])
optimize!(model)
qubo_model = QUBOTools.backend(model)
n, linear, quadratic, scale, offset = ToQUBO.qubo(model, :dense)This allows you to:
- Export the QUBO to various file formats
- Analyze the QUBO structure
- Use additional QUBOTools functionality
Next Steps
- Learn about Compiler Settings to customize the reformulation
- Explore Examples in QUBO.jl for end-to-end application guides