HLPL / VerTeX Modelling Language Documentation

← lessons

A constraint over a set

Σ in your constraints, not just the objective.

Chapter: III — Sets and sums · lesson id sum-constraint · practice lesson


sum_{i in I}{expr} is the modelling language's big-Σ. You've seen it in the objective; here we put it in a constraint too — a budget cap on total weight.

Items have values v_i and weights w_i. You have W units of capacity. Pick the most valuable subset that fits. (Yes — this is already a knapsack. We'll formalise it in its own chapter.)

Predict before running

Items have values {3,5,2,7,4} and weights {2,4,1,5,3} with budget W = 8. What's the best value?

Starter code

model picks
set I = {1, 2, 3, 4, 5}
const v = {3, 5, 2, 7, 4}, forall i in I
const w = {2, 4, 1, 5, 3}, forall i in I
const W = 8
var 0 <= x <= 1, forall i in I
constr sum_{i in I}{w_{i} * x_{i}} <= W
max sum_{i in I}{v_{i} * x_{i}}
end

import elytica
def main():
  elytica.init_model("picks")
  elytica.run_model("picks")
  for i in [1,2,3,4,5]:
    print("x"+str(i), "=", elytica.get_variable_value("picks", "x"+str(i)))
  print("obj =", elytica.get_best_primal_bound("picks"))
  return 0

Hint

No code changes. Look at the budget — it forces the solver to drop items.

What counts as correct

Mastery variant

Different values, weights, and a tighter budget. Which subset wins?

model picks_v
set I = {1, 2, 3, 4, 5}
const v = {4, 2, 6, 3, 5}, forall i in I
const w = {2, 1, 3, 2, 2}, forall i in I
const W = 6
var 0 <= x <= 1, forall i in I
constr sum_{i in I}{w_{i} * x_{i}} <= W
max sum_{i in I}{v_{i} * x_{i}}
end

import elytica
def main():
  elytica.init_model("picks_v")
  elytica.run_model("picks_v")
  for i in [1,2,3,4,5]:
    print("x"+str(i), "=", elytica.get_variable_value("picks_v", "x"+str(i)))
  print("obj =", elytica.get_best_primal_bound("picks_v"))
  return 0

Read this through MCP: read with path: "lessons/sum-constraint", or resource hlpl://lessons/sum-constraint.