Built-in Features
VarNumberFeature
Bases: BaseFeature[VarNumberFeatureResult]
Fake feature class.
run(model: Model) -> VarNumberFeatureResult
Fake feature which will return a random number.
Parameters:
-
model(Model) –The model for which the feature should be calculated
OptSolFeature
Bases: BaseModelLookupFeature[OptSolFeatureResult, OptSolFeatureResult]
Feature that computes the optimal (or best feasible) solution for optimization models.
This feature translates a Luna-Model to LP format and solves it using the SCIP mixed-integer programming solver. It can be configured with a maximum runtime to obtain upper bounds for computationally expensive problems.
Solving is expensive, and for many benchmark instances the optimal solution is
already known (e.g. shipped alongside the model), so re-solving is wasteful.
Register those known values as OptSolFeatureResult records with
:meth:~luna_bench.custom.BaseModelLookupFeature.add_model /
:meth:~luna_bench.custom.BaseModelLookupFeature.add_models, and the feature serves
them directly instead of solving. A model with no registered value is solved as
usual, so an unpopulated feature behaves exactly as it always has.
The mapping is keyed by hash(model), which covers the model's name as well as
its contents and survives the encode()/decode() round-trip a benchmark
performs before running features. Populate it before handing the feature to
Benchmark.add_feature(): the benchmark serializes the feature's configuration at
that point, so entries added afterwards never reach the run. Use
:meth:~luna_bench.custom.BaseModelLookupFeature.covers to check a modelset up front
rather than discovering gaps as unexpected solves mid-run.
Attributes:
-
max_runtime((float | None, optional)) –Maximum solver runtime in seconds. If None (default), the solver runs until optimality is proven or infeasibility is detected. If set, the solver may return a suboptimal solution marked with pre_terminated=True. Ignored for a model whose value is precomputed.
-
quiet_output(bool) –Defines the verbosity of the SCIP solver output. Ignored for a model whose value is precomputed.
-
mapping(dict[int, OptSolFeatureResult]) –Inherited.
hash(model)to precomputed result; populate it withadd_model/add_modelsrather than by hand.
Raises:
-
InfeasibleModelError–If the model has no precomputed value and the solver proves it infeasible.
Requires
Install the 'pre-defined' extra: pip install luna-bench[pre-defined]
(only needed for models that have to be solved).
Examples:
>>> # Solve to optimality (no time limit)
>>> feature = OptSolFeature()
>>> result = feature.run(model)
>>> print(f"Optimal value: {result.global_best_sol}")
>>> # Get best solution within 60 seconds
>>> feature = OptSolFeature(max_runtime=60)
>>> result = feature.run(model)
>>> if result.pre_terminated:
... print(f"Upper bound: {result.global_best_sol}")
... else:
... print(f"Optimal value: {result.global_best_sol}")
>>> # Reuse a known optimum, skipping the solver
>>> feature = OptSolFeature()
>>> feature.add_model(model, OptSolFeatureResult(global_best_sol=42.0))
>>> feature.run(model).global_best_sol
42.0
>>> # A known solution rather than a bare number
>>> feature.add_model(other, OptSolFeatureResult.from_solution(solution, pre_terminated=False))
>>> # Register a whole collection at once, then check for gaps up front
>>> feature = OptSolFeature()
>>> feature.add_models(collection.get_precomp_solutions())
>>> unsolved = [m for m in modelset.models if not feature.covers(m)]
to_result(value: OptSolFeatureResult, model: Model) -> OptSolFeatureResult
Report a registered value as this run's feature result.
A registered value is already an OptSolFeatureResult, so it only has to be
handed back. It is copied rather than returned as-is, so that a consumer holding
the result cannot reach back into the mapping and change what later runs see.
Parameters:
-
value(OptSolFeatureResult) –The result registered for
model. -
model(Model) –The model the value was looked up for. Unused - the value carries everything the result needs.
Returns:
-
OptSolFeatureResult–A copy of the registered value.
on_miss(model: Model) -> OptSolFeatureResult
Calculate the optimal solution for the given model, or at least get an upper bound.
Called for any model without a precomputed value, which is every model unless the mapping has been populated. Overrides the base's raising behaviour: a missing entry is not an error here, just the expensive path.
This method performs the following steps: 1. Translates the Luna Quantum model to LP format via a temporary file 2. Reads the LP file into a SCIP solver instance 3. Configures the time limit (if specified) 4. Solves the optimization problem 5. Returns the best objective value and termination status
Parameters:
-
model(Model) –The model for which the feature should be calculated
Returns:
-
OptSolFeatureResult–Contains the best objective value found and whether the solver terminated early due to time limit.
Notes
- For large or difficult problems, consider setting max_runtime to avoid excessive computation time
- When pre_terminated is True, the returned best_sol is an upper bound (for minimization) or lower bound (for maximization) on the optimal value
run(model: Model) -> TFeatureResult
Return the registered value for model.
Parameters:
-
model(Model) –The model to look up.
Returns:
-
TFeatureResult–The registered value, wrapped by
to_result.
Raises:
-
ModelLookupMissError–If the model has no entry and
on_missis not overridden.
add_model(model: Model, value: TValue) -> None
Register value for model, replacing any existing entry.
Parameters:
-
model(Model) –The model to assign a value to.
-
value(TValue) –The value to serve whenever this model is seen.
add_models(entries: Mapping[Model, TValue] | Iterable[tuple[Model, TValue]]) -> None
covers(model: Model) -> bool
Return whether model has an entry, without running the feature.
Useful for validating a mapping against a modelset up front instead of discovering gaps as failed feature results mid-run.
Parameters:
-
model(Model) –The model to check.
Returns:
-
bool–True if the model has an entry in the mapping.
MIP Features
ProblemSizeFeatures
Bases: BaseFeature[ProblemSizeFeaturesResult]
Feature extractor for problem size-related characteristics.
Extracts features related to the number and types of variables, constraints, and the sparsity of constraint matrices. Includes both absolute counts and fractional values, as well as statistical metrics related to variable support sizes.
run(model: Model) -> ProblemSizeFeaturesResult
Calculate problem size features for the given optimization model.
Computes various metrics including variable counts by type, constraint counts, matrix sparsity measures, and support size statistics for bounded variables.
Parameters:
-
model(Model) –The optimization model for which the features should be calculated.
Returns:
-
ProblemSizeFeaturesResult–Container with problem size metrics.
LinearConstraintMatrixFeatures
Bases: BaseFeature[LinearConstraintMatrixFeaturesResult]
Feature extractor for linear constraint matrix properties.
Extracts statistical features related to variable coefficients, constraint coefficients, and the distribution of constraint matrix entries. Includes both continuous and non-continuous features, as well as normalized and variation coefficient metrics.
run(model: Model) -> LinearConstraintMatrixFeaturesResult
Calculate linear constraint matrix features.
Computes various statistics for the constraint matrix including coefficient sums, normalized entries, and variation coefficients, grouped by variable type.
Parameters:
-
model(Model) –The optimization model for which the features should be calculated.
Returns:
-
LinearConstraintMatrixFeaturesResult–Container with constraint matrix statistical measures.
ObjectiveFunctionFeature
Bases: BaseFeature[ObjectiveFunctionFeatureResult]
Feature extractor for objective function coefficient statistics.
Extracts statistical features (mean, std) of objective function coefficients for continuous, non-continuous, and all variable types. Includes raw absolute values as well as normalized and square-root-normalized versions.
run(model: Model) -> ObjectiveFunctionFeatureResult
Calculate statistical features of objective function coefficients.
Computes mean and standard deviation of absolute objective function coefficients for continuous, non-continuous, and all variable types. Also calculates these statistics for normalized and square-root-normalized coefficient values.
Parameters:
-
model(Model) –The optimization model for which the features should be calculated.
Returns:
-
ObjectiveFunctionFeatureResult–Container with statistical measures of objective function coefficients.
RightHandSideFeatures
Bases: BaseFeature[RightHandSideFeaturesResult]
Feature extractor for right-hand side values of constraints.
Extracts statistical features (mean and standard deviation) for the RHS values of different constraint types: less-than-or-equal (<=), equality (==), and greater-than-or-equal (>=) constraints.
run(model: Model) -> RightHandSideFeaturesResult
Calculate right-hand side statistical features for constraints.
Computes mean and standard deviation of RHS values grouped by constraint sense (<=, ==, >=).
Parameters:
-
model(Model) –The optimization model for which the features should be calculated.
Returns:
-
RightHandSideFeaturesResult–Container with RHS statistical measures for each constraint type.
VariableConstraintGraphFeatures
Bases: BaseFeature[VariableConstraintGraphFeaturesResult]
Feature extractor for variable-constraint graph properties.
Calculates node degree statistics for variables and constraints in the bipartite graph representation of an optimization model. Computes statistics separately for continuous and non-continuous variables/constraints.
run(model: Model) -> VariableConstraintGraphFeaturesResult
Calculate variable-constraint graph features.
Computes node degree statistics (mean, median, variation coefficient, and quantiles) for variables and constraints, grouped by variable type.
Parameters:
-
model(Model) –The optimization model for which the features should be calculated.
Returns:
-
VariableConstraintGraphFeaturesResult–Container with graph-based statistical measures.
QUBO Features
QuboGraphFeature
Bases: BaseFeature[QuboGraphFeatureResult]
Extract graph-based features from QUBO models.
Compute graph-theoretic features from the QUBO matrix by constructing a
weighted graph via networkx.from_numpy_array and analysing its topology.
Extracted features include:
- Connectivity: Average degree distribution, average clustering coefficient, number of connected components, and average path length.
- Robustness: Graph density, number of bridges, and number of articulation points.
Attributes:
-
include_self_loops(bool) –Whether to include diagonal elements (self-loops) in the graph analysis. If False (default), diagonal entries are zeroed out before constructing the graph, analyzing only variable interactions. If True, linear terms are included as self-loops, which affects degree calculations and other metrics.
Requires
Install the 'pre-defined' extra: pip install luna-bench[pre-defined]
run(model: Model) -> QuboGraphFeatureResult
Compute graph-based features for the given model.
Parameters:
-
model(Model) –The optimization model to extract features from.
Returns:
-
QuboGraphFeatureResult–A result object containing the computed graph features.
QuboMatrixFeature
Bases: BaseFeature[QuboMatrixFeatureResult]
Extract statistical matrix features from QUBO models.
Compute descriptive statistics over all entries of the QUBO matrix.
Extracted features include:
- Central tendency / dispersion: Mean, median, variance, standard deviation, minimum, and maximum.
- Shape: Skewness and kurtosis of the flattened matrix.
- Quantiles: 10th and 90th percentiles (q10, q90) and the variation coefficient (vc).
run(model: Model) -> QuboMatrixFeatureResult
Compute matrix statistical features for the given model.
Parameters:
-
model(Model) –The optimization model to extract features from.
Returns:
-
QuboMatrixFeatureResult–A result object containing the computed matrix statistics.
QuboSparsityDensityFeature
Bases: BaseFeature[QuboSparsityDensityFeatureResult]
Extract sparsity and density features from QUBO models.
Compute structural features describing the fill pattern of the QUBO matrix.
Extracted features include:
- Ratios: Sparsity and density of the matrix.
- Counts: Number of zero and non-zero entries.
- Size: Number of variables (matrix dimension).
run(model: Model) -> QuboSparsityDensityFeatureResult
Compute sparsity and density features for the given model.
Parameters:
-
model(Model) –The optimization model to extract features from.
Returns:
-
QuboSparsityDensityFeatureResult–A result object containing the computed sparsity/density features.
QuboSpectralAnalysisFeature
Bases: BaseFeature[QuboSpectralAnalysisFeatureResult]
Extract spectral analysis features from QUBO models.
Decompose the QUBO matrix with numpy.linalg.eigh and compute
descriptive statistics over eigenvalues and eigenvectors.
Extracted features include:
- Eigenvalue statistics: Mean, median, std, variation coefficient, q10, q90, minimum, maximum, and dominant (largest absolute) eigenvalue.
- Eigenvector statistics: Same set of statistics computed over all eigenvector components.
- Condition number: Ratio of largest to smallest singular value, indicating numerical stability.
run(model: Model) -> QuboSpectralAnalysisFeatureResult
Compute spectral analysis features for the given model.
Parameters:
-
model(Model) –The optimization model to extract features from.
Returns:
-
QuboSpectralAnalysisFeatureResult–A result object containing the computed spectral features.