Subset Sum Example
The Subset Sum problem asks whether a subset of integers sums to a specified target. It is NP-complete and one of the fundamental problems in cryptography and computational complexity.
import getpass
import os
from dotenv import load_dotenv
from luna_quantum.algorithms import SCIP
from luna_usecases.subset_sum import (
SubsetSumCollection,
SubsetSumData,
SubsetSumFormulation,
SubsetSumInstance,
)
load_dotenv()
if "LUNA_API_KEY" not in os.environ:
os.environ["LUNA_API_KEY"] = getpass.getpass("Enter your Luna API key: ")
Create Data
Define 6 integers and a target sum of 14.
Alternatively, generate a random set with a feasible target
data = SubsetSumData(numbers=[3, 7, 1, 8, 5, 2], target=14)
data = SubsetSumData.generate_random(6)
print(data.to_string())
Plot Data
Visualize the numbers and target.
Create Formulation
Find a subset of numbers that sums exactly to the target.
Subset Sum Formulation:
Numbers: 6
Target: 27
Decision Variables:
x[i] in {0,1} for i = 0, ..., 5
x[i] = 1 if number i is selected
Total: 6 binary variables
Objective:
minimize 0 (feasibility problem)
Constraints:
1. Sum equals target (1 constraint):
sum_i numbers[i] * x[i] == 27
Create Instance
Combine data and formulation into a solvable instance.
Data:Subset Sum Problem:
Numbers: [ 6 10 2 5 8 3]
Target: 27
Total sum: 34
Number count: 6
Formulation:Subset Sum Formulation:
Numbers: 6
Target: 27
Decision Variables:
x[i] in {0,1} for i = 0, ..., 5
x[i] = 1 if number i is selected
Total: 6 binary variables
Objective:
minimize 0 (feasibility problem)
Constraints:
1. Sum equals target (1 constraint):
sum_i numbers[i] * x[i] == 27
Formulate Model
Translate the instance into a mathematical optimization model.
Solve and Interpret
Solve the model with SCIP and interpret the raw result into a use-case-specific solution.
scip = SCIP()
job = scip.run(model)
sol = job.result()
uc_solution = instance.interpret(sol)
print(uc_solution.to_string())
/Users/maximilianjanetschek/PycharmProjects/luna-usecases/.venv/lib/python3.13/site-packages/rich/live.py:260:
UserWarning: install "ipywidgets" for Jupyter support
warnings.warn('install "ipywidgets" for Jupyter support')
Subset Sum Solution:
Selected indices: [0 1 4 5]
Selected sum: 27
Difference from target: 0
Valid (sum == target): True
Plot Solution
Visualize the optimal solution.
Collections
Generate a benchmark collection of random instances for batch processing.
collection = SubsetSumCollection.from_random(
min_n_numbers=5,
max_n_numbers=8,
seed=42,
)
model = collection.instances[0].formulate()
print(model)