### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming-with-datamodel.ipynb Installs the cuOpt library and its server client. It provides commented-out examples for different CUDA versions (10.x and 12.x), allowing users to select the appropriate installation command based on their system's CUDA setup. ```python # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Clone cuOpt Examples Repository Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/README.md Clones the NVIDIA cuOpt examples repository from GitHub and navigates into the cloned directory. This is the first step to get started with the examples. ```bash git clone https://github.com/NVIDIA/cuopt-examples.git cd cuopt-examples ``` -------------------------------- ### Sudoku Problem Setup Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb This snippet demonstrates the initial setup for solving a Sudoku problem using cuOpt. It includes the problem definition and the necessary imports for the optimization process. The example visualizes the Sudoku grid. ```Python import cuopt import numpy as np # Problem Setup # In this problem, we will solve the following Sudoku problem # [Image of Sudoku problem] print("Problem Setup Complete.") ``` -------------------------------- ### Install PuLP and cuOpt Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Simple_MIP_pulp.ipynb Installs the PuLP library for mathematical modeling and the cuOpt library for GPU-accelerated optimization. The cuOpt installation command is commented out and should be enabled if cuOpt is not pre-installed. ```python pip install pulp==3.2.0 ``` ```python # # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # !pip install --extra-index-url=https://pypi.nvidia.com cuopt-cu12==25.5.* ``` -------------------------------- ### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/routing_optimization_over_server/cvrptw_service_team_routing.ipynb Installs the cuOpt library and its server client. It provides commented-out examples for different CUDA versions, allowing users to select the appropriate installation command based on their system's CUDA setup. ```bash # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Install PuLP Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Simple_LP_pulp.ipynb Installs the PuLP library, a Python-based modeler for linear and mixed-integer programming. This is a prerequisite for setting up and solving LP problems. ```python !pip install pulp==3.2.0 ``` -------------------------------- ### Run cuOpt Examples with Docker Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/README.md Runs the cuOpt examples using a Docker container. It mounts the current directory, exposes all GPUs, and sets up the environment to install requirements and launch Jupyter notebooks. ```bash docker run -it --rm --gpus all --network=host -v $(pwd):/workspace -w /workspace nvidia/cuopt:25.05.* /bin/bash -c "pip install --user -r requirements.txt; jupyter-notebook" ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/CONTRIBUTING.md Instructions for installing pre-commit and running its hooks for code linting and formatting. Pre-commit helps maintain a consistent code style across the project. ```bash conda install -c conda-forge pre-commit # or pip install pre-commit ``` ```bash pre-commit run ``` ```bash pre-commit run --all-files ``` ```bash pre-commit install ``` -------------------------------- ### Install PuLP Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb Installs the PuLP library, a Python-based modeler for linear and mixed integer programming. This is a prerequisite for setting up the Sudoku solving environment. ```python !pip install pulp==3.2.0 ``` -------------------------------- ### Jupyter Environment Setup Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/requirements.txt This snippet outlines the necessary packages for setting up a Jupyter environment to run cuOpt examples. It includes Jupyter, notebook, and ipykernel. ```python jupyter notebook ipykernel ``` -------------------------------- ### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/intra-factory_transport/cost_matrix_and_waypoint_graph_creation.ipynb Installs necessary Python libraries for cuOpt examples, including scipy, matplotlib, pandas, requests, polyline, and folium. ```python # Install notebook dependencies !pip install --user -q scipy matplotlib pandas requests polyline folium ``` -------------------------------- ### Install cuOpt Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrptw_benchmark_gehring_homberger.ipynb Installs the cuOpt library. The commented-out lines provide specific installation commands for different CUDA versions (10.x and 12.x), which should be uncommented based on the system's CUDA setup. ```bash # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-cu11==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-cu12==25.5.* ``` -------------------------------- ### Install Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Production_Planning_Example_Pulp.ipynb Installs the PuLP library for linear and mixed-integer programming modeler and cuOpt for GPU-accelerated solving. PuLP version 3.2.0 is specified. ```python !pip install pulp==3.2.0 ``` -------------------------------- ### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming-with-datamodel.ipynb Installs the necessary cuOpt server and client libraries. The specific command depends on the CUDA version installed on the system (e.g., CUDA 10.x or 12.x). ```bash # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Install cuOpt (Optional) Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Simple_LP_pulp.ipynb Installs the cuOpt library, NVIDIA's GPU-accelerated solver. This command is typically uncommented and used in environments like Google Colab where cuOpt is not pre-installed. ```python # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # !pip install --extra-index-url=https://pypi.nvidia.com cuopt-cu12==25.5.* ``` -------------------------------- ### cuOpt Example: Basic Usage Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb This snippet demonstrates the fundamental usage of the cuOpt library for solving optimization problems. It includes setup, problem definition, and solution retrieval. ```C++ /* * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "cuopt/cuopt.hpp" int main() { // Initialize cuOpt cuopt::Context ctx; // Create a problem cuopt::Problem problem; // Add variables auto x = problem.addVariable(0.0, 10.0); auto y = problem.addVariable(0.0, 10.0); // Add objective function (minimize x + y) problem.setObjective(x + y); // Add constraints problem.addConstraint(x + y <= 5.0); // Solve the problem auto solution = ctx.solve(problem); // Print the solution std::cout << "x = " << solution.get(x) << std::endl; std::cout << "y = " << solution.get(y) << std::endl; return 0; } ``` -------------------------------- ### Install cuOpt and GAMSPy Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/GAMSPy_integration_example/trnsport_cuopt.ipynb Installs the necessary libraries, cuOpt and GAMSPy, along with their dependencies. It also downloads and extracts a cuOpt-link release for integration. ```python # remove -q to debug issues with pip installs !pip install -q --extra-index-url=https://pypi.nvidia.com cuopt-cu12==25.5.* nvidia-cuda-runtime-cu12==12.8.* nvidia-nvjitlink-cu12 !pip install -q gamspy import subprocess import sys !wget -nc -nv -O cuopt-link-release.zip "https://github.com/GAMS-dev/cuoptlink-builder/releases/download/v0.0.1/cuopt-link-release.zip" gams_base_path = subprocess.check_output([sys.executable, '-m', 'gamspy', 'show', 'base']).decode('utf-8').strip() subprocess.run(f"unzip -o cuopt-link-release.zip -d {gams_base_path}", shell=True, check=True) ``` -------------------------------- ### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming.ipynb Installs the cuOpt library and its server client. The specific command depends on the CUDA version of the underlying system (e.g., CUDA 11.x or CUDA 12.x). ```python # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Install cuOpt (Optional) Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb Installs the cuOpt library, NVIDIA's GPU-accelerated solver. This command is intended for environments like Google Colab where cuOpt might not be pre-installed. It specifies the cu12 version and a wildcard for the latest patch release. ```python # # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # !pip install --extra-index-url=https://pypi.nvidia.com cuopt-cu12==25.5.* ``` -------------------------------- ### Install cuOpt Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming.ipynb Installs the necessary cuOpt libraries. The specific command depends on the CUDA version installed on the system (e.g., CUDA 10.x or 12.x). ```python # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Problem Setup and Formulation Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Simple_LP_pulp.ipynb Sets up a random linear program with specified dimensions (m constraints, n variables). It generates random data for the objective function coefficients (c), constraint matrix (A), and constraint bounds (b), then defines the LP problem using PuLP. ```python # Import packages. from pulp import * import numpy as np # Generate a random non-trivial linear program. m = 15 n = 10 np.random.seed(1) s0 = np.random.randn(m) lamb0 = np.maximum(-s0, 0) s0 = np.maximum(s0, 0) x0 = np.random.randn(n) A = np.random.randn(m, n) b = A @ x0 + s0 c = -A.T @ lamb0 # Define and solve the Pulp problem prob = LpProblem("LP_example", LpMinimize) x = [LpVariable(f"x{i}", lowBound=None) for i in range(n)] prob += lpSum([c[i] * x[i] for i in range(n)]), "Objective" for i in range(m): prob += lpSum([A[i, j] * x[j] for j in range(n)]) <= b[i], f"Constraint_{i}" ``` -------------------------------- ### Problem Setup with PuLP Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Production_Planning_Example_Pulp.ipynb Defines a production planning problem using PuLP. It includes integer variables for product quantities (x1, x2), a binary variable for machine activation (y), an objective function to maximize profit, and constraints for material, labor, minimum production, and trivial solutions. ```python from pulp import * # Define the problem problem = LpProblem("Production_Planning", LpMaximize) # Decision variables x1 = LpVariable('x1', lowBound=0, cat='Integer') # Product 1 units x2 = LpVariable('x2', lowBound=0, cat='Integer') # Product 2 units y = LpVariable('y', cat='Binary') # Machine usage flag # Objective function: Maximize profit problem += 20.0*x1 + 120.0*x2 + 1000.0*y, "Total_Profit" # Constraints problem += 3.0*x1 + 2.0*x2 <= 240.0, "Material_limit_x2" problem += 2.0*x1 + 4.0*x2 <= 180.0, "Labor_limit_x2" problem += x2 >= 5.0*y, "Minimum_x₂_if_machine_used" problem += x1 >= 1.0, "Prevent_trivial_solution_x1" problem += x2 >= 1.0, "Prevent_trivial_solution_x2" ``` -------------------------------- ### Dataset and Market Scenario Setup Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/02_backtesting.ipynb Configures the dataset to be used for backtesting, specifying the dataset name and file path. It also defines various market scenarios with their respective date ranges for in-sample analysis. ```python # --- Dataset Configuration --- DATASET_NAME = "sp500" DATASET_FILE_PATH = f"../data/stock_data/{DATASET_NAME}.csv" # --- Market Scenario Definitions --- # Users can add or modify scenarios here for different in-sample periods SCENARIO_DEFINITIONS = { 'pre_crisis': ('2005-01-01', '2007-10-01'), 'crisis': ('2007-10-01', '2009-04-01'), 'post_crisis': ('2009-06-30', '2014-06-30'), 'oil_price_crash': ('2014-06-01', '2016-03-01'), 'FAANG_surge': ('2015-01-01', '2021-01-01'), 'covid': ('2020-01-01', '2023-01-01'), 'recent': ('2022-01-04', '2024-01-01') # Default scenario for this run } ``` -------------------------------- ### Install cuOpt and Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/01_optimization_with_cufolio.ipynb Installs the necessary libraries for cuOpt and portfolio optimization, including numpy, pandas, cvxpy, and cuML. This should be run once in the environment. ```python # Install dependencies # This cell only needs to be run once, typically after setting up the environment. # If dependencies are already installed, you can comment out or skip this cell. # Install cuOpt (if not already installed) # !pip install --user --extra-index-url https://pypi.nvidia.com -q cuopt-cu12==25.5.* # Install other dependencies (if not already installed) # !pip install --user --extra-index-url https://pypi.nvidia.com -q "numpy>=1.24.4" "pandas>=2.2.1" "cvxpy>=1.6.5" "scipy==1.15.2" "scikit-learn==1.6.1" "msgpack>=1.1.0" "cuml-cu12==25.4.*" "seaborn>=0.13.2" bin/cufolio-25.5-py3-none-any.whl ``` -------------------------------- ### Install cuOpt Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrp_daily_deliveries.ipynb Installs the cuOpt library. Users should uncomment the appropriate line based on their CUDA version (11.X or 12.X). ```bash # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-11.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-cu11==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-cu12==25.5.* ``` -------------------------------- ### Install Dependencies in Notebook Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/CONTRIBUTING.md Installs dependencies required for a Jupyter notebook using a requirements.txt file. This ensures the notebook is self-contained and runnable in environments without direct access to local modules. ```python !pip install -q -r requirements.txt ``` -------------------------------- ### cuOpt Python API: Basic Usage Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb This snippet demonstrates the basic usage of the cuOpt Python API for solving optimization problems. It covers problem setup, variable definition, and solution retrieval. ```Python import cuopt # Initialize cuOpt context ctx = cuopt.Context() # Create a problem problem = cuopt.Problem() # Add variables x = problem.add_variable(0.0, 10.0) y = problem.add_variable(0.0, 10.0) # Set objective function (minimize x + y) problem.set_objective(x + y) # Add constraints problem.add_constraint(x + y <= 5.0) # Solve the problem solution = ctx.solve(problem) # Print the solution print(f"x = {solution.get(x)}") print(f"y = {solution.get(y)}") ``` -------------------------------- ### Problem Setup with PuLP Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Simple_MIP_pulp.ipynb Defines a Mixed Integer Programming (MIP) problem using the PuLP library. It sets up a minimization objective function and two constraints, defining integer and continuous variables. ```python from pulp import * # Define the problem problem = LpProblem("Integer_Optimization", LpMinimize) # Define variables x = LpVariable('x', cat='Integer') # Integer y = LpVariable('y', lowBound=0.0) # Non-negative # Objective function problem += 2.0 * x + 3.0 * y, "Objective" # Constraints problem += x + y >= 10.0, "Constraint1" problem += x <= 15.0, "Constraint2" ``` -------------------------------- ### Run cuOpt Server Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming.ipynb Starts the cuOpt server in a background process. It includes logic to check if the server is already running to avoid multiple instances. A cleanup function is registered to terminate the server when the script exits. ```python import subprocess import atexit import signal import os import psutil def is_cuopt_server_running(): for proc in psutil.process_iter(['pid', 'name', 'cmdline']): try: cmdline = proc.info['cmdline'] if 'python3' in proc.info['name'] and cmdline: # Check if cmdline exists and is not None if any('cuopt_server.cuopt_service' in cmd for cmd in cmdline): return True except (psutil.NoSuchProcess, psutil.AccessDenied): pass return False # Only start server if it's not already running if not is_cuopt_server_running(): # Start cuOpt server in background server_process = subprocess.Popen(['python3', '-m', 'cuopt_server.cuopt_service'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def cleanup_server(): try: server_process.terminate() server_process.wait(timeout=5) # Wait up to 5 seconds for graceful termination print("Terminated cuOpt server") except (subprocess.TimeoutExpired, ProcessLookupError): # If graceful termination fails, force kill try: server_process.kill() print("Killed cuOpt server") except ProcessLookupError: pass atexit.register(cleanup_server) print("Started cuOpt server") else: print("cuOpt server is already running") ``` -------------------------------- ### cuOpt Example: Integer Programming Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb This example showcases how to use cuOpt for integer programming problems. It demonstrates defining integer variables and constraints. ```C++ /* * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "cuopt/cuopt.hpp" int main() { // Initialize cuOpt cuopt::Context ctx; // Create a problem cuopt::Problem problem; // Add integer variables auto x = problem.addVariable(0.0, 10.0, cuopt::VariableType::INTEGER); auto y = problem.addVariable(0.0, 10.0, cuopt::VariableType::INTEGER); // Add objective function (maximize 2x + 3y) problem.setObjective(2 * x + 3 * y, cuopt::ObjectiveSense::MAXIMIZE); // Add constraints problem.addConstraint(x + y <= 5.0); problem.addConstraint(2 * x + y <= 8.0); // Solve the problem auto solution = ctx.solve(problem); // Print the solution std::cout << "x = " << solution.get(x) << std::endl; std::cout << "y = " << solution.get(y) << std::endl; return 0; } ``` -------------------------------- ### Run cuOpt Server Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming-with-datamodel.ipynb Starts the cuOpt server in the background. It includes logic to check if the server is already running to avoid multiple instances. A cleanup function is registered to terminate the server when the script exits. ```python import subprocess import atexit import signal import os import psutil def is_cuopt_server_running(): for proc in psutil.process_iter(['pid', 'name', 'cmdline']): try: cmdline = proc.info['cmdline'] if 'python3' in proc.info['name'] and cmdline: # Check if cmdline exists and is not None if any('cuopt_server.cuopt_service' in cmd for cmd in cmdline): return True except (psutil.NoSuchProcess, psutil.AccessDenied): pass return False # Only start server if it's not already running if not is_cuopt_server_running(): # Start cuOpt server in background server_process = subprocess.Popen(['python3', '-m', 'cuopt_server.cuopt_service'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def cleanup_server(): try: server_process.terminate() server_process.wait(timeout=5) # Wait up to 5 seconds for graceful termination print("Terminated cuOpt server") except (subprocess.TimeoutExpired, ProcessLookupError): # If graceful termination fails, force kill try: server_process.kill() print("Killed cuOpt server") except ProcessLookupError: pass atexit.register(cleanup_server) print("Started cuOpt server") else: print("cuOpt server is already running") ``` -------------------------------- ### Set Solver Configuration Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming-with-datamodel.ipynb Allows for fine-tuning of solver parameters to optimize performance and runtime. Examples include setting a time limit and optimality tolerance. ```python ss.set_parameter("time_limit", 1) ss.set_optimality_tolerance(0.0001) ``` -------------------------------- ### Sample cuOpt Solver Response Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming-with-datamodel.ipynb An example of the JSON response received from the cuOpt solver. It includes the solver status, primal and dual solutions, objective values, and other statistics. Status '1' indicates an optimal solution is available. ```json { "response": { "solver_response": { "status": 1, "solution": { "problem_category": 0, "primal_solution": [ 37.5, 38.75000000000001 ], "dual_solution": [ -0.12500016770509828, -1.750000111803399 ], "primal_objective": 303.75, "dual_objective": 6.3805226600279e-310, "solver_time": 0.019212961196899414, "vars": { "x": 37.5, "y": 38.75000000000001 }, "lp_statistics": { "primal_residual": 6.37992675089215e-310, "dual_residual": 6.38052266003797e-310, "gap": 6.37992675097e-310, "nb_iterations": 2 }, "reduced_cost": [ 0.0, 0.0 ], "milp_statistics": {} } }, "total_solve_time": 0.08559036254882812 }, "reqId": "64ba4d53-1417-4f9f-96f6-299621147bce" } ``` -------------------------------- ### Example cuOpt Solver Response Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming.ipynb Illustrates a typical JSON response from the cuOpt solver, including the status, primal and dual solutions, objective values, and solver statistics. Status '1' indicates an optimal solution. ```json { "response": { "solver_response": { "status": 1, "solution": { "problem_category": 0, "primal_solution": [ 37.5, 38.75000000000001 ], "dual_solution": [ -0.12500016770509828, -1.750000111803399 ], "primal_objective": 303.75, "dual_objective": 6.9169198857246e-310, "solver_time": 0.03702497482299805, "vars": { "x": 37.5, "y": 38.75000000000001 }, "lp_statistics": { "primal_residual": 6.91676961621886e-310, "dual_residual": 6.91691988573466e-310, "gap": 6.91676961629673e-310, "nb_iterations": 2 }, "reduced_cost": [ 0.0, 0.0 ], "milp_statistics": {} } }, "total_solve_time": 0.124053955078125 }, "reqId": "a9f0f9c7-3e53-43a8-a108-1b3e7a9dc3d1" } ``` -------------------------------- ### Python Code Style Guidelines Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/CONTRIBUTING.md Best practices for writing Python code within the NVIDIA cuOpt Examples project, emphasizing PEP 8 compliance, type hints, docstrings, and clear naming conventions. ```python # Follow PEP 8 guidelines # Use type hints for function arguments and return values # Write docstrings for all public functions and classes # Keep functions focused and single-purpose # Use meaningful variable and function names # Add comments for complex logic ``` -------------------------------- ### Example cuOpt Solver Response Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming.ipynb A sample JSON response from the cuOpt solver, indicating an optimal solution is available. It includes primal and dual solutions, objective values, and solver statistics. ```json { "response": { "solver_response": { "status": 1, "solution": { "problem_category": 1, "primal_solution": [ 37.0, 39.500000000000014 ], "dual_solution": null, "primal_objective": 303.50000000000006, "dual_objective": null, "solver_time": 0.0, "vars": { "x": 37.0, "y": 39.500000000000014 }, "lp_statistics": {}, "reduced_cost": null, "milp_statistics": { "mip_gap": 0.0, "solution_bound": 303.50000000000006, "presolve_time": 0.011782234, "max_constraint_violation": 2.842170943040401e-14, "max_int_violation": 0.0, "max_variable_bound_violation": 0.0, "num_nodes": 16955616, "num_simplex_iterations": 25554 } } }, "total_solve_time": 0.036028385162353516 }, "reqId": "86519025-7522-46ac-b527-9c3b8e89c622" } ``` -------------------------------- ### cuOpt Python API: Integer Programming Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb This example shows how to use the cuOpt Python API for integer programming. It includes defining integer variables and setting up integer constraints. ```Python import cuopt # Initialize cuOpt context ctx = cuopt.Context() # Create a problem problem = cuopt.Problem() # Add integer variables x = problem.add_variable(0.0, 10.0, var_type=cuopt.VariableType.INTEGER) y = problem.add_variable(0.0, 10.0, var_type=cuopt.VariableType.INTEGER) # Set objective function (maximize 2x + 3y) problem.set_objective(2 * x + 3 * y, sense=cuopt.ObjectiveSense.MAXIMIZE) # Add constraints problem.add_constraint(x + y <= 5.0) problem.add_constraint(2 * x + y <= 8.0) # Solve the problem solution = ctx.solve(problem) # Print the solution print(f"x = {solution.get(x)}") print(f"y = {solution.get(y)}") ``` -------------------------------- ### Sample cuOpt LP Solve Response Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming-with-datamodel.ipynb An example JSON output representing the solution to a linear programming problem solved by cuOpt. It includes solver status, primal and dual solutions, objective values, and detailed MILP statistics. ```json { "response": { "solver_response": { "status": 1, "solution": { "problem_category": 1, "primal_solution": [ 37.0, 39.500000000000014 ], "dual_solution": null, "primal_objective": 303.50000000000006, "dual_objective": null, "solver_time": 0.0, "vars": { "x": 37.0, "y": 39.500000000000014 }, "lp_statistics": {}, "reduced_cost": null, "milp_statistics": { "mip_gap": 0.0, "solution_bound": 303.50000000000006, "presolve_time": 0.032318192, "max_constraint_violation": 2.842170943040401e-14, "max_int_violation": 0.0, "max_variable_bound_violation": 0.0, "num_nodes": 16955616, "num_simplex_iterations": 25554 } } }, "total_solve_time": 0.11340999603271484 }, "reqId": "f05db529-eefe-4bbf-9b33-9c4406c1e362" } ``` -------------------------------- ### Generate User-Defined Benchmark Portfolios Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/02_backtesting.ipynb Provides an example of how to define and format custom benchmark portfolios for comparison during backtesting. This involves specifying asset allocations and cash holdings. ```python # Example: Define user-input benchmark portfolios dictionary user_defined_benchmarks_dict = { # 'NVDA-JPM': ({'NVDA': 0.72, 'JPM': 0.18}, 0.1), # (asset_weights_dict, cash_holding_float) # 'AAPL-MSFT': ({'AAPL': 0.29, 'MSFT': 0.61}, 0.1), # Add more benchmarks as needed } # Convert user-defined portfolios into the required format for the backtester # The `full_returns_for_backtest` dictionary is used to ensure assets are known ``` -------------------------------- ### Set Vehicle Start and End Locations Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrptw_benchmark_gehring_homberger.ipynb Configures the starting and ending locations for all vehicles in the routing model. In this example, all vehicles start and end at the depot (location 0). ```python # All vehicles start and end at the depot (location 0) veh_start_locations = cudf.Series([0] * n_vehicles) veh_end_locations = cudf.Series([0] * n_vehicles) data_model.set_vehicle_locations(veh_start_locations, veh_end_locations) ``` -------------------------------- ### Set Vehicle Locations Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrp_daily_deliveries.ipynb Sets the starting and ending locations for all vehicles. In this example, all vehicles start and end at the depot (location 0). ```python # All vehicles start and end at the depot (location 0) veh_start_locations = cudf.Series([0, 0, 0]) veh_end_locations = cudf.Series([0, 0, 0]) data_model.set_vehicle_locations(veh_start_locations, veh_end_locations) ``` -------------------------------- ### Initialize DataModel and Solver Settings Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/linear-programming-with-datamodel.ipynb Initializes the DataModel for defining the linear programming problem and ThinClientSolverSettings for configuring the solver. These are fundamental objects for setting up the problem. ```python import numpy as np import cuopt_mps_parser from data_model import DataModel from cuopt_sh_client import ThinClientSolverSettings problem_data = {} dm = DataModel() ss = ThinClientSolverSettings() ``` -------------------------------- ### Install Notebook Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrp_daily_deliveries.ipynb Installs the matplotlib library, which is required for plotting functionalities within the notebook. ```bash # Install notebook dependencies !pip install --user -q matplotlib ``` -------------------------------- ### Initialize cuOpt DataModel and Solver Settings Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/sample_lp_sever_notebooks/mixed-integer-linear-programming-with-datamodel.ipynb Initializes the necessary components for cuOpt, including the DataModel for problem definition and ThinClientSolverSettings for configuring the solver. This sets up the environment for defining the MILP problem. ```python import numpy as np import cuopt_mps_parser from data_model import DataModel from cuopt_sh_client import ThinClientSolverSettings problem_data = {} dm = DataModel() ss = ThinClientSolverSettings() ``` -------------------------------- ### Install Notebook Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/last_mile_delivery/cvrptw_benchmark_gehring_homberger.ipynb Installs necessary Python libraries for the notebook, including matplotlib for plotting and scipy for scientific computations. The '-q' flag ensures a quiet installation process. ```bash # Install notebook dependencyn !pip install --user -q matplotlib scipy ``` -------------------------------- ### Initial CVaR Portfolio Optimization Setup Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/03_advanced_topics.ipynb Prepares data and instantiates the CVaR optimization problem for initial portfolio allocation. This involves selecting a market scenario, calculating returns, and setting up the CVaR optimizer with specific parameters. ```python # --- Select Scenario for Initial Optimization --- # Choose a key from 'market_scenarios' dictionary (e.g., 'recent_short_sample') selected_initial_opt_scenario_key = 'recent_short_sample' initial_opt_start_date, initial_opt_end_date = get_regime_dates(selected_initial_opt_scenario_key) # Regime dictionary for calculating returns initial_opt_regime_dict = {"name": selected_initial_opt_scenario_key, "range": (initial_opt_start_date, initial_opt_end_date)} # Compute returns dictionary initial_opt_returns_dict = cvar_utils.calculate_returns( sp500_dataset_directory, initial_opt_regime_dict, log_return_type, initial_opt_cvar_params # Using parameters defined for initial optimization ) # Instantiate CVaR optimization problem initial_cvar_problem = cvar_optimizer.CVaR( returns_dict=initial_opt_returns_dict, cvar_params=initial_opt_cvar_params, problem_from_file=None ) ``` -------------------------------- ### Install Notebook Dependencies Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/routing_optimization_over_server/cvrptw_benchmark_gehring_homberger.ipynb Installs essential Python libraries required for the notebook, including matplotlib, scipy, pandas, and numpy, for data manipulation and visualization. ```bash #Install notebook dependencies !pip install --user -q matplotlib scipy pandas numpy ``` -------------------------------- ### Instantiate Parameters and Optimizer (S&P 500 Example) Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/01_optimization_with_cufolio.ipynb Demonstrates the initialization of parameters and optimizer objects for Conditional Value-at-Risk (CVaR) optimization using an S&P 500 dataset. ```python # --- Instantiate Parameters and Optimizer Objects (S&P 500 Example) --- # In this section, we define the parameters for Conditional Value-at-Risk (CVaR) optimization for an S&P 500 dataset example and initialize the optimizer. ``` -------------------------------- ### Initialize CVaR Optimization Problem Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/cuFOLIO_portfolio_optimization/CVaR/02_backtesting.ipynb Calculates returns for the optimization period and instantiates the CVaR optimization problem. It requires dataset path, regime dictionary, return type, CVaR parameters, and the computation device. ```python optimization_returns = cvar_utils.calculate_returns( DATASET_FILE_PATH, optimization_regime_dict, RETURN_TYPE, backtest_cvar_params, # CVaR parameters defined above device=KDE_COMPUTATION_DEVICE ) cvar_optimizer_problem = cvar_optimizer.CVaR( returns_dict=optimization_returns, cvar_params=backtest_cvar_params ) ``` -------------------------------- ### Start cuOpt Server Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/routing_optimization_over_server/cvrptw_benchmark_gehring_homberger.ipynb Starts the cuOpt server as a background subprocess. It includes logic to check if the server is already running and registers a cleanup function to terminate the server when the script exits. ```python import subprocess import atexit import signal import os import psutil def is_cuopt_server_running(): for proc in psutil.process_iter(['pid', 'name', 'cmdline']): try: cmdline = proc.info['cmdline'] if 'python3' in proc.info['name'] and cmdline: # Check if cmdline exists and is not None if any('cuopt_server.cuopt_service' in cmd for cmd in cmdline): return True except (psutil.NoSuchProcess, psutil.AccessDenied): pass return False # Only start server if it's not already running if not is_cuopt_server_running(): # Start cuOpt server in background server_process = subprocess.Popen(['python3', '-m', 'cuopt_server.cuopt_service'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def cleanup_server(): try: server_process.terminate() server_process.wait(timeout=5) # Wait up to 5 seconds for graceful termination print("Terminated cuOpt server") except (subprocess.TimeoutExpired, ProcessLookupError): # If graceful termination fails, force kill try: server_process.kill() print("Killed cuOpt server") except ProcessLookupError: pass atexit.register(cleanup_server) print("Started cuOpt server") else: print("cuOpt server is already running") ``` -------------------------------- ### Install cuOpt Server and Client Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/routing_optimization_over_server/cvrptw_benchmark_gehring_homberger.ipynb Installs the cuOpt server and client libraries. The specific version depends on the underlying CUDA version (e.g., CUDA 10.X or 12.X). This is necessary if cuOpt is not pre-installed. ```bash # Install cuOpt # Enable this in case you are running this in google colab or such places where cuOpt is not yet installed # This would be incase underlying system is cuda-10.X # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu11==25.5.* cuopt-sh-client==25.5.* # This would be incase underlying system is cuda-12.x # !pip install --extra-index-url https://pypi.nvidia.com --user cuopt-server-cu12==25.5.* cuopt-sh-client==25.5.* ``` -------------------------------- ### Basic cuOpt Usage (Python) Source: https://github.com/nvidia/cuopt-examples/blob/branch-25.08/PuLP_integration_example/Sudoku_pulp.ipynb Demonstrates the fundamental steps to use cuOpt for optimization in Python. This includes setting up the problem, defining constraints, and solving the optimization. ```Python import cuopt # Initialize cuOpt cuopt.init() # Define optimization problem (example: linear programming) # ... problem definition ... # Solve the problem result = cuopt.solve(problem) # Process the result print(result) ```