### Complete Warm Start Example Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_mip_start.md A full example demonstrating the warm-start functionality for a wedding seating problem. It includes setting up the model, assigning initial values, and solving with warm-start enabled. ```python """ A set partitioning model of a wedding seating problem Adaptation where an initial solution is given to solvers: CPLEX_CMD, GUROBI_CMD, COIN_CMD Authors: Stuart Mitchell 2009, Franco Peschiera 2019 """ from typing import Tuple, Union import pulp max_tables = 5 max_table_size = 4 guests = "A B C D E F G I J K L M N O P Q R".split() def happiness( table: Union[ Tuple[str], Tuple[str, str, str, str], Tuple[str, str], Tuple[str, str, str] ], ) -> int: """ Find the happiness of the table - by calculating the maximum distance between the letters """ return abs(ord(table[0]) - ord(table[-1])) # create list of all possible tables possible_tables = [tuple(c) for c in pulp.allcombinations(guests, max_table_size)] seating_model = pulp.LpProblem("Wedding Seating Model", pulp.LpMinimize) # create a binary variable to state that a table setting is used _table_keys = ["_".join(t) for t in possible_tables] vars_by_key = seating_model.add_variable_dict( "table_%s", (_table_keys,), 0, 1, pulp.LpInteger ) x = {t: vars_by_key["_".join(t)] for t in possible_tables} seating_model += pulp.lpSum([happiness(table) * x[table] for table in possible_tables]) # specify the maximum number of tables seating_model += ( pulp.lpSum([x[table] for table in possible_tables]) <= max_tables, "Maximum_number_of_tables", ) # A guest must seated at one and only one table for guest in guests: seating_model += ( pulp.lpSum([x[table] for table in possible_tables if guest in table]) == 1, f"Must_seat_{guest}", ) # I've taken the optimal solution from a previous solving. x is the variable dictionary. solution = { ("M", "N"): 1.0, ("E", "F", "G"): 1.0, ("A", "B", "C", "D"): 1.0, ("I", "J", "K", "L"): 1.0, ("O", "P", "Q", "R"): 1.0, } for k, v in solution.items(): x[k].setInitialValue(v) solver = pulp.COIN_CMD(msg=True, warmStart=True) # solver = pulp.CPLEX_CMD(msg=True, warmStart=True) # solver = pulp.GUROBI_CMD(msg=True, warmStart=True) # solver = pulp.CPLEX_PY(msg=True, warmStart=True) # solver = pulp.GUROBI(msg=True, warmStart=True) seating_model.solve(solver) print(f"The chosen tables are out of a total of {len(possible_tables)}:") for table in possible_tables: if x[table].value() == 1.0: print(table) ``` -------------------------------- ### Install PuLP and CBC using uv Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/installing_pulp_at_home.md An alternative installation method using 'uv' for installing PuLP and the CBC solver. This is a recommended approach for managing Python packages. ```bash uv pip install "pulp[cbc]" ``` -------------------------------- ### Install PuLP with CBC from GitHub Source: https://github.com/coin-or/pulp/blob/master/README.rst Installs the latest development version of PuLP, including the CBC solver, directly from its GitHub repository. ```bash python -m pip install -U "pulp[cbc] @ git+https://github.com/coin-or/pulp.git" ``` -------------------------------- ### Install All Open Source Solvers Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for all available open-source solvers including SCIP, HiGHS, and CBC. ```bash python -m pip install pulp[open_py] ``` -------------------------------- ### Install PuLP from Source with uv Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/installing_pulp_at_home.md Installs PuLP in editable mode from the source code using 'uv'. This command also installs development dependencies and the CBC extra, which is necessary for most tests and examples. ```bash uv venv uv pip install --group dev -e ".[cbc]" ``` -------------------------------- ### Install PuLP and CBC from PyPI Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/installing_pulp_at_home.md Recommended installation that includes PuLP and the CBC solver via the 'cbcbox' dependency. This ensures PuLP can automatically locate and use CBC. ```bash python -m pip install pulp[cbc] ``` -------------------------------- ### Install PuLP with COPT Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the COPT solver. Note that COPT may require a commercial license. ```bash python -m pip install pulp[copt] ``` -------------------------------- ### Install PuLP with Gurobi Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the Gurobi solver. Note that Gurobi may require a commercial license. ```bash python -m pip install pulp[gurobi] ``` -------------------------------- ### Install GUROBI Python Package (Linux) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Installs the GUROBI Python package from its installation directory. Requires administrator privileges. ```bash cd /opt/gurobi801/linux64/ sudo python3 setup.py install ``` -------------------------------- ### Install PuLP from Source with pip Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/installing_pulp_at_home.md Installs PuLP in editable mode from the source code using 'pip'. This involves creating a virtual environment, activating it, upgrading pip, and then installing the package with development dependencies and the CBC extra. ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate python -m pip install --upgrade pip python -m pip install -e ".[cbc]" ``` -------------------------------- ### Activate Warm Start When Solving Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_mip_start.md Pass the `warmStart=True` argument to the solver to enable warm-starting. This tells the solver to use the previously set initial values. ```python seating_model.solve(pulp.COIN_CMD(msg=True, warmStart=True)) ``` -------------------------------- ### Problem Setup and Parameter Initialization Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_two_stage_production_planning_problem.md Initializes the PuLP problem for maximization and sets up all necessary parameters and dictionaries for the gemstone optimization problem, including prices, capacities, and scenario data. ```python import pulp # parameters products = ["wrenches", "pliers"] price = [130, 100] steel = [1.5, 1] molding = [1, 1] assembly = [0.3, 0.5] capsteel = 27 capmolding = 21 LB = [0, 0] capacity_ub = [15, 16] steelprice = 58 scenarios = [0, 1, 2, 3] pscenario = [0.25, 0.25, 0.25, 0.25] wrenchearnings = [160, 160, 90, 90] plierearnings = [100, 100, 100, 100] capassembly = [8, 10, 8, 10] production = [(j, i) for j in scenarios for i in products] pricescenario = [[wrenchearnings[j], plierearnings[j]] for j in scenarios] priceitems = [item for sublist in pricescenario for item in sublist] # create dictionaries for the parameters price_dict = dict(zip(production, priceitems)) capacity_dict = dict(zip(products, capacity_ub * 4)) steel_dict = dict(zip(products, steel)) molding_dict = dict(zip(products, molding)) assembly_dict = dict(zip(products, assembly)) # Create the 'gemstoneprob' variable to specify gemstoneprob = pulp.LpProblem("The Gemstone Tool Problem", pulp.LpMaximize) ``` -------------------------------- ### Install PuLP with XPRESS Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the XPRESS solver. Note that XPRESS may require a commercial license. ```bash python -m pip install pulp[xpress] ``` -------------------------------- ### Install PuLP with MOSEK Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the MOSEK solver. Note that MOSEK may require a commercial license. ```bash python -m pip install pulp[mosek] ``` -------------------------------- ### Install PuLP with CYLP Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the CYLP solver. CYLP is a Python interface to CLP and CBC. ```bash python -m pip install pulp[cylp] ``` -------------------------------- ### Install PuLP with uv Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Install PuLP and its development dependencies in editable mode using uv. This command should be run from the pulp directory after creating a virtual environment. ```bash cd pulp uv venv uv pip install --group dev -e . ``` -------------------------------- ### Install PuLP with SCIP Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the SCIP solver. Note that SCIP may require a commercial license for certain uses. ```bash python -m pip install pulp[scip] ``` -------------------------------- ### Install PuLP with HiGHS Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the HiGHS solver. HiGHS is an open-source solver. ```bash python -m pip install pulp[highs] ``` -------------------------------- ### Install PuLP with CPLEX Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the CPLEX solver. Note that CPLEX may require a commercial license. ```bash python -m pip install pulp[cplex] ``` -------------------------------- ### Python range() Function Example Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Illustrates the use of the range() function to create a list of integers. The output shows the sequence generated by range(start, stop). ```python >>> range(3,8) [3,4,5,6,7] ``` -------------------------------- ### Install PuLP with Dev Dependencies using uv Source: https://github.com/coin-or/pulp/blob/master/README.rst Installs PuLP in editable mode with development dependencies, including CBC, using the uv package manager. ```bash uv venv uv pip install --group dev -e .[cbc] ``` -------------------------------- ### Install PuLP with OR-Tools Support Source: https://github.com/coin-or/pulp/blob/master/README.rst Install PuLP with support for the OR-Tools CP-SAT solver. This enables using Google's CP-SAT solver. ```bash python -m pip install pulp[ortools] ``` -------------------------------- ### Import PuLP and Define Problem Header Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_transportation_problem.md Start your Python file with a docstring and import necessary functions from the PuLP library. ```python """ The Beer Distribution Problem for the PuLP Modeller Authors: Antony Phillips, Dr Stuart Mitchell 2007 """ # Import PuLP modeler functions from pulp import * ``` -------------------------------- ### Transportation Problem Data Setup Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_transportation_problem.md Defines supply nodes, their capacities, demand nodes, their requirements, and the cost matrix for transporting goods between them. This setup is typical for a balanced transportation problem. ```python # Creates a list of all the supply nodes Warehouses = ["A", "B", "C"] # Creates a dictionary for the number of units of supply for each supply node supply = {"A": 1000, "B": 4000, "C": 100} # Creates a list of all demand nodes Bars = ["1", "2", "3", "4", "5"] # Creates a dictionary for the number of units of demand for each demand node demand = { "1": 500, "2": 900, "3": 1800, "4": 200, "5": 700, } # Creates a list of costs of each transportation path costs = [ # Bars # 1 2 3 4 5 [2, 4, 5, 2, 1], # A Warehouses [3, 1, 3, 2, 3], # B [0, 0, 0, 0, 0], ] ``` -------------------------------- ### Install PuLP with pip Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Install PuLP and its development dependencies in editable mode using pip. This command should be run from the pulp directory after creating and activating a virtual environment. ```bash cd pulp python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python3 -m pip install --upgrade pip pip install --group dev -e . ``` -------------------------------- ### Install XPRESS_PY via PIP Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Installs the Xpress Python package using pip. This package includes a runtime distribution and a Community License. ```bash pip install xpress ``` -------------------------------- ### Python for Loop Example Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Illustrates a for loop iterating through a list of strings, printing each element. The output shows the sequential processing of list items. ```python #The following code demonstrates a list with strings ingredientslist = ["Rice","Water","Jelly"] for i in ingredientslist: print i print "No longer in the loop" ``` -------------------------------- ### Install PuLP with Dev Dependencies using pip Source: https://github.com/coin-or/pulp/blob/master/README.rst Installs PuLP in editable mode with development dependencies, including CBC, using pip. Maturin is used automatically for the Rust extension. ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install --upgrade pip python -m pip install -e ".[cbc]" ``` -------------------------------- ### List All Available Solvers Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Use this function to get a list of all solvers that PuLP can potentially access on your system. ```python import pulp as pl solver_list = pl.listSolvers() print(solver_list) # ['GLPK_CMD', 'PYGLPK', 'CPLEX_CMD', 'CPLEX_PY', 'CPLEX_DLL', 'GUROBI', 'GUROBI_CMD', 'MOSEK', 'XPRESS', 'COIN_CMD', 'COINMP_DLL', 'CHOCO_CMD', 'MIPCL_CMD', 'SCIP_CMD', 'CPSAT', ...] ``` -------------------------------- ### MIPCL_CMD Solver Class Definition Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md This snippet shows the basic structure for defining a new solver class, inheriting from `LpSolver_CMD`. It includes initialization parameters and parent class setup. ```python from .core import LpSolver_CMD, subprocess, PulpSolverError import os from .. import constants import warnings class MIPCL_CMD(LpSolver_CMD): name = "MIPCL_CMD" def __init__( self, path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None, ): LpSolver_CMD.__init__( self, mip=mip, msg=msg, timeLimit=timeLimit, options=options, path=path, keepFiles=keepFiles, ) ``` -------------------------------- ### Get a Solver Object by Name Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Instantiate a solver object using its name. Additional arguments are passed to the solver's constructor, such as setting a time limit. ```python import pulp as pl solver = pl.getSolver('CPLEX_CMD') solver = pl.getSolver('CPLEX_CMD', timeLimit=10) ``` -------------------------------- ### Import PuLP Package Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_two_stage_production_planning_problem.md Import the PuLP library to begin modeling optimization problems. ```python import pulp ``` -------------------------------- ### Registering the New Solver in `__init__.py` Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md This snippet shows how to import the new solver class and add it to the `_all_solvers` list in `pulp/apis/__init__.py` to make it available to PuLP. ```python from .mipcl import MIPCL_CMD _all_solvers = [ # (...) MIPCL_CMD, ] ``` -------------------------------- ### Initialize CPLEX Solver using System PATH Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md This method relies on the CPLEX executable being discoverable via the system's PATH environment variable. It simplifies solver initialization by not requiring an explicit path. ```python import pulp as pl model = pl.LpProblem("Example", pl.LpMinimize) _var = model.add_variable('a') _var2 = model.add_variable('a2') solver = pl.CPLEX_CMD() model += _var + _var2 == 1 result = model.solve(solver) ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Build the HTML documentation for PuLP using Sphinx. Navigate to the 'doc' directory and run 'make html'. The output will be in 'doc/build/html/'. ```bash cd doc make html ``` -------------------------------- ### Define Ingredients and Costs Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_blending_problem.md Sets up the list of ingredients and their associated costs. This data forms the basis for the optimization problem. ```python Ingredients = ["CHICKEN", "BEEF", "MUTTON", "RICE", "WHEAT", "GEL"] costs = { "CHICKEN": 0.013, "BEEF": 0.008, "MUTTON": 0.010, "RICE": 0.002, "WHEAT": 0.005, "GEL": 0.001, } ``` -------------------------------- ### Install XPRESS_PY via Conda Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Installs the Xpress Python package using conda. This package includes a runtime distribution and a Community License. ```bash conda install -c fico-xpress xpress ``` -------------------------------- ### Initialize the LP Problem Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_transportation_problem.md Create the LP problem instance using LpProblem, specifying the problem name and optimization sense (minimize). ```python # Creates the 'prob' variable to contain the problem data prob = LpProblem("Beer Distribution Problem", LpMinimize) ``` -------------------------------- ### Create Production and Price Lists Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_two_stage_production_planning_problem.md Generate lists representing combinations of scenarios and products, and flatten scenario-specific prices into a single list for easier dictionary creation. ```python production = [(j, i) for j in scenarios for i in products] pricescenario = [[wrenchearnings[j], plierearnings[j]] for j in scenarios] priceitems = [item for sublist in pricescenario for item in sublist] ``` -------------------------------- ### Implementing the `actualSolve` Method Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md This method handles the core solving process for a given `LpProblem`. It prepares the problem, calls the solver executable, and processes the results. It includes handling maximization problems by minimizing the inverse objective and managing temporary files. ```python def actualSolve(self, lp): """Solve a well formulated lp problem""" if not self.executable(self.path): raise PulpSolverError("PuLP: cannot execute " + self.path) tmpMps, tmpSol = self.create_tmp_files(lp.name, "mps", "sol") if lp.sense == constants.LpMaximize: # we swap the objectives # because it does not handle maximization. warnings.warn( "MIPCL_CMD does not allow maximization, " "we will minimize the inverse of the objective function." ) lp += -lp.objective lp.checkDuplicateVars() lp.checkDuplicateConstraints() lp.checkLengthVars(52) lp.writeMPS(tmpMps, mpsSense=lp.sense) # just to report duplicated variables: try: os.remove(tmpSol) except: pass cmd = self.path cmd += " %s" % tmpMps cmd += " -solfile %s" % tmpSol if self.timeLimit is not None: cmd += " -time %s" % self.timeLimit for option in self.options: cmd += " " + option if lp.isMIP(): if not self.mip: warnings.warn("MIPCL_CMD cannot solve the relaxation of a problem") if self.msg: pipe = None else: pipe = open(os.devnull, "w") return_code = subprocess.call(cmd.split(), stdout=pipe, stderr=pipe) # We need to undo the objective swap before finishing if lp.sense == constants.LpMaximize: lp += -lp.objective if return_code != 0: raise PulpSolverError("PuLP: Error while trying to execute " + self.path) if not os.path.exists(tmpSol): status = constants.LpStatusNotSolved status_sol = constants.LpSolutionNoSolutionFound values = None else: status, values, status_sol = self.readsol(tmpSol) self.delete_tmp_files(tmpMps, tmpSol) lp.assignStatus(status, status_sol) if status not in [constants.LpStatusInfeasible, constants.LpStatusNotSolved]: lp.assignVarsVals(values) return status ``` -------------------------------- ### Instantiating and Using a Python Class Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Shows how to create an instance of a Python class and access both class variables and instance-specific data. Printing an instance calls the __str__ method, and calling a method like 'trim' executes its logic. ```python >>> a = Pattern("PatternA",[1,0,1]) >>> a.cost # a is now an instance of the Pattern class and is associated with Pattern class variables 1 >>> print a # This calls the Pattern.__str__() function "PatternA" >>> a.trim() # This calls the Pattern.trim() function. Note that no input is required. ``` -------------------------------- ### Get Variable Value After Solving Source: https://github.com/coin-or/pulp/blob/master/README.rst Retrieve the optimal value of a variable 'x' after the problem has been solved. ```python value(x) ``` -------------------------------- ### Get Variable Value Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/includeme.md Retrieves the optimal value of a specific variable (e.g., 'x') after the problem has been solved. ```python value(x) > 2.0 ``` -------------------------------- ### Get Variable Value After Solving Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_mip_start.md Retrieve the value of a variable after a model has been solved. This is useful for inspecting the results. ```python x[('O', 'P', 'Q', 'R')].value() # 1.0 x[('K', 'N', 'O', 'R')].value() # 0.0 ``` -------------------------------- ### Create LpProblem and Add Variables Source: https://github.com/coin-or/pulp/blob/master/doc/source/technical/pulp.md Instantiate an LpProblem and add variables with specified bounds and categories. Use this to define the decision variables for your optimization problem. ```python >>> prob = LpProblem("example", LpMinimize) >>> x = prob.add_variable('x', lowBound=0, cat='Continuous') >>> y = prob.add_variable('y', upBound=5, cat='Integer') ``` -------------------------------- ### Configure COIN-OR CBC Path Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md When using COIN_CMD, you can explicitly provide the path to the CBC executable if it's not found on your system's PATH. ```python import pulp as pl solver = pl.COIN_CMD(path=r"C:\\path\\to\\cbc.exe") ``` -------------------------------- ### Implementing the `defaultPath` Method Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md This method specifies the default executable path for a command-line solver. It is required by `LpSolver_CMD`. ```python def defaultPath(self): return self.executableExtension("mps_mipcl") ``` -------------------------------- ### Initialize CPLEX Solver with Explicit Path (Windows) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Use this method when you need to specify the exact location of the CPLEX executable. This is useful for one-off configurations or when the solver is not in the system's PATH. ```python path_to_cplex = r'C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64\cplex.exe' import pulp as pl model = pl.LpProblem("Example", pl.LpMinimize) _var = model.add_variable('a') _var2 = model.add_variable('a2') solver = pl.CPLEX_CMD(path=path_to_cplex) model += _var + _var2 == 1 result = model.solve(solver) ``` -------------------------------- ### Whiskas Model 1 Python File Header Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_blending_problem.md This comment block at the start of the Python file outlines the purpose of the program and provides author and date information. ```default """ The Simplified Whiskas Model Python Formulation for the PuLP Modeller Authors: Antony Phillips, Dr Stuart Mitchell 2007 """ ``` -------------------------------- ### Solve a PuLP Problem with Default Solver Source: https://github.com/coin-or/pulp/blob/master/README.rst Solve the defined PuLP problem using the default solver. This is typically CBC if installed with 'pulp[cbc]' or 'cbc' is on the PATH. ```python status = prob.solve() ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Stage, commit, and push your local changes to your forked repository. Use 'git status' to see changes, 'git add' to stage, 'git commit' to record, and 'git push' to upload. ```bash git status git add some_modified_file.py git commit -m "some message" git push origin ``` -------------------------------- ### Import Solver Configuration from JSON File Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Imports a PuLP solver configuration from a JSON file. This allows recreating a solver with previously saved settings. ```python import pulp solver = pulp.getSolverFromJson("some_file_name.json") ``` -------------------------------- ### Apply Ruff Linter and Formatter with uv Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Check and format the PuLP code using ruff. These commands should be run from the project root with the development environment activated. ```bash uv run ruff check pulp uv run ruff format pulp ``` -------------------------------- ### Python if-elif-else Statement Syntax Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Demonstrates the syntax for conditional execution using if, elif (else if), and else statements. The colon signifies the start of a block, and indentation marks its end. ```python if j in testlist: # some commands elif j == 5: # some commands else: # some commands ``` -------------------------------- ### Solve a PuLP Problem with OR-Tools CP-SAT Solver Source: https://github.com/coin-or/pulp/blob/master/README.rst Solve the PuLP problem using the OR-Tools CP-SAT solver. Ensure PuLP is installed with 'pulp[ortools]'. Continuous variables are solved on their integer-rounded domain. ```python from pulp import CPSAT status = prob.solve(CPSAT(msg=False)) ``` -------------------------------- ### Creating and Accessing Dictionary Elements Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Demonstrates how to create an empty dictionary, add key-value pairs, and access values using their keys. Keys can be of various types like integers or strings. ```python >>> x = {} >>> x[4] = "programming" >>> x["games"] = 12 >>> print x["games"] 12 ``` -------------------------------- ### Update Supply and Demand Data for Extended Model Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_transportation_problem.md Modifies the supply and demand dictionaries to include a dummy demand node ('D') and adjusts the total demand. This setup is used to model extensions such as handling excess supply by routing it to the dummy node. ```python # Creates a dictionary for the number of units of supply for each supply node supply = {"A": 1000, "B": 4000} # Creates a list of all demand nodes Bars = ["1", "2", "3", "4", "5", "D"] # Creates a dictionary for the number of units of demand for each demand node demand = {"1": 500, "2": 900, "3": 1800, "4": 200, "5": 700, "D": 900} ``` -------------------------------- ### Solve a SuperSudoku Puzzle with PuLP_LPARRAY Source: https://github.com/coin-or/pulp/blob/master/doc/source/plugins/lparray.md This example demonstrates solving an unconstrained SuperSudoku puzzle using PuLP_LPARRAY. It defines the board as a binary LpVariable array and applies constraints for digit uniqueness per cell, row, column, box, and XY coordinates. ```default from lparray import lparray # name R, C, r, c, n lb ub type X = lparray.create_anon("Board", (3, 3, 3, 3, 9), 0, 1, pp.LpBinary) prob = pp.LpProblem("SuperSudoku", pp.LpMinimize) (X.sum(axis=-1) == 1).constrain(prob, "OneDigitPerCell") (X.sum(axis=(1, 3)) == 1).constrain(prob, "MaxOnePerRow") (X.sum(axis=(0, 2)) == 1).constrain(prob, "MaxOnePerCol") (X.sum(axis=(2, 3)) == 1).constrain(prob, "MaxOnePerBox") (X.sum(axis=(0, 1)) == 1).constrain(prob, "MaxOnePerXY") prob.solve() board = X.values.argmax(axis=-1) print(board) ``` -------------------------------- ### Implementing the `available` Method Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md This method checks if the solver executable is available and operational. It is required for both `LpSolver` and `LpSolver_CMD` base classes. ```python def available(self): return self.executable(self.path) ``` -------------------------------- ### Solve with COIN_CMD (Default Temporary Files) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Solves a PuLP problem using the COIN_CMD solver. Temporary files are written to the system's default temporary directory and deleted after use. ```python import pulp as pl model = pl.LpProblem("Example", pl.LpMinimize) _var = model.add_variable('a') _var2 = model.add_variable('a2') model += _var + _var2 == 1 solver = pl.COIN_CMD() result = model.solve(solver) ``` -------------------------------- ### Python List Creation and Printing Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Shows how to explicitly create a list containing mixed data types (integers and strings) and how to print the list and its elements. Accessing elements is done via index. ```python >>> a = [5,8,"pt"] >>> print a [5,8,'pt'] >>> print a[0] 5 ``` -------------------------------- ### Initialize PuLP Problem Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_two_stage_production_planning_problem.md Create an instance of the PuLP problem, specifying the problem name and the optimization objective (maximization in this case). ```python gemstoneprob = pulp.LpProblem("The Gemstone Tool Problem", pulp.LpMaximize) ``` -------------------------------- ### Solve with COIN_CMD (Custom Temporary Directory) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Solves a PuLP problem using the COIN_CMD solver, specifying a custom directory for temporary files via the tmpDir attribute. ```python import pulp as pl model = pl.LpProblem("Example", pl.LpMinimize) _var = model.add_variable('a') _var2 = model.add_variable('a2') model += _var + _var2 == 1 solver = pl.COIN_CMD() solver.tmpDir = 'PUT_SOME_ALTERNATIVE_PATH_HERE' result = model.solve(solver) ``` -------------------------------- ### Creating a List Using a Simple List Comprehension Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Illustrates the creation of a list containing numbers from 0 to 4 using a concise list comprehension. This is a more efficient way to create lists compared to traditional loops. ```python >>> a = [i for i in range(5)] >>> a [0, 1, 2, 3, 4] ``` -------------------------------- ### Run Unit Tests with uv Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Execute the unit tests for PuLP using uv. This command discovers and runs tests from the pulp/tests directory. ```bash uv run python -m unittest discover -s pulp/tests -v ``` -------------------------------- ### Iterating Through a Dictionary and Updating Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Shows how to initialize a dictionary with values, iterate through its keys and values, and add new key-value pairs. This is useful for managing data collections. ```python costs = {"CHICKEN": 1.3, "BEEF": 0.8, "MUTTON": 12} print "Cost of Meats" for i in costs: print i print costs[i] costs["LAMB"] = 5 print "Updated Costs of Meats" for i in costs: print i print costs[i] ``` -------------------------------- ### Calling a Python Function with Default Parameters Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Shows how to call a Python function, utilizing default parameter values and specifying keyword arguments. The order of keyword arguments does not matter. ```python >>> string_appender('newbegin', end_message = 'StringOver') newbeginendStringOver ``` -------------------------------- ### Import Solver Configuration from Dictionary Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Imports a PuLP solver configuration from a Python dictionary. This allows recreating a solver with previously saved settings. ```python import pulp solver = pulp.getSolverFromDict(solver_dict) ``` -------------------------------- ### Generate LP File for Inspection Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_debug.md Use the `writeLP()` method to generate an LP file representing your optimization problem. This file can be opened in a text editor to verify constraint construction. ```python prob.writeLP("model.lp") ``` -------------------------------- ### Set Up Optimization Model and Objective Function Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_set_partitioning_problem.md Initializes the PuLP optimization problem and defines the objective function to maximize total guest happiness. The happiness is calculated based on the distance between guests at each table. ```python seating_model = pulp.LpProblem("Wedding Seating Model", pulp.LpMinimize) # BEGIN define_x # create a binary variable to state that a table setting is used _table_keys = ["_\" ".join(t) for t in possible_tables] vars_by_key = seating_model.add_variable_dict( "table_%s", (_table_keys,), 0, 1, pulp.LpInteger ) x = {t: vars_by_key["_".join(t)] for t in possible_tables} # END define_x seating_model += pulp.lpSum([happiness(table) * x[table] for table in possible_tables]) ``` -------------------------------- ### Solver Configuration Dictionary Structure Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Shows the typical structure of the dictionary returned when exporting a PuLP solver's configuration. ```default {'keepFiles': 0, 'mip': True, 'msg': True, 'options': [], 'solver': 'COIN_CMD', 'timeLimit': None, 'warmStart': False} ``` -------------------------------- ### Include Solver in Test Suite Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md Create a test file for a new solver by inheriting from BaseSolverTest.PuLPTest and setting the solveInst attribute. ```python from pulp.tests.solver_common import BaseSolverTest import pulp.apis as solvers class MIPCL_CMDTest(BaseSolverTest.PuLPTest): solveInst = solvers.MIPCL_CMD ``` -------------------------------- ### Solve with COIN_CMD (Keep Temporary Files) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Solves a PuLP problem using the COIN_CMD solver with the keepFiles=True option. Temporary files are created in the current directory and are not deleted. ```python import pulp as pl model = pl.LpProblem("Example", pl.LpMinimize) _var = model.add_variable('a') _var2 = model.add_variable('a2') model += _var + _var2 == 1 solver = pl.COIN_CMD(keepFiles=True) result = model.solve(solver) ``` -------------------------------- ### Set Initial Value for a Variable Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_mip_start.md Assign an initial value to a variable before solving the model. This is a prerequisite for warm-starting. ```python x[('O', 'P', 'Q', 'R')].setInitialValue(1) x[('K', 'N', 'O', 'R')].setInitialValue(0) ``` -------------------------------- ### Import PuLP Modeler Functions Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_sudoku_problem.md Imports necessary functions from the PuLP library to begin modeling the Sudoku problem. ```python """ The Sudoku Problem Formulation for the PuLP Modeller Authors: Antony Phillips, Dr Stuart Mitchell edited by Nathan Sudermann-Merx """ # Import PuLP modeler functions from pulp import * ``` -------------------------------- ### Initialize PuLP Problem Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_blending_problem.md Initializes a PuLP problem instance for minimization. This is the first step in defining a linear programming problem. ```python # Create the 'prob' variable to contain the problem data prob = LpProblem("The Whiskas Problem", LpMinimize) ``` -------------------------------- ### Set GUROBI Environment Variables (Linux/Mac) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Add these lines to your ~/.bashrc or equivalent file to configure the GUROBI solver environment on Linux or Mac. ```default export GUROBI_HOME="/opt/gurobi801/linux64" export PATH="${PATH}:${GUROBI_HOME}/bin" export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" ``` -------------------------------- ### Print, Solve, and Output Results Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_two_stage_production_planning_problem.md Prints the PuLP problem, writes it to an LP file, solves the problem, and prints the solution status. It then iterates through variables to print their optimal values and the optimized objective function value. ```python # Print problem print(gemstoneprob) # The problem data is written to an .lp file gemstoneprob.writeLP("gemstoneprob.lp") # The problem is solved using PuLP's choice of Solver gemstoneprob.solve() # The status of the solution is printed to the screen print("Status:", pulp.LpStatus[gemstoneprob.status]) # Each of the variables is printed with it's resolved optimum value for v in gemstoneprob.variables(): print(v.name, "=", v.varValue) result = [v.varValue for v in gemstoneprob.variables()] # The optimised objective function value is printed to the console print("Total price = ", pulp.value(gemstoneprob.objective)) ``` -------------------------------- ### Set GUROBI Environment Variables (Windows) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Configure GUROBI solver environment variables on Windows using the command line. ```default set GUROBI_HOME=/opt/gurobi801/linux64 set PATH=%PATH%;%GUROBI_HOME%/bin set LD_LIBRARY_PATH=%LD_LIBRARY_PATH%;%GUROBI_HOME%/lib ``` -------------------------------- ### Export Solver Configuration to Dictionary Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Exports the configuration of a PuLP solver (COIN_CMD in this case) to a Python dictionary for backup or inspection. ```python import pulp solver = pulp.COIN_CMD() solver_dict = solver.toDict() ``` -------------------------------- ### Creating a List Based on Conditions from Other Lists Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Demonstrates creating a new list by applying conditions that reference elements from existing lists ('odds' and 'fifths'). This showcases advanced list comprehension usage for data filtering and combination. ```python >>> a = [i for i in range(25) if (i in odds and i not in fifths)] ``` -------------------------------- ### Import PuLP Functions Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_blending_problem.md Imports necessary functions from the PuLP library to enable linear programming model creation and solving. ```python # Import PuLP modeler functions from pulp import * ``` -------------------------------- ### Custom Solver actualSolve Method Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/add_solver.md Implement the actualSolve method to define the workflow for building the solver model, calling the solver, and retrieving solution information. ```python def actualSolve(self, lp): self.buildSolverModel(lp) # set the initial solution self.callSolver(lp) # get the solution information solutionStatus = self.findSolutionValues(lp) return solutionStatus ``` -------------------------------- ### Define Supply and Demand Nodes and Capacities Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_transportation_problem.md Create lists for supply and demand nodes, and dictionaries to store their respective capacities and demands. ```python # Creates a list of all the supply nodes Warehouses = ["A", "B"] # Creates a dictionary for the number of units of supply for each supply node supply = {"A": 1000, "B": 4000} # Creates a list of all demand nodes Bars = ["1", "2", "3", "4", "5"] # Creates a dictionary for the number of units of demand for each demand node demand = { "1": 500, "2": 900, "3": 1800, "4": 200, "5": 700, } ``` -------------------------------- ### Define LP Variables for Ingredients Source: https://github.com/coin-or/pulp/blob/master/doc/source/CaseStudies/a_blending_problem.md Creates a dictionary of LP variables, one for each ingredient, with a lower bound of zero. These variables represent the quantity of each ingredient to be used. ```python # A dictionary called 'ingredient_vars' is created to contain the referenced Variables ingredient_vars = prob.add_variable_dict("Ingr", (Ingredients,), 0, None, LpContinuous) ``` -------------------------------- ### Set XPRESS Environment Variables (Linux/Mac) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Add these lines to your ~/.bashrc or equivalent file to configure the XPRESS solver environment on Linux or Mac. ```default export XPRESSDIR="/opt/xpressmp" export PATH="${PATH}:${XPRESSDIR}/bin" export XPAUTH_PATH="${XPRESSDIR}/bin/xpauth.xpr" ``` -------------------------------- ### Clone the PuLP Repository Source: https://github.com/coin-or/pulp/blob/master/doc/source/develop/contribute.md Clone your forked PuLP repository to your local machine. Replace `` with your GitHub username. ```bash git clone git@github.com:/pulp.git ``` -------------------------------- ### Set XPRESS Environment Variables (Windows) Source: https://github.com/coin-or/pulp/blob/master/doc/source/guides/how_to_configure_solvers.md Configure XPRESS solver environment variables on Windows using the command line. ```default set XPRESSDIR=C:/xpressmp set PATH=%PATH%;%XPRESSDIR%/bin set XPAUTH_PATH=%XPRESSDIR%/bin/xpauth.xpr ``` -------------------------------- ### Importing All Functions from the PuLP Module Source: https://github.com/coin-or/pulp/blob/master/doc/source/main/basic_python_coding.md Shows the standard import statement required at the beginning of Python scripts that use the PuLP library. Importing all functions with an asterisk makes them directly accessible. ```python >>> from pulp import * ```