Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Integer and Nonlinear Models

Open In Colab

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().

Loading...

The decisions

Qahwa House’s board has three expansion decisions to make this year.

  1. 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).

  2. 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.

  3. 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:

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 xpx_p that is 1 if we fund project pp and 0 if we do not. Then the total NPV and the total cost are linear in the xpx_p:

max⁡∑pNPVp xpsubject to∑pcostp xp≤1000,xp∈{0,1}.\max \sum_p \text{NPV}_p \, x_p \quad \text{subject to} \quad \sum_p \text{cost}_p \, x_p \le 1000, \qquad x_p \in \{0, 1\}.

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:

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
Loading...

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:

RuleConstraint
fund B only if A is funded (B requires A)xB≤xAx_B \le x_A
not both A and B (A excludes B)xA+xB≤1x_A + x_B \le 1
exactly one of A and BxA+xB=1x_A + x_B = 1
at least one of A, B, CxA+xB+xC≥1x_A + x_B + x_C \ge 1
at most two of A, B, CxA+xB+xC≤2x_A + x_B + x_C \le 2
A and B together or not at allxA=xBx_A = x_B

For example, xB≤xAx_B \le x_A: if A is not funded (xA=0x_A = 0) then xBx_B 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.

NPV 1,200 k SAR | cost 1,000 k SAR | plan ['P1', 'P2', 'P3', 'P5', 'P10']
Loading...

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 xpx_p be 0 or 1 and only ask 0≤xp≤10 \le x_p \le 1, we get an ordinary LP: the LP relaxation. It is fast to solve. Can we solve it and round the answer?

LP relaxation: NPV 1,229.26 k SAR
P1 0.741 P2 0.741 P3 0.741 P5 1.000 P6 1.000 dtype: float64

The 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:

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 210=1,0242^{10} = 1{,}024 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:

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.

<Figure size 700x340 with 1 Axes>

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:

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:

ColumnMeaning
sitea candidate kiosk site, named after its road
yearly_cost_ksarthe yearly cost of running a kiosk there: rent, staff and the fit-out spread over its life (k SAR)
capacity_cupsthe most cups a day the kiosk can serve
district, district_cupsa district and the cups a day its residents would buy at a kiosk within reach
minutesdriving 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.

Loading...

Each column must have at least one open site with a ✓. With ys=1y_s = 1 if site ss is opened, the set-covering model is

min⁡∑scosts yssubject to∑s reaches dys≥1 for every district d,ys∈{0,1}.\min \sum_s \text{cost}_s \, y_s \quad \text{subject to} \quad \sum_{s \text{ reaches } d} y_s \ge 1 \ \text{for every district } d, \qquad y_s \in \{0, 1\}.

One “at least one” constraint per district: the logical rule from section 2, written for twelve districts.

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:

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.

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 6×360=2,1606 \times 360 = 2{,}160 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:

  • ys∈{0,1}y_s \in \{0, 1\}: open site ss or not;

  • xsd≥0x_{sd} \ge 0: cups a day that customers from district dd buy at kiosk ss (only for pairs within 10 minutes).

max⁡ 2.16∑s,dxsd−∑scosts ys\max \ 2.16 \sum_{s,d} x_{sd} - \sum_s \text{cost}_s \, y_s

subject to

  • demand: ∑sxsd≤cupsd\sum_s x_{sd} \le \text{cups}_d for every district: a district buys no more than its demand;

  • capacity and link: ∑dxsd≤capacitys ys\sum_d x_{sd} \le \text{capacity}_s \, y_s for every site.

The last constraint does two jobs. If the site is open (ys=1y_s = 1) it is the capacity limit; if it is closed (ys=0y_s = 0) it forces every xsdx_{sd} to 0. This is the big-M pattern: x≤Myx \le M y, where MM is a number at least as large as xx could ever be. Here the capacity is a natural MM. (Any larger number works too, but a tight MM helps the solver.) To see why the link matters, solve the model with and without it:

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?

Loading...

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:

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:

FundExpected returnVolatility
Sukuk fund5.0%2%
Saudi equity fund10.0%20%
Real-estate fund7.5%14%
Gold6.0%15%

The expected return of a mix with weights ww is linear, ∑iwiμi\sum_i w_i \mu_i, but its risk is not: the variance is w⊤Σw=∑i∑jwiwjσijw^\top \Sigma w = \sum_i \sum_j w_i w_j \sigma_{ij}, a quadratic function of the weights, where σij\sigma_{ij} is the covariance of funds ii and jj. 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).

target 7.5%: volatility 9.7% (the real-estate fund alone: 14.0%)
Loading...

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.

<Figure size 640x380 with 1 Axes>

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 xB≤xAx_B \le x_A, not both xA+xB≤1x_A + x_B \le 1, at least one ∑x≥1\sum x \ge 1.

  • 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 x≤Myx \le M y. 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.