Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions docs/cuopt/source/cuopt-python/convex/convex-examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,80 @@ Multi-GPU PDLP shards an LP across GPUs. Set the method to PDLP and ``CUOPT_NUM_
.. literalinclude:: examples/multi_gpu_pdlp_example.py
:language: python
:linenos:


Transportation Example (model built over index sets)
------------------------------------------------------

Most of the examples above declare a few variables by name. Larger models are
indexed over sets and built in loops: the variables live in a dictionary keyed by
the index tuple, and each constraint is accumulated with ``sum(...)`` before being
compared. ``addConstraint`` requires a comparison, so the expression has to be
compared in the call itself.

:download:`transportation_example.py <examples/transportation_example.py>`

.. literalinclude:: examples/transportation_example.py
:language: python
:linenos:

The response is as follows:

.. code-block:: text

Status: Optimal
Total shipping cost: 150.0
plant 0 -> warehouse 0: 5.0
plant 0 -> warehouse 2: 15.0
plant 1 -> warehouse 0: 5.0
plant 1 -> warehouse 1: 25.0


Multi-Period Planning Example (inventory carried between periods)
-------------------------------------------------------------------

Constraints that link one period to the next need a boundary value for the first
period. A plain Python number mixes with variables in an expression, so the
boundary needs no special casing beyond a conditional.

:download:`multi_period_planning_example.py <examples/multi_period_planning_example.py>`

.. literalinclude:: examples/multi_period_planning_example.py
:language: python
:linenos:

The response is as follows:

.. code-block:: text

Status: Optimal
Total cost: 182.0
Period 0: make 12.0, inventory 2.0
Period 1: make 18.0, inventory 0.0
Period 2: make 15.0, inventory 0.0


Building Large Linear Expressions
-------------------------------------------------------------------

The examples above build expressions with ``sum(...)``, which is the clearest choice for the
handful of terms they contain. The cost matters at scale. Adding two expressions with ``+``
builds new variable and coefficient lists from both operands, so accumulating ``N`` terms one
at a time copies on the order of ``N^2 / 2`` entries; both ``sum(...)`` and
``expr = expr + term`` work this way.

For an expression with thousands of terms, build the two lists first and pass them to a single
``LinearExpression``. Its third argument, ``constant``, is required rather than optional:

.. code-block:: python

from cuopt.linear_programming.problem import LinearExpression

variables = [x[i] for i in range(n)]
coefficients = [cost[i] for i in range(n)]
expression = LinearExpression(variables, coefficients, 0.0)

``LinearExpression`` keeps a reference to the lists it is given rather than copying them, and
``+=`` extends them in place. That is what makes both forms fast, but it also means the
expression shares state with those lists and with any other expression built from them, so a
later ``+=`` modifies all of them at once. Pass lists that nothing else holds a reference to.
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""
Multi-Period Planning Example (inventory carried between periods)

Shows a model whose constraints link one period to the next. The balance
constraint refers to the previous period's inventory, so the first period
needs a boundary value -- a plain Python number mixes with variables in an
expression, so no special casing is needed beyond a conditional.

Problem:
Meet demand over 3 periods by producing and carrying inventory.

- Demand per period: [10, 20, 15]
- Production capacity per period: 18
- Production cost: 4.0 per unit
- Holding cost: 1.0 per unit carried

Expected Output:
Status: Optimal
Total cost: 182.0
Period 0: make 12.0, inventory 2.0
Period 1: make 18.0, inventory 0.0
Period 2: make 15.0, inventory 0.0
"""

from cuopt.linear_programming.problem import Problem, CONTINUOUS, MINIMIZE
from cuopt.linear_programming.solver_settings import SolverSettings

demand = [10.0, 20.0, 15.0]
production_capacity = 18.0
production_cost = 4.0
holding_cost = 1.0

periods = range(len(demand))

problem = Problem("multi_period_planning")

make = {
t: problem.addVariable(
lb=0, ub=production_capacity, vtype=CONTINUOUS, name=f"make_{t}"
)
for t in periods
}
inventory = {
t: problem.addVariable(lb=0, vtype=CONTINUOUS, name=f"inventory_{t}")
for t in periods
}

# Balance: previous inventory + production - demand == inventory.
# Opening stock is zero, so period 0 uses the plain number 0.0.
for t in periods:
previous = inventory[t - 1] if t > 0 else 0.0
problem.addConstraint(
previous + make[t] - demand[t] == inventory[t], name=f"balance_{t}"
)

problem.setObjective(
sum(
production_cost * make[t] + holding_cost * inventory[t]
for t in periods
),
sense=MINIMIZE,
)

problem.solve(SolverSettings())

print(f"Status: {problem.Status.name}")
if problem.Status.name in ["Optimal", "PrimalFeasible"]:
print(f"Total cost: {problem.ObjValue}")
for t in periods:
# Adding 0.0 normalises a -0.0 the solver may return at a bound.
made = round(make[t].getValue(), 6) + 0.0
held = round(inventory[t].getValue(), 6) + 0.0
print(f"Period {t}: make {made}, inventory {held}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""
Transportation Example (model built over index sets)

Most examples in this guide declare a handful of variables by name. Real models
are indexed over sets and built in loops. This example shows that shape:

- variables held in a dict keyed by the index tuple
- constraints accumulated with ``sum(...)`` over a generator, then compared

Problem:
Ship goods from 2 plants to 3 warehouses at least cost.

- Plant supply: [20, 30]
- Warehouse demand: [10, 25, 15]
- Unit shipping cost:
to W0 W1 W2
P0 2.0 3.0 1.0
P1 5.0 4.0 8.0

Expected Output:
Status: Optimal
Total shipping cost: 150.0
plant 0 -> warehouse 0: 5.0
plant 0 -> warehouse 2: 15.0
plant 1 -> warehouse 0: 5.0
plant 1 -> warehouse 1: 25.0
"""

from cuopt.linear_programming.problem import Problem, CONTINUOUS, MINIMIZE
from cuopt.linear_programming.solver_settings import SolverSettings

supply = [20.0, 30.0]
demand = [10.0, 25.0, 15.0]
cost = [[2.0, 3.0, 1.0],
[5.0, 4.0, 8.0]]

plants = range(len(supply))
warehouses = range(len(demand))

problem = Problem("transportation")

# Index the variables with a dict keyed by the index tuple.
ship = {
(p, w): problem.addVariable(lb=0, vtype=CONTINUOUS, name=f"ship_{p}_{w}")
for p in plants
for w in warehouses
}

# addConstraint needs a comparison. Accumulate the row expression with sum(),
# then compare it in the call -- passing a bare expression raises ValueError.
for p in plants:
problem.addConstraint(
sum(ship[p, w] for w in warehouses) <= supply[p], name=f"supply_{p}"
)

for w in warehouses:
problem.addConstraint(
sum(ship[p, w] for p in plants) >= demand[w], name=f"demand_{w}"
)

problem.setObjective(
sum(cost[p][w] * ship[p, w] for p in plants for w in warehouses),
sense=MINIMIZE,
)

settings = SolverSettings()
settings.set_parameter("time_limit", 60)
problem.solve(settings)

# Status values are PascalCase; "OPTIMAL" would never match.
print(f"Status: {problem.Status.name}")
if problem.Status.name in ["Optimal", "PrimalFeasible"]:
print(f"Total shipping cost: {problem.ObjValue}")
for (p, w), var in sorted(ship.items()):
if var.getValue() > 1e-6:
print(f" plant {p} -> warehouse {w}: {var.getValue()}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""
Facility Location Example (binary variables with linking constraints)

Shows the two things most MILP models need beyond a simple integer variable:

- a binary variable, expressed as INTEGER with lb=0 and ub=1
- a linking constraint tying a continuous quantity to a binary decision, so
that shipping from a facility forces that facility to be open

Problem:
Choose which facilities to open and how much to ship from each.

- Fixed cost to open: [100, 80]
- Capacity: [50, 50]
- Customer demand: [30, 20]
- Unit shipping cost:
to C0 C1
F0 4.0 6.0
F1 5.0 3.0

Expected Output:
Status: Optimal
Total cost: 290.0
Facility 0: closed
Facility 1: open
"""

from cuopt.linear_programming.problem import (
Problem,
CONTINUOUS,
INTEGER,
MINIMIZE,
)
from cuopt.linear_programming.solver_settings import SolverSettings

fixed_cost = [100.0, 80.0]
capacity = [50.0, 50.0]
demand = [30.0, 20.0]
ship_cost = [[4.0, 6.0],
[5.0, 3.0]]

facilities = range(len(fixed_cost))
customers = range(len(demand))

problem = Problem("facility_location")

# A binary variable is INTEGER with lb=0 and ub=1.
is_open = {
f: problem.addVariable(lb=0, ub=1, vtype=INTEGER, name=f"open_{f}")
for f in facilities
}
ship = {
(f, c): problem.addVariable(lb=0, vtype=CONTINUOUS, name=f"ship_{f}_{c}")
for f in facilities
for c in customers
}

for c in customers:
problem.addConstraint(
sum(ship[f, c] for f in facilities) >= demand[c], name=f"demand_{c}"
)

# Linking: a facility can ship only up to its capacity, and only if open.
for f in facilities:
problem.addConstraint(
sum(ship[f, c] for c in customers) <= capacity[f] * is_open[f],
name=f"link_{f}",
)

problem.setObjective(
sum(fixed_cost[f] * is_open[f] for f in facilities)
+ sum(
ship_cost[f][c] * ship[f, c] for f in facilities for c in customers
),
sense=MINIMIZE,
)

settings = SolverSettings()
settings.set_parameter("time_limit", 120)
settings.set_parameter("mip_relative_gap", 0.01)
problem.solve(settings)

print(f"Status: {problem.Status.name}")
if problem.Status.name in ["Optimal", "FeasibleFound"]:
print(f"Total cost: {problem.ObjValue}")
for f in facilities:
state = "open" if is_open[f].getValue() > 0.5 else "closed"
print(f"Facility {f}: {state}")
24 changes: 24 additions & 0 deletions docs/cuopt/source/cuopt-python/mip/mip-examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,27 @@ The response is as follows:
Final objective value: 303.00

Total incumbent solutions found: 1


Facility Location Example (binary variables with linking constraints)
---------------------------------------------------------------------

Models indexed over sets are usually built in loops, with the variables held in a
dictionary keyed by the index tuple. This example also shows a binary variable
(``INTEGER`` with ``lb=0`` and ``ub=1``) and a linking constraint that forces a
facility open before anything can ship from it.

:download:`facility_location_example.py <examples/facility_location_example.py>`

.. literalinclude:: examples/facility_location_example.py
:language: python
:linenos:

The response is as follows:

.. code-block:: text

Status: Optimal
Total cost: 290.0
Facility 0: closed
Facility 1: open
Loading
Loading