Skip to content

DOptimization · optimize.lp

Linear and integer programming (LP / MILP)

Which decisions maximize (or minimize) a linear objective within the constraints?

Solves a linear or mixed-integer program with HiGHS in both engines (scipy.optimize ↔ R highs): the optimal decisions, objective, constraint activity and slack, and for linear programs the shadow price of each constraint and the reduced cost of each variable. Infeasible models are diagnosed by an elastic program that names the constraints to relax and by how much; a parametric sweep re-solves over values of one constraint (efficient frontiers).

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Product mix”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

OptimizationRecorded · Python and R agreeRecorded 2026-11-09 · 18 values compared
R

Optimal objective 2200.00 (maximized); 2 of 2 constraints binding.

Objective
2,200
Binding constraints
2

Optimal decisions

VariableOptimal valueObjective coef.LowerUpperTypeReduced cost
chairs24450—continuous0
tables14800—continuous0

Constraints

ConstraintActivityRight-hand sideSlackBindingShadow price
Wood400<=4000yes1
Labour450<=4500yes4
  • 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.
Python

Optimal objective 2200.00 (maximized); 2 of 2 constraints binding.

Objective
2,200
Binding constraints
2

Optimal decisions

VariableOptimal valueObjective coef.LowerUpperTypeReduced cost
chairs24450—continuous0
tables14800—continuous0

Constraints

ConstraintActivityRight-hand sideSlackBindingShadow price
Wood400<=4000yes1.0000
Labour450<=4500yes4
  • 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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Product mixNo data needed
  • Diet min ge eqNo data needed
  • Knapsack milpNo data needed
  • Infeasible relaxNo data needed
  • UnboundedNo data needed
  • Transport sweepNo data needed

In the guides

Where it sits in the decision guides

  • Constrained optimization (risk, fairness, cost) · DS & ML Decision Guide · Optimize / decide
  • Prescriptive analytics (simulation, OR, causal RL) · DS & ML Decision Guide · Optimize / decide
  • Optimize / decide: expected value / reward; conversion / business impact; regret, cumulative reward; constraint satisfaction · DS & ML Decision Guide · How to evaluate — common metrics by question type

Choices you make

hypothesis

Optimization model (JSON)default {"sense":"max","variables":[{"name":"chairs","lower":0,"upper":null,"type":"continuous","objective":45},{"name":"tables","lower":0,"upper":null,"type":"continuous","objective":80}],"constraints":[{"name":"Wood","coefs":{"chairs":5,"tables":20},"sense":"<=","rhs":400},{"name":"Labour","coefs":{"chairs":10,"tables":15},"sense":"<=","rhs":450}],"objective_constant":0}

Variables (bounds, continuous/integer/binary, objective coefficient), linear constraints and the sense — built by the Scenario studio's Optimize step.

options

Sweep a constraintdefault —

Name of a constraint whose right-hand side is varied (empty = no sweep).

Right-hand-side valuesdefault

Right-hand-side values to sweep for the chosen constraint, to see how the optimum changes.

Sweep axis labeldefault —

How the swept value is shown (e.g. "Target return"); defaults to the constraint name.

What it reports

status
Finds the decision values that give the best linear objective while meeting linear constraints.
optimal
Finds the decision values that give the best linear objective while meeting linear constraints.
objective
Finds the decision values that give the best linear objective while meeting linear constraints.
n_variables
How many independent units the analysis used; it sets precision and power.
n_constraints
How many independent units the analysis used; it sets precision and power.
n_integer
How many independent units the analysis used; it sets precision and power.
n_binding
How many independent units the analysis used; it sets precision and power.
sense
Whether the objective was minimized or maximized.

Per group, level or term: x[<variable>], reduced[<variable>], activity[<constraint>], slack[<constraint>], shadow[<constraint>], relax[<constraint>], sweep[<value>], mip_gap

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy, scipy, codesplash; R uses highs, jsonlite, codesplashr.

Default traps between the two languages

  • Both engines call HiGHS (scipy's bundled build ↔ the R highs package); a unique optimum, its duals and reduced costs agree to the solver's feasibility tolerance (abs 1e-7). Degenerate or tied optima can return different vertices or duals — the result flags degeneracy.
Python

The exact script CodeSplash ran for example “Product mix” · 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 1fc90745d4a6f433
# 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\":\"chairs\",\"lower\":0,\"upper\":null,\"type\":\"continuous\",\"objective\":45},{\"name\":\"tables\",\"lower\":0,\"upper\":null,\"type\":\"continuous\",\"objective\":80}],\"constraints\":[{\"name\":\"Wood\",\"coefs\":{\"chairs\":5,\"tables\":20},\"sense\":\"<=\",\"rhs\":400},{\"name\":\"Labour\",\"coefs\":{\"chairs\":10,\"tables\":15},\"sense\":\"<=\",\"rhs\":450}],\"objective_constant\":0}"))
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,
})
R

The exact script CodeSplash ran for example “Product mix” · 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 1fc90745d4a6f433
# 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\":\"chairs\",\"lower\":0,\"upper\":null,\"type\":\"continuous\",\"objective\":45},{\"name\":\"tables\",\"lower\":0,\"upper\":null,\"type\":\"continuous\",\"objective\":80}],\"constraints\":[{\"name\":\"Wood\",\"coefs\":{\"chairs\":5,\"tables\":20},\"sense\":\"<=\",\"rhs\":400},{\"name\":\"Labour\",\"coefs\":{\"chairs\":10,\"tables\":15},\"sense\":\"<=\",\"rhs\":450}],\"objective_constant\":0}")
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
))

Sources

  • Huangfu Q, Hall JAJ (2018). Parallelizing the dual revised simplex method. Mathematical Programming Computation 10:119–142.
  • Chinneck JW (2008). Feasibility and Infeasibility in Optimization. Springer (elastic programming).

From the CodeSplash method registry · optimize.lp v1.0.0.