# Linear programming for microgrids with PuLP

> How to allocate limited renewable power across loads with linear programming in Python and PuLP, so emergency loads are always served first. Based on CivicGrid-AI.

**Linear programming** finds the best values for a set of decisions when the goal and every rule can be written as straight-line (linear) equations. It is a natural fit for a microgrid: decide how much power each load gets, subject to how much power exists. This is the core of [CivicGrid-AI](/work/civicgrid-ai/).

## The problem

Suppose the next hour's forecast says the grid will have **120 kW**. Loads want:

| Load | Demand (kW) | Priority |
|---|---|---|
| Clinic | 40 | Must be served |
| Emergency lighting | 15 | Must be served |
| Streetlights | 50 | Important |
| EV chargers | 60 | Nice to have |

## Write it as a model

- **Decision variables:** power given to each load, between 0 and its demand.
- **Constraint:** total power given cannot exceed the 120 kW available.
- **Hard rule:** life-safety loads get 100% of their demand.
- **Objective:** maximize weighted power served, with higher weights for more important loads.

## The code

```python
from pulp import LpProblem, LpVariable, LpMaximize, lpSum, PULP_CBC_CMD, LpStatus

supply = 120
loads = {
    "clinic":       {"demand": 40, "weight": 100, "critical": True},
    "emergency":    {"demand": 15, "weight": 100, "critical": True},
    "streetlights": {"demand": 50, "weight": 10,  "critical": False},
    "ev_chargers":  {"demand": 60, "weight": 1,   "critical": False},
}

model = LpProblem("microgrid", LpMaximize)
power = {name: LpVariable(name, 0, load["demand"]) for name, load in loads.items()}

model += lpSum(load["weight"] * power[name] for name, load in loads.items())
model += lpSum(power.values()) <= supply

for name, load in loads.items():
    if load["critical"]:
        model += power[name] == load["demand"]

model.solve(PULP_CBC_CMD(msg=False))
print(LpStatus[model.status])
for name in loads:
    print(name, power[name].value())
```

Result: clinic 40, emergency lighting 15, streetlights 50, EV chargers 15. The weights make the solver fill streetlights before chargers.

## When supply is too low

If supply falls below the critical demand (say 50 kW), the model above becomes **infeasible**: no solution meets every hard rule. Always check `LpStatus[model.status]`. A good fallback is to run a second model that serves critical loads in priority order and raises an alert, rather than silently failing.

## Where forecasts come in

CivicGrid-AI does not know supply in advance. Regression models forecast solar output and power from foot-traffic tiles for the next interval, and that forecast becomes the `supply` value. Re-solving every interval keeps the plan current.
