vahvel
Linear and mixed-integer programming. Describe a model with plain Gleam data, keyed by your own types, and solve it with microlp, a pure-Rust solver, through a NIF.
A Model combines an Objective and Constraints, both built from
Expressions over your variable keys, with a Domain for each key.
solve returns an Outcome; read a Solution with value, or with
evaluate_solution for any expression used to build the model.
import vahvel.{Constant, Linear, Sum}
type Waffle {
Classic
Chocolate
}
let model =
vahvel.Model(
domain: fn(_) { vahvel.NonNegativeInteger },
objective: vahvel.Maximize(
Sum([Linear(3.0, Classic), Linear(5.0, Chocolate)]),
),
constraints: [
vahvel.LessEqual(
Sum([Linear(2.0, Classic), Linear(3.0, Chocolate)]),
Constant(13.0),
),
],
)
let assert Ok(vahvel.Optimal(solution, _)) = vahvel.solve(model)
vahvel.objective(solution) // 21.0
vahvel.value(solution, Chocolate) // Ok(3.0)
The API is unstable while the package is 0.x.
Types
A linear relation between two expressions. Constraints have no names; a constraint value is its own identity.
pub type Constraint(v) {
LessEqual(lhs: Expression(v), rhs: Expression(v))
Equal(lhs: Expression(v), rhs: Expression(v))
GreaterEqual(lhs: Expression(v), rhs: Expression(v))
}
Constructors
-
LessEqual(lhs: Expression(v), rhs: Expression(v))lhs ≤ rhs. -
Equal(lhs: Expression(v), rhs: Expression(v))lhs = rhs. -
GreaterEqual(lhs: Expression(v), rhs: Expression(v))lhs ≥ rhs.
The values a variable may take. None means no bound on that side. Bounds
are inclusive; Binary is shorthand for Integer(Some(0), Some(1)).
A lower bound above the upper bound is an empty domain, so the model is
infeasible.
The current backend limits integer variables to the signed 32-bit range:
explicit integer bounds must fit it, and a None integer bound stops at its
edge. A solution value of −2³¹ or 2³¹ − 1 therefore means that limit was reached.
pub type Domain {
Binary
Real(lower: option.Option(Float), upper: option.Option(Float))
Integer(lower: option.Option(Int), upper: option.Option(Int))
NonNegativeReal
NonNegativeInteger
}
Constructors
-
BinaryAn integer variable restricted to zero or one.
-
Real(lower: option.Option(Float), upper: option.Option(Float))A real-valued variable with optional inclusive bounds.
-
Integer(lower: option.Option(Int), upper: option.Option(Int))An integer-valued variable with optional inclusive bounds.
-
NonNegativeRealA real-valued variable at least zero:
Real(Some(0.0), None). -
NonNegativeIntegerAn integer-valued variable at least zero:
Integer(Some(0), None).
Why an expression could not be evaluated.
pub type EvaluationError(v) {
MissingValue(v)
NonFiniteValue
}
Constructors
-
MissingValue(v)The lookup supplied no value for this variable, which the expression references.
-
NonFiniteValueThe result is not finite: a product or sum overflowed.
An affine expression over variable keys. Duplicate variables and zero coefficients are allowed, and expressions nest to any depth.
Sum([Linear(3.0, X), Linear(2.0, Y), Constant(7.0)]) // 3x + 2y + 7
Difference(revenue, cost) // revenue − cost
list.map(items, fn(i) { Linear(i.weight, Pick(i.id)) }) |> Sum // Σ wᵢ pickᵢ
For shorter literals, rename the constructors at the import:
import vahvel.{Linear as L, Constant as C}.
pub type Expression(v) {
Variable(variable: v)
Linear(coefficient: Float, variable: v)
Constant(value: Float)
Sum(expressions: List(Expression(v)))
Difference(lhs: Expression(v), rhs: Expression(v))
Scaled(coefficient: Float, expression: Expression(v))
}
Constructors
-
Variable(variable: v)A variable with coefficient one, equivalent to
Linear(1.0, variable). -
Linear(coefficient: Float, variable: v)A variable times a coefficient, written coefficient first as in
3x. -
Constant(value: Float)A number that references no variable.
-
Sum(expressions: List(Expression(v)))The sum of the expressions; the empty sum is zero.
-
Difference(lhs: Expression(v), rhs: Expression(v))lhsminusrhs, equivalent toSum([lhs, Scaled(-1.0, rhs)]). Both sides still reference their variables even when they cancel. -
Scaled(coefficient: Float, expression: Expression(v))Scale an expression, including its constants. Scaling by zero still references the expression’s variables.
Per-call solver budgets. None means unlimited; zero is valid.
pub type Limits {
Limits(
time: option.Option(duration.Duration),
nodes: option.Option(Int),
)
}
Constructors
-
Limits( time: option.Option(duration.Duration), nodes: option.Option(Int), )Arguments
- time
-
Time for the backend solve only; it may be exceeded between checks.
- nodes
-
Branch-and-bound nodes, excluding the root relaxation. Continuous LP work is not limited.
Where in a model an error occurred.
pub type Location(v) {
InObjective
InConstraint(index: Int, constraint: Constraint(v))
}
Constructors
-
InObjectiveThe objective expression.
-
InConstraint(index: Int, constraint: Constraint(v))The constraint, and its zero-based position in
Model.constraints.
A model to solve. A variable exists once an expression references it, and
domain gives its allowed values. The same key may be reused in different
models.
pub type Model(v) {
Model(
domain: fn(v) -> Domain,
objective: Objective(v),
constraints: List(Constraint(v)),
)
}
Constructors
-
Model( domain: fn(v) -> Domain, objective: Objective(v), constraints: List(Constraint(v)), )Arguments
- domain
-
The allowed values of each variable. It is called only for keys the objective or constraints reference, so a
caseover the keys a model uses is enough. - objective
-
The expression to optimize and its direction.
- constraints
-
The relations every solution must satisfy, within the solver’s tolerance.
The expression to optimize, with its direction.
pub type Objective(v) {
Minimize(Expression(v))
Maximize(Expression(v))
}
Constructors
-
Minimize(Expression(v))Find the smallest value of the expression.
-
Maximize(Expression(v))Find the largest value of the expression.
A proof or a budget stop.
pub type Outcome(v) {
Optimal(solution: Solution(v), stats: Stats)
Limited(
reason: StopReason,
solution: option.Option(Solution(v)),
stats: Stats,
)
Infeasible
Unbounded
}
Constructors
-
The solver proved this solution optimal, within its tolerance.
-
Limited( reason: StopReason, solution: option.Option(Solution(v)), stats: Stats, )A budget in
Limitsstopped search before a proof. The solution, if any, is feasible but unproven;Nonemeans no usable assignment was returned, not infeasibility. -
InfeasibleNo assignment satisfies the constraints and domains, including when a domain is empty or a constraint over constants is false.
-
UnboundedThe objective improves without limit. An unbounded integer direction is instead
Optimalat the backend’s integer limit; seeDomain.
A usable assignment from one solve. The enclosing outcome carries proof status and statistics; a solution alone is not a claim of optimality.
pub opaque type Solution(v)
Why a model could not be solved. Infeasibility and unboundedness are
answers, not errors; see Outcome.
pub type SolveError(v) {
InvalidDomain(v)
InvalidTimeLimit
InvalidNodeLimit
NonFinite(Location(v))
SolverFailure(String)
}
Constructors
-
InvalidDomain(v)This variable’s integer bounds do not fit the backend’s signed 32 bits.
-
InvalidTimeLimitLimits.timeis negative or longer than 100 years. -
InvalidNodeLimitLimits.nodesis negative or does not fit an unsigned 64-bit integer. -
NonFinite(Location(v))A product or sum of the model’s numbers overflowed.
-
SolverFailure(String)The solver failed numerically or internally. The message is for diagnostics only.
How much work the solver did and how far from proven its answer is. Models requiring no solver work report zero work and a zero gap.
pub type Stats {
Stats(
nodes: Int,
iterations: Int,
solve_time: duration.Duration,
gap: option.Option(Float),
)
}
Constructors
-
Stats( nodes: Int, iterations: Int, solve_time: duration.Duration, gap: option.Option(Float), )Arguments
- nodes
-
Branch-and-bound nodes solved; zero for a purely continuous model.
- iterations
-
Simplex iterations, including the root relaxation.
- solve_time
-
Time spent inside the backend solver, excluding lowering, decoding, canonicalization and problem construction.
- gap
-
Relative objective gap:
abs(objective - bound) / max(abs(objective), 1).Some(0.0)for an optimum;Nonewithout an incumbent or a finite gap. A zero gap alone does not prove optimality.
The budget that stopped search before a proof was obtained.
pub type StopReason {
TimeLimit
NodeLimit
}
Constructors
-
TimeLimitLimits.timeran out. -
NodeLimitLimits.nodesran out.
Values
pub fn evaluate(
expression: Expression(v),
lookup: fn(v) -> Result(Float, Nil),
) -> Result(Float, EvaluationError(v))
Evaluate an expression with the values lookup gives its variables, e.g. a
cost breakdown or the cost of a hand-made plan; residual evaluates a
constraint. Values need not satisfy any model.
Every referenced variable needs a value, even one that cancels or is scaled
by zero. The first variable without one, in depth-first order, is
MissingValue(key); unreferenced keys are never looked up.
vahvel.evaluate(profit, dict.get(plan, _))
vahvel.evaluate(profit, fn(key) {
case dict.get(overrides, key) {
Ok(value) -> Ok(value)
Error(Nil) -> vahvel.value(solution, key)
}
})
pub fn evaluate_dict(
expression: Expression(v),
values: dict.Dict(v, Float),
) -> Result(Float, EvaluationError(v))
Evaluate an expression at the values in a dictionary:
evaluate(expression, dict.get(values, _)).
pub fn evaluate_solution(
expression: Expression(v),
solution: Solution(v),
) -> Result(Float, EvaluationError(v))
Evaluate an expression at a solution’s values:
evaluate(expression, value(solution, _)).
pub fn objective(solution: Solution(v)) -> Float
A solution’s objective value, including constant terms, as reported by the
solver. It is not recomputed from the rounded integer values, so it can
differ from evaluate_solution of the objective expression in the last
digits.
pub fn residual(
constraint: Constraint(v),
lookup: fn(v) -> Result(Float, Nil),
) -> Result(Float, EvaluationError(v))
A constraint’s lhs − rhs at the values lookup gives its variables:
evaluate(Difference(lhs, rhs), lookup). It holds when the residual is at
most zero for LessEqual, zero for Equal and at least zero for
GreaterEqual; solver results meet that only within the solver’s tolerance.
list.map(constraints, fn(c) { #(c, vahvel.residual(c, lookup)) })
pub fn solve(
model: Model(v),
) -> Result(Outcome(v), SolveError(v))
Solve without time or node limits. The outcome is Optimal, Infeasible
or Unbounded, never Limited.
pub fn solve_with(
model: Model(v),
limits: Limits,
) -> Result(Outcome(v), SolveError(v))
Solve with per-call budgets. Limits are validated before the model; validation and trivial proofs still run with zero budgets. Model lowering, validation, construction and NIF overhead are outside the time budget.
pub fn stats(outcome: Outcome(v)) -> option.Option(Stats)
Statistics of this solve. Infeasible and unbounded answers have none because the backend does not return statistics for those proofs.
pub fn value(solution: Solution(v), key: v) -> Result(Float, Nil)
Look up a primal value by variable key, like dict.get. A key that no
expression references is Error(Nil), never zero. Integer and binary
variables have exact whole values, so float.round converts them without
loss.