Skip to content

Linear programs and shadow prices

Write a choice under limits as a linear program, find the best corner, and use shadow prices to see which limit is worth relaxing.

Applied ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Write decisions, an objective and constraints as a linear program
  • Identify binding constraints and read slack
  • Use a shadow price, and test its range with a sweep
01

Choices under limits

Read

A workshop makes chairs and tables. Chairs earn 45 and tables earn 80. Wood and labor are limited:

max⁡45 c+80 ts.t.5 c+20 t≤400(wood)10 c+15 t≤450(labor)c,t≥0\begin{aligned} \max\quad & 45\,c + 80\,t \\ \text{s.t.}\quad & 5\,c + 20\,t \le 400 \quad \text{(wood)} \\ & 10\,c + 15\,t \le 450 \quad \text{(labor)} \\ & c, t \ge 0 \end{aligned}

That's a linear programLinear programFinds the decision values that give the best linear objective while meeting linear constraints.: a linear objective, linear limits, and decisions that can take fractional values.

02

Where is the best mix?

Explore

The limits draw a feasible region. In this similar two-product problem, move the limits and the profits, and watch the best point.

DExplorable · The feasible region of a linear program

Which mix of two products earns the most, and what is one more hour of labor worth?

How much would profit rise with one more hour of labor?

5.0
How sure?
6.0
5.0
100
150
40
0
profit 380.0

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

The best point is always on a corner of the region. Which limits meet at that corner? When you raise the profit of one product, does the answer slide, or jump to another corner?

03

Solve it

In the app
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.
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 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
))
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.
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 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,
})

The best profit is 2,200, from 24 chairs and 14 tables. 2 of 2 constraints are binding: fully used, with no slack.

Check by hand. Wood: 5×24+20×14=4005 \times 24 + 20 \times 14 = 400. Labor: 10×24+15×14=45010 \times 24 + 15 \times 14 = 450. Profit: 45×24+80×14=2,20045 \times 24 + 80 \times 14 = 2{,}200.

04

What's another hour worth?

Predict

Predict first

You can buy one more unit of wood or one more hour of labor. Which adds more profit?

WoodLaborThey're worth the same
Reveal

Labor. Its shadow priceShadow priceHow much the best objective would improve with one more unit of a constrained resource. is 4, and wood's is 1: that's how much the best profit rises per extra unit, with the mix re-solved. They also account for all the profit: 400×1+450×4=2,200400 \times 1 + 450 \times 4 = 2{,}200. Pay less than the shadow price for more capacity, and you come out ahead.

05

Use a shadow price

Checkpoint

Check yourself

A supplier offers extra labor at 6 per hour. Labor's shadow price is 4. Should you buy?

Show the answer

Answer: b

The shadow price is the most an extra unit is worth, while the same constraints stay binding.

Check yourself

A constraint has slack: you aren't using all of it. What's its shadow price?

Show the answer

Answer: a

If you already have spare capacity, one more unit adds nothing. Only binding constraints have non-zero shadow prices.

06

A shadow price has a range

In the app

A shipping model moves goods at least cost, from two plants to two stores. Demand at store C is one of its limits. A sweep re-solves as that limit changes.

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

Optimal objective 195.00 (minimized); 2 of 4 constraints binding.

Objective
195
Binding constraints
2

Plots

Objective vs Demand at CWhich portfolios give the most return for each level of risk, and where does the chosen one sit?
View data
KindObjectiveDemand at C
frontier11510
frontier15520
frontier19530
frontier23540

Optimal decisions

VariableOptimal valueObjective coef.LowerUpperTypeReduced cost
x_AC3040—continuous0
x_AD060—continuous3
x_BC050—continuous1
x_BD2530—continuous0

Constraints

ConstraintActivityRight-hand sideSlackBindingShadow price
Supply A30<=4010no0
Supply B25<=3510no0
Demand C30=300yes4
Demand D25=250yes3

Objective as Demand at C changes

Demand at CObjectiveStatus
10115optimal
20155optimal
30195optimal
40235optimal
  • 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 c3f39327c822ec39
# 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\":\"min\",\"variables\":[{\"name\":\"x_AC\",\"objective\":4},{\"name\":\"x_AD\",\"objective\":6},{\"name\":\"x_BC\",\"objective\":5},{\"name\":\"x_BD\",\"objective\":3}],\"constraints\":[{\"name\":\"Supply A\",\"coefs\":{\"x_AC\":1,\"x_AD\":1},\"sense\":\"<=\",\"rhs\":40},{\"name\":\"Supply B\",\"coefs\":{\"x_BC\":1,\"x_BD\":1},\"sense\":\"<=\",\"rhs\":35},{\"name\":\"Demand C\",\"coefs\":{\"x_AC\":1,\"x_BC\":1},\"sense\":\"=\",\"rhs\":30},{\"name\":\"Demand D\",\"coefs\":{\"x_AD\":1,\"x_BD\":1},\"sense\":\"=\",\"rhs\":25}]}")
SWEEP <- "Demand C" # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES <- c(10, 20, 30, 40)
SWEEP_LABEL <- "Demand at C"
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
))
Python

Optimal objective 195.00 (minimized); 2 of 4 constraints binding.

Objective
195
Binding constraints
2

To keep this page light, the plots are shown once, under the R tab.

Optimal decisions

VariableOptimal valueObjective coef.LowerUpperTypeReduced cost
x_AC3040—continuous0
x_AD060—continuous3
x_BC050—continuous1
x_BD2530—continuous0

Constraints

ConstraintActivityRight-hand sideSlackBindingShadow price
Supply A30<=4010no0
Supply B25<=3510no0
Demand C30=300yes4
Demand D25=250yes3

Objective as Demand at C changes

Demand at CObjectiveStatus
10115optimal
20155optimal
30195optimal
40235optimal
  • 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 c3f39327c822ec39
# 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\":\"min\",\"variables\":[{\"name\":\"x_AC\",\"objective\":4},{\"name\":\"x_AD\",\"objective\":6},{\"name\":\"x_BC\",\"objective\":5},{\"name\":\"x_BD\",\"objective\":3}],\"constraints\":[{\"name\":\"Supply A\",\"coefs\":{\"x_AC\":1,\"x_AD\":1},\"sense\":\"<=\",\"rhs\":40},{\"name\":\"Supply B\",\"coefs\":{\"x_BC\":1,\"x_BD\":1},\"sense\":\"<=\",\"rhs\":35},{\"name\":\"Demand C\",\"coefs\":{\"x_AC\":1,\"x_BC\":1},\"sense\":\"=\",\"rhs\":30},{\"name\":\"Demand D\",\"coefs\":{\"x_AD\":1,\"x_BD\":1},\"sense\":\"=\",\"rhs\":25}]}"))
SWEEP = "Demand C"  # constraint whose right-hand side is swept ("" = none)
SWEEP_VALUES = [10, 20, 30, 40]
SWEEP_LABEL = "Demand at C" 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 least cost is 195. As demand at C runs through 10, 20, 30 and 40, the cost runs through 115, 155, 195 and 235: up 4 per unit, which is that constraint's shadow price.

Beyond some point, supply runs out or another route takes over, and the slope changes. Sweep it before you bet on a shadow price far from your current plan.

07

Check your understanding

Checkpoint

Check yourself

A plan makes 24 chairs at a profit of 45 each and 14 tables at 80 each. What's the total profit?

Show the answer

Answer: 2200

45 × 24 + 80 × 14 = 1,080 + 1,120 = 2,200.

Check yourself

A route isn't used in the best plan, and its reduced cost is 3. What does that mean?

Show the answer

Answer: a

Reduced cost measures how far a variable left at zero is from being worth using.

Check yourself

Your LP uses forecasts of demand and prices, and it gives one precise plan. What's the catch?

Show the answer

Answer: b

The solver treats inputs as known. Sweep the important ones, or simulate, to see how robust the plan is.

08

Try it

In the app

In Scenarios & optimization, choose Transportation plan (LP), or open the Optimize step of any model. Add variables and constraints there. The Sweep section re-solves as one constraint's limit varies.

Python
from scipy.optimize import linprog

# linprog minimizes, so negate the profit
res = linprog(c=[-45, -80], A_ub=[[5, 20], [10, 15]], b_ub=[400, 450], bounds=(0, None), method="highs")

print(res.x, -res.fun)
print(-res.ineqlin.marginals)   # shadow prices of wood and labor
R
library(highs)

res <- highs_solve(
  L = c(45, 80), maximum = TRUE, lower = c(0, 0),
  A = rbind(c(5, 20), c(10, 15)), rhs = c(400, 450)
)
res$primal_solution
res$objective_value
res$solver_msg
09

Recap

Recap
  • A linear program has decisions, a linear objective and linear limits.
  • The best point is a corner, where binding constraints meet.
  • A shadow price is what one more unit of a limit is worth, within a range.
  • Sweep a constraint to see that range.

Concepts in this lesson