Yes-or-no decisions
Use integer programs when decisions come in whole units, and diagnose models that have no answer or no limit.
What runs in CodeSplash
- Linear and integer programming (LP / MILP) Verified in Python and R
You will be able to
- Say when you need integer variables, and why rounding can fail
- Solve a small knapsack, and read why a greedy rule misses the best answer
- Diagnose infeasible and unbounded models
Read first
You can't fund half a project
ReadLinear programs allow fractions. Many decisions don't: fund a project or not, open a warehouse or not, buy a whole number of machines.
An integer programInteger programA linear program whose decisions must be whole numbers or yes/no. Harder to solve, and shadow prices no longer apply. restricts some variables to whole numbers, or to 0 and 1. It's a harder problem, but small ones solve quickly.
Pick the projects
PredictPredict first
Three projects have a value and a weight: a (60, 10), b (100, 20), c (120, 30). There's also item d, worth 7, weighing 4, and you can take up to 3 of it. Your limit is 55. A common rule is to pick by value per weight: a, then b, then as many d as fit. Is that the best you can do?
Reveal
No. That rule gives a + b + three d: 60 + 100 + 21 = 181, using a weight of 42. The best plan skips a: b + c + one d gives 227, for a weight of 20 + 30 + 4 = 54. Choosing by ratio ignores how the items fit together.
See the solution
In the appOptimal objective 227.00 (maximized); 0 of 1 constraints binding.
- Objective
- 227
- Binding constraints
- 0
- MIP gap
- 0
Optimal decisions
| Variable | Optimal value | Objective coef. | Lower | Upper | Type |
|---|---|---|---|---|---|
| a | 0 | 60 | 0 | 1 | binary |
| b | 1 | 100 | 0 | 1 | binary |
| c | 1 | 120 | 0 | 1 | binary |
| d | 1 | 7 | 0 | 3 | integer |
Constraints
| Constraint | Activity | Right-hand side | Slack | Binding | |
|---|---|---|---|---|---|
| Weight | 54 | <= | 55 | 1 | no |
- Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear and integer programming (LP / MILP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method optimize.lp 1.0.0 · spec ad6c5ecc500f2fdb
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_opt_*: model -> arrays, HiGHS via highs::highs_solve, dual conventions (twin of codesplash.sim.lp)
# %% Model
model <- cs_opt_load("{\"sense\":\"max\",\"variables\":[{\"name\":\"a\",\"type\":\"binary\",\"objective\":60},{\"name\":\"b\",\"type\":\"binary\",\"objective\":100},{\"name\":\"c\",\"type\":\"binary\",\"objective\":120},{\"name\":\"d\",\"type\":\"integer\",\"lower\":0,\"upper\":3,\"objective\":7}],\"constraints\":[{\"name\":\"Weight\",\"coefs\":{\"a\":10,\"b\":20,\"c\":30,\"d\":4},\"sense\":\"<=\",\"rhs\":55}]}")
SWEEP <- "" # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES <- c()
SWEEP_LABEL <- ""
if (!nzchar(SWEEP_LABEL)) SWEEP_LABEL <- SWEEP
warnings <- list(); tables <- list(); charts <- list()
# %% Solve
# cs_opt_solve() builds c, A, lhs/rhs and bounds from the model and calls
# highs::highs_solve(L = c, lower, upper, A, lhs, rhs, types, maximum = ...).
res <- cs_opt_solve(model)
x <- res$x_data
nms <- x$names
cnames <- vapply(seq_along(model$constraints), function(i) {
n <- model$constraints[[i]]$name
if (is.null(n) || !nzchar(n)) sprintf("c%d", i) else as.character(n)
}, character(1))
status <- res$status
values <- list(
status = status, optimal = if (status == "optimal") 1 else 0, sense = res$sense,
objective = if (is.null(res$objective)) NA else res$objective, n_variables = length(nms), n_constraints = length(cnames),
n_integer = sum(x$integrality), n_binding = if (status == "optimal") sum(res$binding) else NA
)
fin <- function(v) if (is.finite(v)) v else NA
if (status == "optimal") {
var_rows <- lapply(seq_along(nms), function(j) {
row <- list(variable = nms[j], value = res$x[j], objective = x$c[j], lower = fin(x$lower[j]), upper = fin(x$upper[j]),
type = model$variables[[j]]$type %||% "continuous")
if (res$is_lp) row$reduced <- res$reduced[j]
row
})
for (j in seq_along(nms)) {
values[[sprintf("x[%s]", nms[j])]] <- res$x[j]
if (res$is_lp) values[[sprintf("reduced[%s]", nms[j])]] <- res$reduced[j]
}
con_rows <- lapply(seq_along(cnames), function(i) {
row <- list(constraint = cnames[i], activity = res$activity[i], sense = x$senses[i], rhs = x$rhs[i], slack = res$slack[i],
binding = if (res$binding[i]) "yes" else "no")
if (res$is_lp) row$shadow <- res$duals[i]
row
})
for (i in seq_along(cnames)) {
values[[sprintf("activity[%s]", cnames[i])]] <- res$activity[i]
values[[sprintf("slack[%s]", cnames[i])]] <- res$slack[i]
if (res$is_lp) values[[sprintf("shadow[%s]", cnames[i])]] <- res$duals[i]
}
vcols <- list(list(key = "variable", label = "Variable", type = "string"), list(key = "value", label = "Optimal value", type = "number"),
list(key = "objective", label = "Objective coef.", type = "number"), list(key = "lower", label = "Lower", type = "number"),
list(key = "upper", label = "Upper", type = "number"), list(key = "type", label = "Type", type = "string"))
ccols <- list(list(key = "constraint", label = "Constraint", type = "string"), list(key = "activity", label = "Activity", type = "number"),
list(key = "sense", label = "", type = "string"), list(key = "rhs", label = "Right-hand side", type = "number"),
list(key = "slack", label = "Slack", type = "number"), list(key = "binding", label = "Binding", type = "string"))
if (res$is_lp) {
vcols <- c(vcols, list(list(key = "reduced", label = "Reduced cost", type = "number")))
ccols <- c(ccols, list(list(key = "shadow", label = "Shadow price", type = "number")))
if (res$primal_degenerate) warnings <- c(warnings, "The optimum is degenerate (more constraints are tight than there are variables): shadow prices are one valid set, not the only one.")
if (res$dual_degenerate) warnings <- c(warnings, "A variable at its bound has a zero reduced cost: other optimal solutions with the same objective exist.")
} else {
values$mip_gap <- res$mip_gap
}
tables[[length(tables) + 1]] <- list(key = "solution", title = "Optimal decisions", columns = vcols, rows = var_rows)
if (length(con_rows)) tables[[length(tables) + 1]] <- list(key = "constraints", title = "Constraints", columns = ccols, rows = con_rows)
} else if (status == "infeasible") {
for (r in res$relax) values[[sprintf("relax[%s]", r$constraint)]] <- r$violation
tables[[length(tables) + 1]] <- list(
key = "relax", title = "Smallest relaxation that makes the model feasible",
columns = list(list(key = "constraint", label = "Constraint", type = "string"), list(key = "sense", label = "", type = "string"),
list(key = "rhs", label = "Right-hand side", type = "number"), list(key = "violation", label = "Relax by", type = "number"),
list(key = "relaxed_rhs", label = "Feasible right-hand side", type = "number")),
rows = res$relax
)
warnings <- c(warnings, "The constraints cannot all hold at once.")
} else if (status == "unbounded") {
warnings <- c(warnings, "The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.")
} else {
warnings <- c(warnings, "The solver stopped without an optimal solution.")
}
# %% Parametric sweep
if (nzchar(SWEEP) && length(SWEEP_VALUES)) {
sw <- cs_opt_sweep(model, SWEEP, SWEEP_VALUES)
for (r in sw) values[[sprintf("sweep[%s]", sprintf("%g", r$rhs))]] <- if (r$status == "optimal") r$objective else NA
tables[[length(tables) + 1]] <- list(
key = "sweep", title = sprintf("Objective as %s changes", SWEEP_LABEL),
columns = list(list(key = "rhs", label = SWEEP_LABEL, type = "number"), list(key = "objective", label = "Objective", type = "number"),
list(key = "status", label = "Status", type = "string")),
rows = lapply(sw, function(r) list(rhs = r$rhs, objective = if (r$status == "optimal") r$objective else NA, status = r$status))
)
ok <- Filter(function(r) r$status == "optimal", sw)
if (length(ok)) {
charts[[length(charts) + 1]] <- cs_chart(
"sweep", "efficient-frontier", sprintf("Objective vs %s", SWEEP_LABEL),
list(risk = cs_col(SWEEP_LABEL, vapply(ok, function(r) r$rhs, numeric(1))),
`return` = cs_col("Objective", vapply(ok, function(r) r$objective, numeric(1))),
kind = cs_col("Kind", rep("frontier", length(ok))))
)
}
}
# %% Result
summary <- if (status == "optimal") {
sprintf("Optimal objective %s (%s); %d of %d constraints binding.", cs_fmt_num(res$objective), if (res$sense == "max") "maximized" else "minimized",
as.integer(values$n_binding), length(cnames))
} else if (status == "infeasible") "Infeasible: the constraints cannot all hold." else if (status == "unbounded") "Unbounded: the objective can improve without limit." else "No optimal solution."
stats_list <- list()
if (status == "optimal") {
stats_list <- list(list(key = "objective", label = "Objective", value = res$objective),
list(key = "n_binding", label = "Binding constraints", value = values$n_binding, format = "integer"))
if (values$n_integer > 0) stats_list <- c(stats_list, list(list(key = "mip_gap", label = "MIP gap", value = values$mip_gap)))
}
cs_publish(list(
method = "optimize.lp",
methodVersion = "1.0.0",
title = paste0("Optimization", if (values$n_integer > 0) " (integer)" else ""),
engine = cs_engine_info("highs", "jsonlite"),
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = warnings,
notes = "Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.",
values = values
))
Optimal objective 227.00 (maximized); 0 of 1 constraints binding.
- Objective
- 227
- Binding constraints
- 0
- MIP gap
- 0
Optimal decisions
| Variable | Optimal value | Objective coef. | Lower | Upper | Type |
|---|---|---|---|---|---|
| a | 0 | 60 | 0 | 1 | binary |
| b | 1 | 100 | 0 | 1 | binary |
| c | 1 | 120 | 0 | 1 | binary |
| d | 1 | 7 | 0 | 3 | integer |
Constraints
| Constraint | Activity | Right-hand side | Slack | Binding | |
|---|---|---|---|---|---|
| Weight | 54 | <= | 55 | 1 | no |
- Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear and integer programming (LP / MILP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method optimize.lp 1.0.0 · spec ad6c5ecc500f2fdb
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import codesplash as cs
from codesplash.sim import lp # model → arrays, HiGHS via scipy.optimize, dual conventions (twin of R cs_opt_*)
# %% Model
model = lp.load(json.loads("{\"sense\":\"max\",\"variables\":[{\"name\":\"a\",\"type\":\"binary\",\"objective\":60},{\"name\":\"b\",\"type\":\"binary\",\"objective\":100},{\"name\":\"c\",\"type\":\"binary\",\"objective\":120},{\"name\":\"d\",\"type\":\"integer\",\"lower\":0,\"upper\":3,\"objective\":7}],\"constraints\":[{\"name\":\"Weight\",\"coefs\":{\"a\":10,\"b\":20,\"c\":30,\"d\":4},\"sense\":\"<=\",\"rhs\":55}]}"))
SWEEP = "" # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES = []
SWEEP_LABEL = "" or SWEEP
warnings, tables, charts = [], [], []
# %% Solve
# lp.solve() builds c, A, b and bounds from the model and calls scipy.optimize.linprog(method="highs")
# for linear programs (duals) or scipy.optimize.milp when integers are present.
res = lp.solve(model)
x = res["x_data"]
names = x["names"]
cnames = [str(c.get("name") or f"c{i + 1}") for i, c in enumerate(model["constraints"])]
status = res["status"]
values = {
"status": status, "optimal": 1 if status == "optimal" else 0, "sense": res["sense"],
"objective": res.get("objective"), "n_variables": len(names), "n_constraints": len(cnames),
"n_integer": int(np.sum(x["integrality"])), "n_binding": int(np.sum(res["binding"])) if status == "optimal" else None,
}
if status == "optimal":
var_rows = []
for j, nm in enumerate(names):
values[f"x[{nm}]"] = float(res["x"][j])
row = {"variable": nm, "value": float(res["x"][j]), "objective": float(x["c"][j]),
"lower": float(x["lower"][j]) if np.isfinite(x["lower"][j]) else None,
"upper": float(x["upper"][j]) if np.isfinite(x["upper"][j]) else None,
"type": (model["variables"][j].get("type") or "continuous")}
if res["is_lp"]:
values[f"reduced[{nm}]"] = float(res["reduced"][j])
row["reduced"] = float(res["reduced"][j])
var_rows.append(row)
con_rows = []
for i, nm in enumerate(cnames):
values[f"activity[{nm}]"] = float(res["activity"][i])
values[f"slack[{nm}]"] = float(res["slack"][i])
row = {"constraint": nm, "activity": float(res["activity"][i]), "sense": x["senses"][i], "rhs": float(x["rhs"][i]),
"slack": float(res["slack"][i]), "binding": "yes" if res["binding"][i] else "no"}
if res["is_lp"]:
values[f"shadow[{nm}]"] = float(res["duals"][i])
row["shadow"] = float(res["duals"][i])
con_rows.append(row)
vcols = [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "value", "label": "Optimal value", "type": "number"},
{"key": "objective", "label": "Objective coef.", "type": "number"}, {"key": "lower", "label": "Lower", "type": "number"},
{"key": "upper", "label": "Upper", "type": "number"}, {"key": "type", "label": "Type", "type": "string"}]
ccols = [{"key": "constraint", "label": "Constraint", "type": "string"}, {"key": "activity", "label": "Activity", "type": "number"},
{"key": "sense", "label": "", "type": "string"}, {"key": "rhs", "label": "Right-hand side", "type": "number"},
{"key": "slack", "label": "Slack", "type": "number"}, {"key": "binding", "label": "Binding", "type": "string"}]
if res["is_lp"]:
vcols.append({"key": "reduced", "label": "Reduced cost", "type": "number"})
ccols.append({"key": "shadow", "label": "Shadow price", "type": "number"})
if res["primal_degenerate"]:
warnings.append("The optimum is degenerate (more constraints are tight than there are variables): shadow prices are one valid set, not the only one.")
if res["dual_degenerate"]:
warnings.append("A variable at its bound has a zero reduced cost: other optimal solutions with the same objective exist.")
else:
values["mip_gap"] = res.get("mip_gap", 0.0)
tables.append({"key": "solution", "title": "Optimal decisions", "columns": vcols, "rows": var_rows})
if con_rows:
tables.append({"key": "constraints", "title": "Constraints", "columns": ccols, "rows": con_rows})
elif status == "infeasible":
for r in res.get("relax", []):
values[f"relax[{r['constraint']}]"] = r["violation"]
tables.append({
"key": "relax", "title": "Smallest relaxation that makes the model feasible",
"columns": [{"key": "constraint", "label": "Constraint", "type": "string"}, {"key": "sense", "label": "", "type": "string"},
{"key": "rhs", "label": "Right-hand side", "type": "number"}, {"key": "violation", "label": "Relax by", "type": "number"},
{"key": "relaxed_rhs", "label": "Feasible right-hand side", "type": "number"}],
"rows": res.get("relax", []),
})
warnings.append("The constraints cannot all hold at once.")
elif status == "unbounded":
warnings.append("The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.")
else:
warnings.append("The solver stopped without an optimal solution.")
# %% Parametric sweep
if SWEEP and SWEEP_VALUES:
sw = lp.sweep(model, SWEEP, SWEEP_VALUES)
for r in sw:
values[f"sweep[{r['rhs']:g}]"] = r["objective"] if r["status"] == "optimal" else None
tables.append({
"key": "sweep", "title": f"Objective as {SWEEP_LABEL} changes",
"columns": [{"key": "rhs", "label": SWEEP_LABEL, "type": "number"}, {"key": "objective", "label": "Objective", "type": "number"},
{"key": "status", "label": "Status", "type": "string"}],
"rows": [{"rhs": r["rhs"], "objective": r["objective"] if r["status"] == "optimal" else None, "status": r["status"]} for r in sw],
})
ok = [r for r in sw if r["status"] == "optimal"]
if ok:
charts.append(cs.chart(
"sweep", "efficient-frontier", f"Objective vs {SWEEP_LABEL}",
{"risk": cs.col(SWEEP_LABEL, [r["rhs"] for r in ok]), "return": cs.col("Objective", [r["objective"] for r in ok]),
"kind": cs.col("Kind", ["frontier"] * len(ok))},
))
# %% Result
if status == "optimal":
summary = f"Optimal objective {cs.fmt_num(res['objective'])} ({'maximized' if res['sense'] == 'max' else 'minimized'}); {values['n_binding']} of {len(cnames)} constraints binding."
else:
summary = {"infeasible": "Infeasible: the constraints cannot all hold.", "unbounded": "Unbounded: the objective can improve without limit."}.get(status, "No optimal solution.")
cs.publish({
"method": "optimize.lp",
"methodVersion": "1.0.0",
"title": "Optimization" + (" (integer)" if values["n_integer"] else ""),
"engine": cs.engine_info("numpy", "scipy"),
"summary": summary,
"statistics": [s for s in [
{"key": "objective", "label": "Objective", "value": res.get("objective")} if status == "optimal" else None,
{"key": "n_binding", "label": "Binding constraints", "value": values["n_binding"], "format": "integer"} if status == "optimal" else None,
{"key": "mip_gap", "label": "MIP gap", "value": values.get("mip_gap")} if status == "optimal" and values["n_integer"] else None,
] if s],
"tables": tables,
"charts": charts,
"warnings": warnings,
"notes": [
"Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.",
],
"values": values,
})
The solver reports a gap of 0, so this answer is proven best, not merely good. On a hard model, you might stop early with a small gap and know how far from best you could be.
This card shows slack, but no shadow prices. Integer programs don't have them: with whole-number choices, one more unit of a limit can be worth nothing, or quite a lot.
Why not round?
CheckpointCheck yourself
Solving without the whole-number rule gives a, b and 83% of c. Why not round that off?
Show the answer
Answer: b
Rounding down keeps a and b, then d fills the rest, for 181. The best integer plan uses a different set altogether, for .
Check yourself
The best plan weighs 54 against a limit of 55. How much slack does the Weight constraint have?
Show the answer
Answer: 1
55 − 54 = 1. There's room left, because no remaining item is light enough to fit.
When there's no answer
PredictPredict first
A model asks for , with and . No values meet all three. The solver status is infeasible. What's the smallest change that would make it solvable?
Reveal
The most you can reach is , so the floor is short by 3. The card names the constraints to relax and by how much. Then the decision is yours: can the floor come down, or can a cap go up?
When there's no limit
In the appUnbounded: the objective can improve without limit.
- The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.
- Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear and integer programming (LP / MILP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method optimize.lp 1.0.0 · spec 3cde5d51db908811
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_opt_*: model -> arrays, HiGHS via highs::highs_solve, dual conventions (twin of codesplash.sim.lp)
# %% Model
model <- cs_opt_load("{\"sense\":\"max\",\"variables\":[{\"name\":\"x\",\"objective\":2},{\"name\":\"y\",\"objective\":1}],\"constraints\":[{\"name\":\"Mix\",\"coefs\":{\"x\":1,\"y\":-1},\"sense\":\"<=\",\"rhs\":3}]}")
SWEEP <- "" # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES <- c()
SWEEP_LABEL <- ""
if (!nzchar(SWEEP_LABEL)) SWEEP_LABEL <- SWEEP
warnings <- list(); tables <- list(); charts <- list()
# %% Solve
# cs_opt_solve() builds c, A, lhs/rhs and bounds from the model and calls
# highs::highs_solve(L = c, lower, upper, A, lhs, rhs, types, maximum = ...).
res <- cs_opt_solve(model)
x <- res$x_data
nms <- x$names
cnames <- vapply(seq_along(model$constraints), function(i) {
n <- model$constraints[[i]]$name
if (is.null(n) || !nzchar(n)) sprintf("c%d", i) else as.character(n)
}, character(1))
status <- res$status
values <- list(
status = status, optimal = if (status == "optimal") 1 else 0, sense = res$sense,
objective = if (is.null(res$objective)) NA else res$objective, n_variables = length(nms), n_constraints = length(cnames),
n_integer = sum(x$integrality), n_binding = if (status == "optimal") sum(res$binding) else NA
)
fin <- function(v) if (is.finite(v)) v else NA
if (status == "optimal") {
var_rows <- lapply(seq_along(nms), function(j) {
row <- list(variable = nms[j], value = res$x[j], objective = x$c[j], lower = fin(x$lower[j]), upper = fin(x$upper[j]),
type = model$variables[[j]]$type %||% "continuous")
if (res$is_lp) row$reduced <- res$reduced[j]
row
})
for (j in seq_along(nms)) {
values[[sprintf("x[%s]", nms[j])]] <- res$x[j]
if (res$is_lp) values[[sprintf("reduced[%s]", nms[j])]] <- res$reduced[j]
}
con_rows <- lapply(seq_along(cnames), function(i) {
row <- list(constraint = cnames[i], activity = res$activity[i], sense = x$senses[i], rhs = x$rhs[i], slack = res$slack[i],
binding = if (res$binding[i]) "yes" else "no")
if (res$is_lp) row$shadow <- res$duals[i]
row
})
for (i in seq_along(cnames)) {
values[[sprintf("activity[%s]", cnames[i])]] <- res$activity[i]
values[[sprintf("slack[%s]", cnames[i])]] <- res$slack[i]
if (res$is_lp) values[[sprintf("shadow[%s]", cnames[i])]] <- res$duals[i]
}
vcols <- list(list(key = "variable", label = "Variable", type = "string"), list(key = "value", label = "Optimal value", type = "number"),
list(key = "objective", label = "Objective coef.", type = "number"), list(key = "lower", label = "Lower", type = "number"),
list(key = "upper", label = "Upper", type = "number"), list(key = "type", label = "Type", type = "string"))
ccols <- list(list(key = "constraint", label = "Constraint", type = "string"), list(key = "activity", label = "Activity", type = "number"),
list(key = "sense", label = "", type = "string"), list(key = "rhs", label = "Right-hand side", type = "number"),
list(key = "slack", label = "Slack", type = "number"), list(key = "binding", label = "Binding", type = "string"))
if (res$is_lp) {
vcols <- c(vcols, list(list(key = "reduced", label = "Reduced cost", type = "number")))
ccols <- c(ccols, list(list(key = "shadow", label = "Shadow price", type = "number")))
if (res$primal_degenerate) warnings <- c(warnings, "The optimum is degenerate (more constraints are tight than there are variables): shadow prices are one valid set, not the only one.")
if (res$dual_degenerate) warnings <- c(warnings, "A variable at its bound has a zero reduced cost: other optimal solutions with the same objective exist.")
} else {
values$mip_gap <- res$mip_gap
}
tables[[length(tables) + 1]] <- list(key = "solution", title = "Optimal decisions", columns = vcols, rows = var_rows)
if (length(con_rows)) tables[[length(tables) + 1]] <- list(key = "constraints", title = "Constraints", columns = ccols, rows = con_rows)
} else if (status == "infeasible") {
for (r in res$relax) values[[sprintf("relax[%s]", r$constraint)]] <- r$violation
tables[[length(tables) + 1]] <- list(
key = "relax", title = "Smallest relaxation that makes the model feasible",
columns = list(list(key = "constraint", label = "Constraint", type = "string"), list(key = "sense", label = "", type = "string"),
list(key = "rhs", label = "Right-hand side", type = "number"), list(key = "violation", label = "Relax by", type = "number"),
list(key = "relaxed_rhs", label = "Feasible right-hand side", type = "number")),
rows = res$relax
)
warnings <- c(warnings, "The constraints cannot all hold at once.")
} else if (status == "unbounded") {
warnings <- c(warnings, "The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.")
} else {
warnings <- c(warnings, "The solver stopped without an optimal solution.")
}
# %% Parametric sweep
if (nzchar(SWEEP) && length(SWEEP_VALUES)) {
sw <- cs_opt_sweep(model, SWEEP, SWEEP_VALUES)
for (r in sw) values[[sprintf("sweep[%s]", sprintf("%g", r$rhs))]] <- if (r$status == "optimal") r$objective else NA
tables[[length(tables) + 1]] <- list(
key = "sweep", title = sprintf("Objective as %s changes", SWEEP_LABEL),
columns = list(list(key = "rhs", label = SWEEP_LABEL, type = "number"), list(key = "objective", label = "Objective", type = "number"),
list(key = "status", label = "Status", type = "string")),
rows = lapply(sw, function(r) list(rhs = r$rhs, objective = if (r$status == "optimal") r$objective else NA, status = r$status))
)
ok <- Filter(function(r) r$status == "optimal", sw)
if (length(ok)) {
charts[[length(charts) + 1]] <- cs_chart(
"sweep", "efficient-frontier", sprintf("Objective vs %s", SWEEP_LABEL),
list(risk = cs_col(SWEEP_LABEL, vapply(ok, function(r) r$rhs, numeric(1))),
`return` = cs_col("Objective", vapply(ok, function(r) r$objective, numeric(1))),
kind = cs_col("Kind", rep("frontier", length(ok))))
)
}
}
# %% Result
summary <- if (status == "optimal") {
sprintf("Optimal objective %s (%s); %d of %d constraints binding.", cs_fmt_num(res$objective), if (res$sense == "max") "maximized" else "minimized",
as.integer(values$n_binding), length(cnames))
} else if (status == "infeasible") "Infeasible: the constraints cannot all hold." else if (status == "unbounded") "Unbounded: the objective can improve without limit." else "No optimal solution."
stats_list <- list()
if (status == "optimal") {
stats_list <- list(list(key = "objective", label = "Objective", value = res$objective),
list(key = "n_binding", label = "Binding constraints", value = values$n_binding, format = "integer"))
if (values$n_integer > 0) stats_list <- c(stats_list, list(list(key = "mip_gap", label = "MIP gap", value = values$mip_gap)))
}
cs_publish(list(
method = "optimize.lp",
methodVersion = "1.0.0",
title = paste0("Optimization", if (values$n_integer > 0) " (integer)" else ""),
engine = cs_engine_info("highs", "jsonlite"),
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = warnings,
notes = "Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.",
values = values
))
Unbounded: the objective can improve without limit.
- The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.
- Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear and integer programming (LP / MILP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method optimize.lp 1.0.0 · spec 3cde5d51db908811
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import codesplash as cs
from codesplash.sim import lp # model → arrays, HiGHS via scipy.optimize, dual conventions (twin of R cs_opt_*)
# %% Model
model = lp.load(json.loads("{\"sense\":\"max\",\"variables\":[{\"name\":\"x\",\"objective\":2},{\"name\":\"y\",\"objective\":1}],\"constraints\":[{\"name\":\"Mix\",\"coefs\":{\"x\":1,\"y\":-1},\"sense\":\"<=\",\"rhs\":3}]}"))
SWEEP = "" # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES = []
SWEEP_LABEL = "" or SWEEP
warnings, tables, charts = [], [], []
# %% Solve
# lp.solve() builds c, A, b and bounds from the model and calls scipy.optimize.linprog(method="highs")
# for linear programs (duals) or scipy.optimize.milp when integers are present.
res = lp.solve(model)
x = res["x_data"]
names = x["names"]
cnames = [str(c.get("name") or f"c{i + 1}") for i, c in enumerate(model["constraints"])]
status = res["status"]
values = {
"status": status, "optimal": 1 if status == "optimal" else 0, "sense": res["sense"],
"objective": res.get("objective"), "n_variables": len(names), "n_constraints": len(cnames),
"n_integer": int(np.sum(x["integrality"])), "n_binding": int(np.sum(res["binding"])) if status == "optimal" else None,
}
if status == "optimal":
var_rows = []
for j, nm in enumerate(names):
values[f"x[{nm}]"] = float(res["x"][j])
row = {"variable": nm, "value": float(res["x"][j]), "objective": float(x["c"][j]),
"lower": float(x["lower"][j]) if np.isfinite(x["lower"][j]) else None,
"upper": float(x["upper"][j]) if np.isfinite(x["upper"][j]) else None,
"type": (model["variables"][j].get("type") or "continuous")}
if res["is_lp"]:
values[f"reduced[{nm}]"] = float(res["reduced"][j])
row["reduced"] = float(res["reduced"][j])
var_rows.append(row)
con_rows = []
for i, nm in enumerate(cnames):
values[f"activity[{nm}]"] = float(res["activity"][i])
values[f"slack[{nm}]"] = float(res["slack"][i])
row = {"constraint": nm, "activity": float(res["activity"][i]), "sense": x["senses"][i], "rhs": float(x["rhs"][i]),
"slack": float(res["slack"][i]), "binding": "yes" if res["binding"][i] else "no"}
if res["is_lp"]:
values[f"shadow[{nm}]"] = float(res["duals"][i])
row["shadow"] = float(res["duals"][i])
con_rows.append(row)
vcols = [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "value", "label": "Optimal value", "type": "number"},
{"key": "objective", "label": "Objective coef.", "type": "number"}, {"key": "lower", "label": "Lower", "type": "number"},
{"key": "upper", "label": "Upper", "type": "number"}, {"key": "type", "label": "Type", "type": "string"}]
ccols = [{"key": "constraint", "label": "Constraint", "type": "string"}, {"key": "activity", "label": "Activity", "type": "number"},
{"key": "sense", "label": "", "type": "string"}, {"key": "rhs", "label": "Right-hand side", "type": "number"},
{"key": "slack", "label": "Slack", "type": "number"}, {"key": "binding", "label": "Binding", "type": "string"}]
if res["is_lp"]:
vcols.append({"key": "reduced", "label": "Reduced cost", "type": "number"})
ccols.append({"key": "shadow", "label": "Shadow price", "type": "number"})
if res["primal_degenerate"]:
warnings.append("The optimum is degenerate (more constraints are tight than there are variables): shadow prices are one valid set, not the only one.")
if res["dual_degenerate"]:
warnings.append("A variable at its bound has a zero reduced cost: other optimal solutions with the same objective exist.")
else:
values["mip_gap"] = res.get("mip_gap", 0.0)
tables.append({"key": "solution", "title": "Optimal decisions", "columns": vcols, "rows": var_rows})
if con_rows:
tables.append({"key": "constraints", "title": "Constraints", "columns": ccols, "rows": con_rows})
elif status == "infeasible":
for r in res.get("relax", []):
values[f"relax[{r['constraint']}]"] = r["violation"]
tables.append({
"key": "relax", "title": "Smallest relaxation that makes the model feasible",
"columns": [{"key": "constraint", "label": "Constraint", "type": "string"}, {"key": "sense", "label": "", "type": "string"},
{"key": "rhs", "label": "Right-hand side", "type": "number"}, {"key": "violation", "label": "Relax by", "type": "number"},
{"key": "relaxed_rhs", "label": "Feasible right-hand side", "type": "number"}],
"rows": res.get("relax", []),
})
warnings.append("The constraints cannot all hold at once.")
elif status == "unbounded":
warnings.append("The objective is unbounded: some variable can grow forever while improving it — add a bound or a constraint.")
else:
warnings.append("The solver stopped without an optimal solution.")
# %% Parametric sweep
if SWEEP and SWEEP_VALUES:
sw = lp.sweep(model, SWEEP, SWEEP_VALUES)
for r in sw:
values[f"sweep[{r['rhs']:g}]"] = r["objective"] if r["status"] == "optimal" else None
tables.append({
"key": "sweep", "title": f"Objective as {SWEEP_LABEL} changes",
"columns": [{"key": "rhs", "label": SWEEP_LABEL, "type": "number"}, {"key": "objective", "label": "Objective", "type": "number"},
{"key": "status", "label": "Status", "type": "string"}],
"rows": [{"rhs": r["rhs"], "objective": r["objective"] if r["status"] == "optimal" else None, "status": r["status"]} for r in sw],
})
ok = [r for r in sw if r["status"] == "optimal"]
if ok:
charts.append(cs.chart(
"sweep", "efficient-frontier", f"Objective vs {SWEEP_LABEL}",
{"risk": cs.col(SWEEP_LABEL, [r["rhs"] for r in ok]), "return": cs.col("Objective", [r["objective"] for r in ok]),
"kind": cs.col("Kind", ["frontier"] * len(ok))},
))
# %% Result
if status == "optimal":
summary = f"Optimal objective {cs.fmt_num(res['objective'])} ({'maximized' if res['sense'] == 'max' else 'minimized'}); {values['n_binding']} of {len(cnames)} constraints binding."
else:
summary = {"infeasible": "Infeasible: the constraints cannot all hold.", "unbounded": "Unbounded: the objective can improve without limit."}.get(status, "No optimal solution.")
cs.publish({
"method": "optimize.lp",
"methodVersion": "1.0.0",
"title": "Optimization" + (" (integer)" if values["n_integer"] else ""),
"engine": cs.engine_info("numpy", "scipy"),
"summary": summary,
"statistics": [s for s in [
{"key": "objective", "label": "Objective", "value": res.get("objective")} if status == "optimal" else None,
{"key": "n_binding", "label": "Binding constraints", "value": values["n_binding"], "format": "integer"} if status == "optimal" else None,
{"key": "mip_gap", "label": "MIP gap", "value": values.get("mip_gap")} if status == "optimal" and values["n_integer"] else None,
] if s],
"tables": tables,
"charts": charts,
"warnings": warnings,
"notes": [
"Solved with HiGHS. Shadow price = change in the objective per unit increase of a constraint's right-hand side; reduced cost = change per unit move of a variable off its bound.",
],
"values": values,
})
Status: unbounded. The profit can grow forever, which real profit can't do. So a limit is missing from your model: capacity, demand or budget. This result reports an error in the model, and it doesn't mean you found an endless opportunity.
Check your understanding
CheckpointCheck yourself
You're planning how many liters of each blend to make. Do you need integer variables?
Show the answer
Answer: a
Use integers only where fractions make no sense. A continuous model is easier to solve, and it tells you what each limit is worth.
Check yourself
Your model comes back unbounded. What's the most likely cause?
Show the answer
Answer: b
Too many or conflicting constraints would make it infeasible instead. Unbounded means nothing stops the objective from improving.
Try it
In the appIn Scenarios & optimization, choose Budget allocation (knapsack) or Product mix (integer program). On the Optimize step, each variable can be continuous, integer or yes/no.
Recap
Recap- Use integer variables when fractions make no sense.
- Neither rounding nor a greedy rule can guarantee the best answer.
- Infeasible means your limits conflict, and the card suggests what to relax.
- Unbounded means a limit is missing.