|
| 1 | +--- |
| 2 | +jupyter: compass-python |
| 3 | +--- |
| 4 | + |
| 5 | +## Example in Python |
| 6 | + |
| 7 | +This example solves the economic dispatch problem with Pyomo and HiGHS. The reusable implementation lives in `examples/python/dispatch_model.py`; this section imports that script, defines a small generator fleet, and reports the least-cost dispatch. |
| 8 | + |
| 9 | +```{python} |
| 10 | +from pathlib import Path |
| 11 | +import sys |
| 12 | +
|
| 13 | +for project_root in [Path.cwd(), *Path.cwd().parents]: |
| 14 | + examples_dir = project_root / "examples" / "python" |
| 15 | + if (examples_dir / "dispatch_model.py").exists(): |
| 16 | + sys.path.insert(0, str(examples_dir)) |
| 17 | + break |
| 18 | +else: |
| 19 | + raise FileNotFoundError("Could not find examples/python/dispatch_model.py") |
| 20 | +
|
| 21 | +from dispatch_model import Generator, merit_order_dispatch, total_cost |
| 22 | +``` |
| 23 | + |
| 24 | +The generator data include a zero-marginal-cost wind unit, a low-cost solar unit, and a gas unit that covers the remaining demand. |
| 25 | + |
| 26 | +```{python} |
| 27 | +generators = [ |
| 28 | + Generator("wind", marginal_cost=0.0, capacity=35.0), |
| 29 | + Generator("solar", marginal_cost=3.0, capacity=25.0), |
| 30 | + Generator("gas", marginal_cost=75.0, capacity=60.0), |
| 31 | +] |
| 32 | +
|
| 33 | +demand = 80.0 |
| 34 | +``` |
| 35 | + |
| 36 | +The solver chooses generation from the cheapest available units first, while enforcing the demand balance and each unit's capacity limit. |
| 37 | + |
| 38 | +```{python} |
| 39 | +dispatch = merit_order_dispatch(demand, generators) |
| 40 | +cost = total_cost(dispatch, generators) |
| 41 | +
|
| 42 | +dispatch, cost |
| 43 | +``` |
| 44 | + |
| 45 | +The solution uses all available wind and solar output, then dispatches gas for the remaining demand. |
| 46 | + |
| 47 | +```{python} |
| 48 | +for generator_name, output in dispatch: |
| 49 | + print(f"{generator_name}: {output:.1f} MW") |
| 50 | +
|
| 51 | +print(f"Total cost: {cost:.2f}") |
| 52 | +``` |
| 53 | + |
| 54 | +If demand exceeds total available capacity, the model is infeasible and the example raises a clear error. |
| 55 | + |
| 56 | +```{python} |
| 57 | +try: |
| 58 | + merit_order_dispatch(200.0, generators) |
| 59 | +except ValueError as error: |
| 60 | + print(error) |
| 61 | +``` |
0 commit comments