diff --git a/docs/cuopt/source/cuopt-python/convex/convex-examples.rst b/docs/cuopt/source/cuopt-python/convex/convex-examples.rst index f7715db530..6561f03be4 100644 --- a/docs/cuopt/source/cuopt-python/convex/convex-examples.rst +++ b/docs/cuopt/source/cuopt-python/convex/convex-examples.rst @@ -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 ` + +.. 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 ` + +.. 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. diff --git a/docs/cuopt/source/cuopt-python/convex/examples/multi_period_planning_example.py b/docs/cuopt/source/cuopt-python/convex/examples/multi_period_planning_example.py new file mode 100644 index 0000000000..e6fea814c1 --- /dev/null +++ b/docs/cuopt/source/cuopt-python/convex/examples/multi_period_planning_example.py @@ -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}") diff --git a/docs/cuopt/source/cuopt-python/convex/examples/transportation_example.py b/docs/cuopt/source/cuopt-python/convex/examples/transportation_example.py new file mode 100644 index 0000000000..73556b5f09 --- /dev/null +++ b/docs/cuopt/source/cuopt-python/convex/examples/transportation_example.py @@ -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()}") diff --git a/docs/cuopt/source/cuopt-python/mip/examples/facility_location_example.py b/docs/cuopt/source/cuopt-python/mip/examples/facility_location_example.py new file mode 100644 index 0000000000..f39f3defab --- /dev/null +++ b/docs/cuopt/source/cuopt-python/mip/examples/facility_location_example.py @@ -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}") diff --git a/docs/cuopt/source/cuopt-python/mip/mip-examples.rst b/docs/cuopt/source/cuopt-python/mip/mip-examples.rst index e44695bdcf..ceaae412ea 100644 --- a/docs/cuopt/source/cuopt-python/mip/mip-examples.rst +++ b/docs/cuopt/source/cuopt-python/mip/mip-examples.rst @@ -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 ` + +.. 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 diff --git a/docs/cuopt/source/faq.rst b/docs/cuopt/source/faq.rst index be828ff77c..d2f7a03986 100644 --- a/docs/cuopt/source/faq.rst +++ b/docs/cuopt/source/faq.rst @@ -475,6 +475,57 @@ Mixed Integer Programming FAQs - On a H100 SXM with 80GB memory, this is the biggest dataset that was tested: - 27 million non-zeros coefficients on a problem from MIPLIB2017. +Common Pitfalls (LP, MILP, and QP) +-------------------------------------- + +Behaviours that fail quietly: a confident, feasible-looking result, or a status that reads as a solver problem rather than a usage error. + +.. dropdown:: Why does my solve return ``NoTermination`` with an objective value of ``nan``? + + The model has no constraints. A problem expressed only with variable bounds is not solved: the status comes back as ``NoTermination`` and ``ObjValue`` is ``nan``, rather than an objective value. + + Express at least one constraint explicitly with ``addConstraint``. A bound such as ``ub=100`` on a variable is not a constraint for this purpose. + +.. dropdown:: Why does my quadratic objective return ``NumericalError``? + + Quadratic objectives are **MINIMIZE-only**. Setting one with ``MAXIMIZE`` does not raise an error: the solve returns status ``NumericalError`` with an objective value of ``0.0``, which looks like a numerical problem rather than an unsupported option. + + To maximize ``f(x)``, minimize ``-f(x)`` and negate the reported objective value: + + .. code-block:: python + + problem.setObjective(-expression, sense=MINIMIZE) + # ... + maximum = -problem.ObjValue + + Quadratic objectives also require continuous variables; integer QP is not supported. + +.. dropdown:: Why does my status check never match, even though the solve succeeded? + + Termination status names are PascalCase, not uppercase. ``problem.Status.name`` returns ``Optimal``, ``PrimalFeasible``, ``NoTermination`` and so on, so a comparison against ``"OPTIMAL"`` silently never matches and a solved model reads as a failure. + + .. code-block:: python + + if problem.Status.name in ["Optimal", "PrimalFeasible"]: # LP / QP + print(problem.ObjValue) + + For MIP, the equivalent check is ``["Optimal", "FeasibleFound"]``. + +.. dropdown:: Why do I get an ``AttributeError`` reading a variable's name or value? + + The accessors are ``getVariableName()`` and ``getValue()``. There is no ``getName()`` and no ``.name`` attribute; both raise ``AttributeError``. + + .. code-block:: python + + for variable in problem.getVariables(): + print(variable.getVariableName(), variable.getValue()) + + Other variable accessors are ``getLowerBound()``, ``getUpperBound()``, ``getVariableType()``, ``getIndex()`` and ``ReducedCost``. + +.. dropdown:: Why are the dual values ``NaN``? + + Duals and reduced costs are available for LP and QP only. A MIP solve has no duals, since an integer optimum is not a continuous one. In addition, a model containing quadratic constraints returns ``NaN`` duals even for LP and QP. + Container FAQs ------------------------------