Integer and Nonlinear Models¶
In Weeks 9 to 11 every decision variable could take any value: 37.5 batches, 212.4 kg of beans. Many business decisions are not like that. You open a kiosk or you do not; you fund a project or you do not. This reading adds binary variables (0 or 1) to the linear programs you already know, shows the modelling tricks they make possible, explains why you cannot simply solve the LP and round, and ends with one nonlinear model: spreading a cash reserve to keep its risk low.
After this reading you can:
model yes-or-no decisions with binary variables in PuLP (capital budgeting);
write logical rules (requires, not both, at least one) as linear constraints;
explain why rounding an LP solution fails, and why one riyal of budget can change the whole plan;
model a fixed cost with a binary variable and a big-M link, and solve a set-covering problem;
solve a small nonlinear model (portfolio risk) with
scipy.optimize.
Setup¶
The first cell installs PuLP when you are in Colab; on your own computer, install it once with pip install "pulp[highs]>=4.3,<5". PuLP 4 needs a solver named explicitly; the course uses HiGHS (free, open source, installed by pulp[highs]), and it also reports shadow prices and reduced costs. One more PuLP 4 rule: a NumPy integer, such as a number read from a DataFrame, cannot follow <= or >= in a constraint; wrap it in float().
# Colab does not include PuLP: install it once per session (a few seconds).
# PuLP 4 ships no solver: the [highs] extra adds HiGHS, a free open-source solver.
# The first model you solve prints two lines about HiGHS (its version and licence): that is normal.
import sys
if "google.colab" in sys.modules:
%pip install -q "pulp[highs]>=4.3,<5"import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pulp
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
projects = load("qahwa_projects.csv").fillna("")
sites = load("qahwa_sites.csv")
projectsThe decisions¶
Qahwa House’s board has three expansion decisions to make this year.
Which projects to fund. Ten projects compete for a capital budget of 1,000 k SAR (one million riyals). For each one the finance team estimated the cost and the NPV: the net present value over five years, after paying for the project, so every project here adds value. Some projects depend on others (
requires) and some cannot be done together (excludes).Where to open drive-through kiosks in north Riyadh, so that customers in every district have one within 10 minutes, or so that the kiosks earn the most.
How to place a cash reserve of 2 million SAR across four funds without taking too much risk.
All ten projects together would cost far more than the budget:
cost = projects.set_index("project")["cost_ksar"]
npv = projects.set_index("project")["npv_ksar"]
print(f"all ten projects: cost {cost.sum():,} k SAR, NPV {npv.sum():,} k SAR; budget 1,000 k SAR")all ten projects: cost 2,600 k SAR, NPV 2,790 k SAR; budget 1,000 k SAR
1. Binary variables: capital budgeting¶
Give each project a variable that is 1 if we fund project and 0 if we do not. Then the total NPV and the total cost are linear in the :
This is a capital budgeting model (also called a knapsack problem: fill a bag of limited size with the most valuable items). In PuLP the only change from an LP is cat="Binary" when the variables are created. A first version ignores the requires and excludes columns:
m = pulp.LpProblem("capital_budgeting", pulp.LpMaximize)
x = m.add_variable_dicts("fund", cost.index, cat="Binary") # one 0/1 variable per project
m += pulp.lpSum(npv[p] * x[p] for p in cost.index) # objective: total NPV
m += pulp.lpSum(cost[p] * x[p] for p in cost.index) <= 1000, "budget" # constraint: the capital budget
res = m.solve(pulp.HiGHS(msg=False))
chosen = [p for p in cost.index if x[p].value() > 0.5]
print(res.status.name, f"| NPV {pulp.value(m.objective):,.0f} k SAR | cost {cost[chosen].sum():,} k SAR")
projects[projects["project"].isin(chosen)][["project", "name", "cost_ksar", "npv_ksar", "requires"]]Running HiGHS 1.16.0 (git hash: f3f113d): Copyright (c) 2026 under MIT licence terms
Includes third-party software components, see THIRD_PARTY_NOTICES.md for full details
Optimal | NPV 1,300 k SAR | cost 960 k SAR
An NPV of 1,300 k SAR, but the plan cannot be carried out: it funds the loyalty app (P2) and the delivery-platform link (P3), and both run on the new POS system (P1), which it leaves out. A model only knows what we tell it.
2. Logical rules as linear constraints¶
With 0/1 variables, logical rules become simple linear constraints. Check each one by trying the values 0 and 1:
| Rule | Constraint |
|---|---|
| fund B only if A is funded (B requires A) | |
| not both A and B (A excludes B) | |
| exactly one of A and B | |
| at least one of A, B, C | |
| at most two of A, B, C | |
| A and B together or not at all |
For example, : if A is not funded () then must be 0; if A is funded, B is free. Here the app and the delivery link require the POS system, and the second roaster (P4) and the cold-brew line (P5) need the same floor space at the roastery. The function below builds the model with these rules from the two columns, for any budget. It also has a cat argument, which we use in section 3.
def capital_budget(budget, cat="Binary"):
"""Best projects within the budget, with the requires/excludes rules. Returns (NPV, x as a Series)."""
m = pulp.LpProblem("capital_budgeting", pulp.LpMaximize)
x = m.add_variable_dicts("fund", cost.index, lowBound=0, upBound=1, cat=cat)
m += pulp.lpSum(npv[p] * x[p] for p in cost.index)
m += pulp.lpSum(cost[p] * x[p] for p in cost.index) <= float(budget) # float(): PuLP 4 refuses a NumPy integer after <= or >=
for _, row in projects.iterrows():
if row["requires"]:
m += x[row["project"]] <= x[row["requires"]] # B requires A: x_B <= x_A
if row["excludes"]:
m += x[row["project"]] + x[row["excludes"]] <= 1 # not both (each pair appears twice: harmless)
res = m.solve(pulp.HiGHS(msg=False))
return pulp.value(m.objective), pd.Series({p: x[p].value() for p in cost.index})
best_npv, best_x = capital_budget(1000)
plan = list(best_x[best_x > 0.5].index)
print(f"NPV {best_npv:,.0f} k SAR | cost {cost[plan].sum():,} k SAR | plan {plan}")
projects[projects["project"].isin(plan)][["project", "name", "cost_ksar", "npv_ksar"]]NPV 1,200 k SAR | cost 1,000 k SAR | plan ['P1', 'P2', 'P3', 'P5', 'P10']
The best feasible plan funds the POS system, the app, the delivery link, the cold-brew line and the barista academy: an NPV of 1,200 k SAR, and it spends the budget to the last riyal. The rules cost 100 k SAR of NPV compared with the impossible plan, which is the price of being realistic.
3. Why not solve the LP and round?¶
If we drop the requirement that be 0 or 1 and only ask , we get an ordinary LP: the LP relaxation. It is fast to solve. Can we solve it and round the answer?
lp_npv, lp_x = capital_budget(1000, cat="Continuous")
print(f"LP relaxation: NPV {lp_npv:,.2f} k SAR")
lp_x[lp_x > 1e-6].round(3)LP relaxation: NPV 1,229.26 k SAR
P1 0.741
P2 0.741
P3 0.741
P5 1.000
P6 1.000
dtype: float64The LP funds 74.1% of the POS system, of the app and of the delivery link. Nobody can buy three quarters of a POS system. Both ways of rounding fail:
down = list(lp_x[lp_x > 1 - 1e-6].index) # keep only the projects the LP funds fully
up = list(lp_x[lp_x > 1e-6].index) # fund every project the LP funds at all
print(f"round down {down}: cost {cost[down].sum():,}, NPV {npv[down].sum():,} k SAR ({npv[down].sum() / best_npv - 1:.0%} against the best plan)")
print(f"round up {up}: cost {cost[up].sum():,} k SAR, over the budget")round down ['P5', 'P6']: cost 600, NPV 770 k SAR (-36% against the best plan)
round up ['P1', 'P2', 'P3', 'P5', 'P6']: cost 1,140 k SAR, over the budget
Rounding down keeps only the cold-brew line and the drive-through lane: 770 k SAR of NPV, 36% less than the best plan, with 400 k SAR of budget left unspent.
Rounding up costs 1,140 k SAR: over budget, infeasible.
The best integer plan (1,200) is neither: it drops the drive-through lane and adds the barista academy. No rounding of the LP finds it.
The LP is still useful: its value is an upper bound. No integer plan can beat 1,229 k SAR, because every integer plan is also a solution of the LP. Solvers such as HiGHS use this in branch and bound: solve the LP; if a variable is fractional, split the problem in two (that variable = 0, that variable = 1) and solve each half; drop any half whose LP bound is already below the best integer plan found so far. With 10 projects there are only plans and we could try them all, but with 50 projects there are more than 1015, and branch and bound still finds the best one in seconds.
4. One riyal can change the whole plan¶
In an LP a small change in the budget moves the solution a little, and the shadow price says how much each riyal is worth (Week 10). Integer models are different. Solve again with one riyal less, 999.999 k SAR:
less_npv, less_x = capital_budget(999.999)
plan_less = list(less_x[less_x > 0.5].index)
print(f"budget 1,000.000: {plan} NPV {best_npv:,.0f}")
print(f"budget 999.999: {plan_less} NPV {less_npv:,.0f}")
print("projects in both plans:", sorted(set(plan) & set(plan_less)) or "none")budget 1,000.000: ['P1', 'P2', 'P3', 'P5', 'P10'] NPV 1,200
budget 999.999: ['P4', 'P6', 'P9'] NPV 1,170
projects in both plans: none
With one riyal less, the best plan funds the second roaster, the drive-through lane and the bakery ovens: not a single project in common with the 1,000 k SAR plan, for only 30 k SAR less NPV. The best plan spent exactly 1,000 k SAR, so one riyal less makes it unaffordable, and the next best combination is built from different pieces. The chart shows the best NPV for every budget from 600 to 1,400 k SAR: it climbs in steps, not along a smooth line, so integer models have no shadow prices. To answer “what if the budget changes?”, solve the model again for each budget.
budgets = np.arange(600, 1401, 10)
best_by_budget = [capital_budget(b)[0] for b in budgets]
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.step(budgets, best_by_budget, where="post", color="#1f6f8b", lw=2.5)
ax.axvline(1000, color="#e07b39", ls="--")
ax.annotate("1,000 k SAR: NPV 1,200", (1000, 1200), xytext=(1040, 1010), color="#e07b39",
arrowprops=dict(arrowstyle="->", color="#e07b39"))
ax.set_xlabel("capital budget (k SAR)")
ax.set_ylabel("best NPV (k SAR)")
ax.set_title("The best plan for every budget")
plt.tight_layout()
plt.show()
Rules of thumb. Without a solver, a manager might fund projects in order of NPV, or in order of NPV per riyal, skipping any project that breaks the budget or a rule. Both rules miss the best plan:
def rule_of_thumb(order, budget=1000):
"""Go down the list; fund a project if it fits the budget and the rules allow it."""
funded = []
for p in order:
row = projects.set_index("project").loc[p]
fits = cost[funded].sum() + cost[p] <= budget
allowed = (not row["requires"] or row["requires"] in funded) and row["excludes"] not in funded
if fits and allowed:
funded.append(p)
return funded
for label, order in [("highest NPV first", npv.sort_values(ascending=False).index),
("highest NPV per riyal first", (npv / cost).sort_values(ascending=False).index)]:
f = rule_of_thumb(order)
print(f"{label:28s} {f} cost {cost[f].sum():,} NPV {npv[f].sum():,}")
print(f"{'integer model':28s} {plan} cost {cost[plan].sum():,} NPV {best_npv:,.0f}")highest NPV first ['P4', 'P6', 'P9'] cost 960 NPV 1,170
highest NPV per riyal first ['P5', 'P6', 'P9', 'P10'] cost 950 NPV 1,160
integer model ['P1', 'P2', 'P3', 'P5', 'P10'] cost 1,000 NPV 1,200
NPV per riyal looks like the smart rule, but it never funds the app or the delivery link, the two best projects per riyal, because their prerequisite, the POS system, has the worst ratio of all. Only a model that sees the projects together finds that the package of three is worth it.
5. Set covering: where to open kiosks¶
Qahwa House wants to open drive-through kiosks in north Riyadh. Eight candidate sites on main roads are available, and the promise to customers is: a kiosk within 10 minutes’ drive of every one of the twelve districts. The file has one row per (site, district) pair:
| Column | Meaning |
|---|---|
site | a candidate kiosk site, named after its road |
yearly_cost_ksar | the yearly cost of running a kiosk there: rent, staff and the fit-out spread over its life (k SAR) |
capacity_cups | the most cups a day the kiosk can serve |
district, district_cups | a district and the cups a day its residents would buy at a kiosk within reach |
minutes | driving time from the district to the site |
The names set the scene; the times, costs and demands are invented. A pivot turns the pairs into a site × district table, and a comparison gives the coverage matrix: which site reaches which district within 10 minutes.
minutes = sites.pivot(index="site", columns="district", values="minutes")
site_cost = sites.groupby("site")["yearly_cost_ksar"].first()
covers = minutes <= 10 # True when the site reaches the district within 10 minutes
table = covers.replace({True: "✓", False: ""})
table.insert(0, "cost", site_cost)
table["districts"] = covers.sum(axis=1)
tableEach column must have at least one open site with a ✓. With if site is opened, the set-covering model is
One “at least one” constraint per district: the logical rule from section 2, written for twelve districts.
def cheapest_cover(covers, must_open=()):
"""Cheapest set of sites that reaches every district. Returns (status, yearly cost, sites)."""
m = pulp.LpProblem("set_covering", pulp.LpMinimize)
y = m.add_variable_dicts("open", covers.index, cat="Binary")
m += pulp.lpSum(site_cost[s] * y[s] for s in covers.index)
for d in covers.columns:
m += pulp.lpSum(y[s] for s in covers.index if covers.loc[s, d]) >= 1, f"reach_{d}"
for s in must_open:
m += y[s] == 1
res = m.solve(pulp.HiGHS(msg=False))
return res.status.name, pulp.value(m.objective), [s for s in covers.index if y[s].value() > 0.5]
status, cover_cost, cover_sites = cheapest_cover(covers)
print(status, f"| {cover_cost:,.0f} k SAR a year |", cover_sites)Optimal | 1,870 k SAR a year | ['Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd']
Three kiosks reach every district within 10 minutes, for 1,870 k SAR a year. A natural rule of thumb starts elsewhere: open first a site that reaches the most districts (three sites reach six each, and Abu Bakr Rd is the cheapest of them), then fill the gaps. Forcing Abu Bakr Rd into the plan shows what that rule costs:
status, forced_cost, forced_sites = cheapest_cover(covers, must_open=["Abu Bakr Rd"])
print(status, f"| {forced_cost:,.0f} k SAR a year |", forced_sites)
print(f"extra cost of starting with Abu Bakr Rd: {forced_cost - cover_cost:,.0f} k SAR a year ({forced_cost / cover_cost - 1:.0%})")Optimal | 2,340 k SAR a year | ['Abu Bakr Rd', 'Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd']
extra cost of starting with Abu Bakr Rd: 470 k SAR a year (25%)
Four kiosks instead of three, and 470 k SAR a year more (+25%): the districts Abu Bakr Rd reaches are mostly reached by the other sites anyway. What matters is how the sites complement each other, which a model sees and a ranking does not.
6. Fixed costs and the big-M link¶
Covering every district is one goal. The board also asks: which kiosks would earn the most? A kiosk earns a margin of about 6 SAR a cup, 360 days a year, so each cup a day sold all year is worth SAR = 2.16 k SAR a year. But a kiosk only earns once it is open, and opening it costs its full yearly cost, however few cups it sells: a fixed cost.
The model has two kinds of variables:
: open site or not;
: cups a day that customers from district buy at kiosk (only for pairs within 10 minutes).
subject to
demand: for every district: a district buys no more than its demand;
capacity and link: for every site.
The last constraint does two jobs. If the site is open () it is the capacity limit; if it is closed () it forces every to 0. This is the big-M pattern: , where is a number at least as large as could ever be. Here the capacity is a natural . (Any larger number works too, but a tight helps the solver.) To see why the link matters, solve the model with and without it:
capacity = sites.groupby("site")["capacity_cups"].first()
demand = sites.groupby("district")["district_cups"].first()
MARGIN = 6 * 360 / 1000 # k SAR a year for each cup a day
def kiosk_plan(link=True, reach_all=False):
"""Most profitable kiosks. Returns (yearly profit in k SAR, open sites, cups a day served per district)."""
m = pulp.LpProblem("kiosks", pulp.LpMaximize)
y = m.add_variable_dicts("open", covers.index, cat="Binary")
pairs = [(s, d) for s in covers.index for d in covers.columns if covers.loc[s, d]]
x = m.add_variable_dicts("cups", pairs, lowBound=0)
m += MARGIN * pulp.lpSum(x.values()) - pulp.lpSum(site_cost[s] * y[s] for s in covers.index)
for d in covers.columns: # demand of each district
m += pulp.lpSum(x[s, d] for s in covers.index if (s, d) in x) <= float(demand[d])
for s in covers.index: # capacity, and the big-M link
m += pulp.lpSum(x[s, d] for d in covers.columns if (s, d) in x) <= float(capacity[s]) * (y[s] if link else 1)
if reach_all: # optional: the 10-minute promise
for d in covers.columns:
m += pulp.lpSum(y[s] for s in covers.index if covers.loc[s, d]) >= 1
res = m.solve(pulp.HiGHS(msg=False))
served = pd.Series({d: sum(x[s, d].value() for s in covers.index if (s, d) in x) for d in covers.columns})
return pulp.value(m.objective), [s for s in covers.index if y[s].value() > 0.5], served
p, opened, _ = kiosk_plan(link=False)
print(f"without the link: profit {p:,.1f} k SAR a year, kiosks opened: {opened}")
profit, open_sites, served = kiosk_plan()
print(f"with the link: profit {profit:,.1f} k SAR a year, kiosks opened: {open_sites}")without the link: profit 4,190.4 k SAR a year, kiosks opened: []
with the link: profit 2,070.0 k SAR a year, kiosks opened: ['Abu Bakr Rd', 'Imam Saud Rd', 'King Fahd Rd']
Without the link the model opens no kiosk at all and still sells 1,940 cups a day: 4,190 k SAR a year from kiosks that do not exist. With the link it opens three kiosks, King Fahd Rd, Abu Bakr Rd and Imam Saud Rd, for a profit of 2,070 k SAR a year. That is not the set-covering plan: Abu Bakr Rd sells many cups, while Anas Ibn Malik Rd mainly adds coverage. Which districts are served?
pd.DataFrame({"demand (cups a day)": demand, "served": served.round(0)}).astype(int)Al Mursalat (80 cups a day) is not served at all: no open kiosk reaches it within 10 minutes, and opening one for it does not pay. Another 180 cups a day go unserved in districts that only full kiosks reach: the rows above where served is below demand. Which districts carry that shortfall is not unique. Other plans that are just as profitable move it to neighbouring districts (another solver, or another version of HiGHS, may show Al Narjis and Al Sahafa instead); the profit, the open kiosks and the 180 cups stay the same.
7. The price of a promise¶
The 10-minute promise and the profit goal disagree. Adding the twelve “at least one” constraints of section 5 to the profit model gives the best plan that keeps the promise:
profit_all, open_all, served_all = kiosk_plan(reach_all=True)
print(f"keep the promise: profit {profit_all:,.1f} k SAR a year, kiosks {open_all}")
print(f"price of the promise: {profit - profit_all:,.1f} k SAR of profit a year")keep the promise: profit 1,850.4 k SAR a year, kiosks ['Abu Bakr Rd', 'Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd']
price of the promise: 219.6 k SAR of profit a year
Keeping the promise means a fourth kiosk, Anas Ibn Malik Rd, and 219.6 k SAR less profit a year: that is what serving Al Mursalat’s 80 cups a day costs. Whether the promise is worth it is a decision for the board (brand, a competitor about to open there, future growth of the district). The model’s job is to put a price on it.
8. A nonlinear model: spreading the cash reserve¶
Qahwa House keeps a cash reserve of 2 million SAR for the next two to three years. The finance team considers four funds. Their estimates of the yearly return, its volatility (standard deviation) and the correlations between funds are invented for this example and are not market forecasts:
| Fund | Expected return | Volatility |
|---|---|---|
| Sukuk fund | 5.0% | 2% |
| Saudi equity fund | 10.0% | 20% |
| Real-estate fund | 7.5% | 14% |
| Gold | 6.0% | 15% |
The expected return of a mix with weights is linear, , but its risk is not: the variance is , a quadratic function of the weights, where is the covariance of funds and . PuLP handles only linear models, so we use scipy.optimize.minimize with the SLSQP method, which accepts a nonlinear objective and constraints. The model: minimise the variance, subject to an expected return of at least the target, weights that add up to 1, and no negative weights (no borrowing).
from scipy.optimize import minimize
funds = ["Sukuk fund", "Saudi equity fund", "Real-estate fund", "Gold"]
mu = np.array([0.05, 0.10, 0.075, 0.06]) # expected yearly return
vol = np.array([0.02, 0.20, 0.14, 0.15]) # volatility (standard deviation)
corr = np.array([[1.0, 0.1, 0.2, 0.1],
[0.1, 1.0, 0.6, 0.0],
[0.2, 0.6, 1.0, 0.1],
[0.1, 0.0, 0.1, 1.0]])
cov = np.outer(vol, vol) * corr # covariance matrix
def min_risk(target):
"""Weights with the lowest volatility whose expected return is at least the target."""
constraints = [{"type": "eq", "fun": lambda w: w.sum() - 1},
{"type": "ineq", "fun": lambda w: w @ mu - target}]
res = minimize(lambda w: w @ cov @ w, x0=np.full(4, 0.25), method="SLSQP",
bounds=[(0, 1)] * 4, constraints=constraints, options={"ftol": 1e-12})
return res.x, np.sqrt(res.fun)
w, risk = min_risk(0.075)
print(f"target 7.5%: volatility {risk:.1%} (the real-estate fund alone: 14.0%)")
pd.DataFrame({"weight": w.round(3), "SAR": (w * 2_000_000).round(-3).astype(int)}, index=funds)target 7.5%: volatility 9.7% (the real-estate fund alone: 14.0%)
To earn the same 7.5% as the real-estate fund, the mix carries a volatility of 9.7% instead of 14%: about 30% less risk for the same expected return. A third goes to sukuk, two fifths to equities, and the rest to real estate and gold, which move little with equities. Solving the model for every target return traces the efficient frontier: the least risk you must accept for each level of expected return.
targets = np.linspace(0.05, 0.10, 21)
frontier = [min_risk(t)[1] for t in targets]
fig, ax = plt.subplots(figsize=(6.4, 3.8))
ax.plot(frontier, targets, color="#1f6f8b", lw=2.5, label="best mix (efficient frontier)")
ax.scatter(vol, mu, color="#e07b39", zorder=3, label="one fund alone")
offsets = {"Sukuk fund": (8, 2, "left"), "Saudi equity fund": (-8, -4, "right"),
"Real-estate fund": (8, -4, "left"), "Gold": (8, -4, "left")}
for name, v, r in zip(funds, vol, mu):
dx, dy, ha = offsets[name]
ax.annotate(name, (v, r), xytext=(dx, dy), textcoords="offset points", fontsize=8, ha=ha, va="center")
ax.scatter([risk], [0.075], color="#1f6f8b", zorder=3)
ax.annotate(f"same 7.5% at {risk:.1%} risk", (risk, 0.075), xytext=(-8, 8), textcoords="offset points",
fontsize=8, ha="right", color="#1f6f8b")
ax.set_xlim(0, 0.22)
ax.set_ylim(0.045, 0.105)
ax.set_xlabel("volatility (risk)")
ax.set_ylabel("expected return")
ax.xaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
ax.yaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
ax.legend(loc="lower right", fontsize=8)
plt.tight_layout()
plt.show()
Every fund except the equity fund lies to the right of the frontier: some mix earns the same return with less risk. Two cautions about nonlinear models:
A nonlinear solver moves step by step from a starting point (
x0) and stops at a local optimum. This model is convex (the variance is a bowl-shaped function of the weights), so the local optimum is the global one. For non-convex models, try several starting points.The answer is only as good as the estimates. Returns and correlations are uncertain, and in a crisis correlations tend to rise. Week 14’s simulation is one way to test a plan against that.
Summary¶
Binary variables model yes-or-no decisions: fund a project, open a site. In PuLP,
cat="Binary".Logical rules are linear constraints on 0/1 variables: requires , not both , at least one .
Do not round an LP. Rounding down wasted 36% of the value here; rounding up broke the budget. The LP gives an upper bound, and branch and bound finds the true integer optimum.
Integer solutions jump. One riyal less budget gave a plan with no project in common, so re-solve for each scenario: there are no shadow prices.
A fixed cost needs a binary variable and a big-M link . Set covering asks for at least one chosen site per customer group. Adding a promise as constraints puts a price on it (219.6 k SAR a year here).
Nonlinear objectives such as portfolio risk need a nonlinear solver (
scipy.optimize.minimize). Diversifying cut the risk by about 30% at the same expected return.
Next week: decision analysis: payoff tables, decision trees, the value of information and attitudes to risk.