### PySCIPOpt eoq Model Initialization Example Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespaceeoq__en Example demonstrating how to initialize the `eoq` model using various parameters and constants defined in the `eoq_en` namespace. ```python model = eoq_en.eoq(I, F, h, d, w, W, a0, aK, K) ``` -------------------------------- ### PySCIPOpt mkp example() Function Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacemkp Defines a function to create example data sets for the mkp module. It references pyscipopt.Multidict.multidict(). ```APIDOC def mkp.example ( ): creates example data set Definition at line 37 of file mkp.py. References pyscipopt.Multidict.multidict(). ``` -------------------------------- ### Python Model Initialization Example Source: https://scipopt.github.io/PySCIPOpt/docs/html/classpyscipopt_1_1scip_1_1Model Example of creating a new SCIP Model instance in Python, disabling automatic SCIP instance creation. ```python from pyscipopt import Model # Create a Model instance without automatically creating a SCIP instance model = Model(createscip=False) ``` -------------------------------- ### Create Example Processing Times (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/pfs_8py_source Creates a fixed example dataset for processing times, specifically for a 3x3 job-machine scenario. This is useful for testing or demonstrating the permutation flow shop model. ```Python def example(): """creates example data set""" proc = [[2, 3, 1], [4, 2, 3], [1, 4, 1]] p = {} for i in range(3): for j in range(3): p[i + 1, j + 1] = proc[j][i] return p ``` -------------------------------- ### Create Example Data Set (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespaceweber__soco Defines a function to generate example data sets for optimization problems. It takes dimensions 'n' and 'm' as input. ```Python def make_data(n, m): """creates example data set""" pass ``` -------------------------------- ### NetworkX Graph Drawing Examples Source: https://scipopt.github.io/PySCIPOpt/docs/html/kmedian_8py_source Demonstrates drawing a graph using NetworkX with different node styles for facilities, clients, and other nodes. Requires 'networkx' and 'matplotlib' to be installed. ```python import networkx as NX import matplotlib.pyplot as P # Assuming G, position, facilities, other, client are defined elsewhere # Example usage: # NX.draw(G, position, with_labels=False, node_color="w", nodelist=facilities) # NX.draw(G, position, with_labels=False, node_color="c", nodelist=other, node_size=50) # NX.draw(G, position, with_labels=False, node_color="g", nodelist=client, node_size=50) # P.show() # Placeholder for actual drawing calls based on context: position = {} G = {} facilities = [] other = [] client = [] NX.draw(G, position, with_labels=False, node_color="w", nodelist=facilities) NX.draw(G, position, with_labels=False, node_color="c", nodelist=other, node_size=50) NX.draw(G, position, with_labels=False, node_color="g", nodelist=client, node_size=50) P.show() ``` -------------------------------- ### Linear Programming Example (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/dir_a562ccaa5e17bafcab246de9ef084f0c A simple SCIP example in Python demonstrating linear programming. This script showcases basic LP modeling and solving capabilities. ```python ``` -------------------------------- ### Example Usage and Result Visualization Source: https://scipopt.github.io/PySCIPOpt/docs/html/kmedian_8py_source Demonstrates how to use the k-median model. It generates data, creates and solves the k-median problem using PySCIPOpt, and then visualizes the results. The visualization part requires `networkx` and `matplotlib` and plots the selected facilities and assigned customers. ```python if __name__ == "__main__": random.seed(67) n = 200 m = n I, J, c, x_pos, y_pos = [make_data](namespacekmedian.html#ac193229cdaa589e23e84ca6bd7211bf9)(n, m, same=True) k = 20 model = [kmedian](namespacekmedian.html)(I, J, c, k) # model.Params.Threads = 1 model.optimize() EPS = 1.e-6 x, y = model.data edges = [(i, j) for (i, j) in x if model.getVal(x[i, j]) > EPS] facilities = [j for j in y if model.getVal(y[j]) > EPS] print("Optimal value:", model.getObjVal()) print("Selected facilities:", facilities) print("Edges:", edges) print("max c:", max([c[i, j] for (i, j) in edges])) try: # plot the result using networkx and matplotlib import networkx as NX import matplotlib.pyplot as P P.clf() G = NX.Graph() facilities = [set](https://scip.zib.de/doc/html/structset.php)(j for j in J if model.getVal(y[j]) > EPS) other = [set](https://scip.de/doc/html/structset.php)(j for j in J if j not in facilities) client = [set](https://scip.de/doc/html/structset.php)(i for i in I if i not in facilities and i not in other) G.add_nodes_from(facilities) G.add_nodes_from(client) G.add_nodes_from(other) for (i, j) in edges: G.add_edge(i, j) position = {} for i in range(len(x_pos)): # ... (rest of plotting code would follow here if fully provided) ``` -------------------------------- ### make_data Function - Create Example Data Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespaceflp A utility function to generate an example dataset for the facility location problem. It relies on the multidict utility from PySCIPOpt. ```APIDOC flp.make_data() creates example data set References: pyscipopt.Multidict.multidict() ``` ```python def make_data(): """creates example data set""" # ... implementation details ... return data ``` -------------------------------- ### Create Example for Single Item Lot Sizing (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacelotsizing__lazy Defines a book example for the single item lot sizing problem. It references the multidict function from pyscipopt.Multidict. ```Python def mk_example(): """mk_example: book example for the single item lot sizing""" # Definition at line 134 of file lotsizing_lazy.py. # References pyscipopt.Multidict.multidict() ``` -------------------------------- ### Create Example Dataset 2 Source: https://scipopt.github.io/PySCIPOpt/docs/html/mctransp_8py_source Generates a second example dataset for the multi-commodity transportation problem. This instance focuses on a single commodity (k=1) across multiple customers and facilities, with specific demand, capacity, production, and cost parameters defined. ```python def make_inst2(): """creates example data set 2""" d = {(1, 1): 45, # {(customer,commodity):demand}} (2, 1): 20, (3, 1): 30, (4, 1): 30, } I = set([i for (i, k) in d]) K = set([k for (i, k) in d]) J, M = multidict({1: 35, 2: 50, 3: 40}) # {factory: capacity}} produce = {1: [1], 2: [1], 3: [1]} # products that can be produced in each facility weight = {1: 1} # {commodity: weight} cost = {(1, 1): 8, (1, 2): 9, (1, 3): 14, # {(customer,factory): cost} (2, 1): 6, (2, 2): 12, (2, 3): 9, (3, 1): 10, (3, 2): 13, (3, 3): 16, (4, 1): 9, (4, 2): 7, (4, 3): 5, } c = {} for i in I: for j in J: for k in produce[j]: c[i, j, k] = cost[i, j] * weight[k] return I, J, K, c, d, M ``` -------------------------------- ### Create Example Dataset 3 Source: https://scipopt.github.io/PySCIPOpt/docs/html/mctransp_8py_source Generates a third example dataset for the multi-commodity transportation problem. This instance features varying demands for three commodities across five customers, with specific facility capacities and production capabilities defined. ```python def make_inst3(): """creates example data set 3""" d = {(1, 1): 40, (1, 2): 30, (1, 3): 10, # {(customer,commodity):demand}} (2, 1): 70, (2, 2): 100, (2, 3): 100, (3, 1): 0, (3, 2): 0, (3, 3): 250, (4, 1): 60, (4, 2): 100, (4, 3): 0, (5, 1): 180, (5, 2): 0, (5, 3): 0 } I = set([i for (i, k) in d]) K = set([k for (i, k) in d]) # Note: J, M, produce, weight, cost are not defined in this snippet, implying they might be handled externally or are missing from the provided text for this function. ``` -------------------------------- ### Main Execution Block Source: https://scipopt.github.io/PySCIPOpt/docs/html/mkp_8py_source Demonstrates how to use the mkp and example functions. It generates data, creates the knapsack model, optimizes it, and prints the optimal value and the selected items. ```Python if __name__ == "__main__": I, J, v, a, b = example() model = mkp(I, J, v, a, b) x = model.data model.optimize() print("Optimal value:", model.getObjVal()) EPS = 1.e-6 for i in x: v = x[i] if model.getVal(v) > EPS: print(v.name, "=", model.getVal(v)) ``` -------------------------------- ### Create Example Dataset 1 (make_inst1) Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacetransp This function generates the first example dataset for the transportation problem. It is a Python function that returns data structures suitable for the transp model. ```python def make_inst1(): """creates example data set 1""" pass ``` -------------------------------- ### Example Function Signature Source: https://scipopt.github.io/PySCIPOpt/docs/html/pfs_8py Signature for an example function within the pfs module. This function is likely a placeholder or demonstration. ```python def example() ``` -------------------------------- ### make_data Function to Create Example Data Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespaceflp-benders A utility function that generates an example dataset for optimization problems. It references the 'pyscipopt.Multidict.multidict()' function for data handling. ```python def make_data(): """creates example data set""" pass ``` -------------------------------- ### Create Example Dataset 2 (make_inst2) Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacetransp This function generates the second example dataset for the transportation problem. It is a Python function that returns data structures suitable for the transp model. ```python def make_inst2(): """creates example data set 2""" pass ``` -------------------------------- ### Sudoku Modeling Example (sudoku.py) Source: https://scipopt.github.io/PySCIPOpt/docs/html/sudoku_8py This snippet refers to the sudoku.py file, which demonstrates how to model a Sudoku puzzle using binary programming with PySCIPOpt. It outlines variable definitions and initializations used within the example. ```Python m = Model() # Variable definitions and initializations # Example: name = str(i) + ',' + str(j) + ',' + str(k) # Example: x = {} # Example: sol = {} # Example: vtype # Example: out = '' ``` -------------------------------- ### Main Execution Block for TSP Solver Source: https://scipopt.github.io/PySCIPOpt/docs/html/tsp_8py_source This block demonstrates how to use the `solve_tsp` function. It handles command-line arguments for specifying an instance or uses a default randomized example if no argument is provided. It sets up the number of nodes and a random seed for data generation. ```python if __name__ == "__main__": import sys # Parse argument if len(sys.argv) < 2: print("Usage: %s instance" % sys.argv[0]) print("Using randomized example instead") n = 200 seed = 1 random.seed(seed) V, c = make_data(n) obj, edges = solve_tsp(V, c) print("\nTSP solved!") print("Objective value: %s" % obj) print("Edges:") for (i, j) in edges: print(" (%s, %s)" % (i, j)) ``` -------------------------------- ### Example Usage: Main Execution Block Source: https://scipopt.github.io/PySCIPOpt/docs/html/gcp__fixed__k_8py_source This block demonstrates how to use the functions defined in the file. It generates a random graph with 75 vertices and an edge probability of 0.25, then solves the graph coloring problem using the bisection method, and finally prints the minimum number of colors found and the resulting color assignment for each vertex. ```python if __name__ == "__main__": random.seed(1) V, E = make_data(75, .25) K, color = solve_gcp(V, E) print("minimum number of colors:", K) print("solution:", color) ``` -------------------------------- ### Generate Example Data for Safety Stock Model Source: https://scipopt.github.io/PySCIPOpt/docs/html/ssa_8py_source Creates an example dataset for the safety stock allocation model. It defines parameters such as the number of stages, service level, demand standard deviation, inventory costs, and production lead times. ```python def make_data(): """creates example data set""" n = 30 # number of stages z = 1.65 # for 95% service level sigma = 100 # demand's standard deviation h = {} # inventory cost T = {} # production lead time h[n] = 1 for i in range(n - 1, 0, -1): h[i] = h[i + 1] + random.randint(30, 50) K = 0 # number of segments (=sum of processing times) for i in range(1, n + 1): T[i] = random.randint(3, 5) # production lead time at stage i K += T[i] return z, sigma, h, T, K, n ``` -------------------------------- ### pyscipopt.conshdlr.consinitpre: Initialize Presolving Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacepyscipopt_1_1conshdlr informs constraint handler that the presolving process is being started ```python def pyscipopt.conshdlr.consinitpre(self, constraints): pass ``` -------------------------------- ### Wine Blending Optimization Example (lo_wines.py) Source: https://scipopt.github.io/PySCIPOpt/docs/html/lo__wines_8py_source This Python script demonstrates how to model and solve a wine blending optimization problem using the PySCIPOpt library. It defines variables for wine blends, constraints based on grape inventory, and an objective function for maximizing profit. The script then optimizes the model and prints the results, including objective value, variable values, and dual costs. ```Python """ It solves the same instance as lo_wines_simple.py: maximize 15x + 18y + 30z subject to 2x + y + z <= 60 x + 2y + z <= 60 z <= 30 x,y,z >= 0 Variables correspond to the production of three types of wine blends, made from pure-grape wines. Constraints correspond to the inventory of pure-grape wines. Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012 """ from pyscipopt import Model, quicksum, SCIP_PARAMSETTING # Initialize model model = Model("Wine blending") model.setPresolve(SCIP_PARAMSETTING.OFF) Inventory = {"Alfrocheiro": 60, "Baga": 60, "Castelao": 30} Grapes = Inventory.keys() Profit = {"Dry": 15, "Medium": 18, "Sweet": 30} Blends = Profit.keys() Use = { ("Alfrocheiro", "Dry"): 2, ("Alfrocheiro", "Medium"): 1, ("Alfrocheiro", "Sweet"): 1, ("Baga", "Dry"): 1, ("Baga", "Medium"): 2, ("Baga", "Sweet"): 1, ("Castelao", "Dry"): 0, ("Castelao", "Medium"): 0, ("Castelao", "Sweet"): 1 } # Create variables x = {} for j in Blends: x[j] = model.addVar(vtype="C", name="x(%s)" % j) # Create constraints c = {} for i in Grapes: c[i] = model.addCons(quicksum(Use[i, j] * x[j] for j in Blends) <= Inventory[i], name="Use(%s)" % i) # Objective model.setObjective(quicksum(Profit[j] * x[j] for j in Blends), "maximize") model.optimize() if model.getStatus() == "optimal": print("Optimal value:", model.getObjVal()) for j in x: print(x[j].name, "=", model.getVal(x[j]), " (red. cost: ", model.getVarRedcost(x[j]), ")") for i in c: try: dual = model.getDualsolLinear(c[i]) except: dual = None print("dual of", c[i].name, ":", dual) else: print("Problem could not be solved to optimality") ``` -------------------------------- ### make_data Function Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespaceprodmix__soco Creates an example data set for the prodmix functionality. It references the multidict function from pyscipopt. ```python def prodmix_soco.make_data(): creates example data set ``` -------------------------------- ### pyscipopt Piecewise Linear Function Examples Source: https://scipopt.github.io/PySCIPOpt/docs/html/piecewise_8py_source Illustrates different methods for implementing piecewise linear functions in pyscipopt, including 'multiple selection', 'disaggregated convex combination', and 'SOS2 constraint'. Each example sets up a model, defines variables and constraints, sets an objective, and prints the results. ```python if __name__ == "__main__": # random.seed(1) a = [-10, 10, 15, 25, 30, 35, 40, 45, 50, 55, 60, 70] b = [-20, -20, 15, -21, 0, 50, 18, 0, 15, 24, 10, 15] print("\n\n\npiecewise: multiple selection") model = Model("multiple selection") X, Y, z = mult_selection(model, a, b) # X,Y --> piecewise linear replacement of x,f(x) based on points a,b u = model.addVar(vtype="C", name="u") A = model.addCons(3 * X + 4 * Y <= 250, "A") B = model.addCons(7 * X - 2 * Y + 3 * u == 170, "B") model.setObjective(2 * X + 15 * Y + 5 * u, "maximize") model.optimize() print("X:", model.getVal(X)) print("Y:", model.getVal(Y)) print("u:", model.getVal(u)) print("\n\n\npiecewise: disaggregated convex combination") model = Model("disaggregated convex combination") X, Y, z = convex_comb_dis(model, a, b) u = model.addVar(vtype="C", name="u") A = model.addCons(3 * X + 4 * Y <= 250, "A") B = model.addCons(7 * X - 2 * Y + 3 * u == 170, "B") model.setObjective(2 * X + 15 * Y + 5 * u, "maximize") model.optimize() print("X:", model.getVal(X)) print("Y:", model.getVal(Y)) print("u:", model.getVal(u)) print("\n\n\npiecewise: disaggregated convex combination, logarithmic number of variables") model = Model("disaggregated convex combination (log)") X, Y, z = convex_comb_dis(model, a, b) u = model.addVar(vtype="C", name="u") A = model.addCons(3 * X + 4 * Y <= 250, "A") B = model.addCons(7 * X - 2 * Y + 3 * u == 170, "B") model.setObjective(2 * X + 15 * Y + 5 * u, "maximize") model.optimize() print("X:", model.getVal(X)) print("Y:", model.getVal(Y)) print("u:", model.getVal(u)) print("\n\n\npiecewise: SOS2 constraint") model = Model("SOS2") X, Y, w = convex_comb_sos(model, a, b) u = model.addVar(vtype="C", name="u") A = model.addCons(3 * X + 4 * Y <= 250, "A") B = model.addCons(7 * X - 2 * Y + 3 * u == 170, "B") model.setObjective(2 * X + 15 * Y + 5 * u, "maximize") model.optimize() print("X:", model.getVal(X)) print("Y:", model.getVal(Y)) print("u:", model.getVal(u)) print("\n\n\npiecewise: aggregated convex combination") model = Model("aggregated convex combination") # ... (rest of the aggregated convex combination example would follow) ``` -------------------------------- ### pyscipopt.conshdlr.consinitsol: Initialize Solution Process Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacepyscipopt_1_1conshdlr informs constraint handler that the branch and bound process is being started ```python def pyscipopt.conshdlr.consinitsol(self, constraints): pass ``` -------------------------------- ### kmedian Module Functions Source: https://scipopt.github.io/PySCIPOpt/docs/html/kmedian_8py_source API documentation for core functions within the kmedian module, including distance calculation, data generation, and the k-median algorithm implementation. ```APIDOC kmedian.distance def distance(x1, y1, x2, y2) Calculates the Euclidean distance between two points (x1, y1) and (x2, y2). Parameters: x1 (float): The x-coordinate of the first point. y1 (float): The y-coordinate of the first point. x2 (float): The x-coordinate of the second point. y2 (float): The y-coordinate of the second point. Returns: float: The Euclidean distance between the two points. Definition: [kmedian.py:45](kmedian_8py_source.html#l00045) kmedian.make_data def make_data(n, m, same=True) Generates synthetic data for the k-median problem. Parameters: n (int): The number of clients. m (int): The number of potential facility locations. same (bool, optional): If True, all clients share the same demand pattern. Defaults to True. Returns: tuple: A tuple containing demand data and distance matrix. Definition: [kmedian.py:50](kmedian_8py_source.html#l00050) kmedian.kmedian def kmedian(I, J, c, k) Solves the k-median problem. Parameters: I (list): A list of client indices. J (list): A list of facility location indices. c (dict): A dictionary mapping client-facility pairs to costs (distances). k (int): The number of facilities to select. Returns: tuple: A tuple containing the optimal facility locations and assigned clients. Definition: [kmedian.py:15](kmedian_8py_source.html#l00015) kmedian module Provides functionality for solving the k-median problem. Definition: [kmedian.py:1](kmedian_8py_source.html#l00001) ``` -------------------------------- ### Solve Lot Sizing with Cutting Planes (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacelotsizing__lazy Solves the lot sizing problem using cutting planes. It starts with a relaxed model and uses lazy constraints to eliminate fractional setup variables. It references the sils function. ```Python def sils_cut(T, f, c, d, h, conshdlr): """solve_sils -- solve the lot sizing problem with cutting planes - start with a relaxed model - used lazy constraints to elimitate fractional setup variables with cutting planes Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns the final model solved, with all necessary cuts added. """ # Definition at line 92 of file lotsizing_lazy.py. # References sils() ``` -------------------------------- ### Build and Solve Model with PySCIPOpt Source: https://scipopt.github.io/PySCIPOpt/docs/html/md_README Demonstrates the fundamental steps to build, solve, and retrieve solutions for an optimization model using the PySCIPOpt library. This includes importing the library, creating a model instance, adding variables, setting the objective function, adding constraints, running the optimizer, and accessing the solution. ```APIDOC from pyscipopt import Model # 1. Create a solver instance model = Model("Example") # model name is optional # 2. Add variables x = model.addVar("x") y = model.addVar("y", vtype="INTEGER") # 3. Set the objective function model.setObjective(x + y) # 4. Add constraints model.addCons(2*x - y*y >= 0) # 5. Optimize the model model.optimize() # 6. Get the best solution sol = model.getBestSol() # 7. Print solution values print("x: {}".format(sol[x])) print("y: {}".format(sol[y])) # --- Method Details --- Model(name=None, ...) Creates a new SCIP model instance. Parameters: name (str, optional): A name for the model. Defaults to None. addVar(name=None, lb=None, ub=None, obj=None, vtype=None, unit=None, zero=None, nonzeroval=None, constant=None, initial=None, separate=None, enforce = None, rootadj = None, cutrootadj = None, primalstart = None, dom = None, originalname=None, vartype=None) Adds a variable to the model. Parameters: name (str, optional): Name of the variable. lb (float, optional): Lower bound of the variable. Defaults to 0. ub (float, optional): Upper bound of the variable. Defaults to infinity. obj (float, optional): Coefficient of the variable in the objective function. vtype (str, optional): Type of the variable ('CONTINUOUS', 'INTEGER', 'BINARY'). Defaults to 'CONTINUOUS'. ... (other parameters for advanced usage) Returns: The created variable object. setObjective(expr, sense=None) Sets the objective function for the model. Parameters: expr (SCIP expression): The expression defining the objective function. sense (str, optional): The optimization sense ('minimize' or 'maximize'). Defaults to 'minimize'. addCons(expr, name=None, initial=None, separate=None, enforce=None, rootadj=None, cutrootadj=None, primalstart=None, dom=None, originalname=None, consType=None) Adds a constraint to the model. Parameters: expr (SCIP expression): The expression defining the constraint. name (str, optional): Name of the constraint. ... (other parameters for advanced usage) Returns: The created constraint object. optimize() Starts the optimization process. getBestSol() Retrieves the best solution found by the optimizer. Returns: A solution object (dictionary-like) mapping variables to their values. ``` -------------------------------- ### Installation Recommendation Source: https://scipopt.github.io/PySCIPOpt/docs/html/md_CHANGELOG Recommends using `pip install .` over `python setup.py install` in the INSTALL documentation. This promotes standard Python package installation practices. ```APIDOC INSTALL documentation - Updated recommendation: Use `pip install .` for installation. - Replaces: `python setup.py install` ``` -------------------------------- ### pfs.example() Function Source: https://scipopt.github.io/PySCIPOpt/docs/html/namespacepfs This function is designed to create an example data set. It is part of the pfs namespace and serves as a utility for generating sample data for testing or demonstration purposes. ```Python def pfs.example (): creates example data set ``` -------------------------------- ### PySCIPOpt: SILS Lot Sizing with Cutting Planes Source: https://scipopt.github.io/PySCIPOpt/docs/html/lotsizing__lazy_8py_source Solves the lot sizing problem using cutting planes with lazy constraints. It starts with a relaxed LP model, relaxes integer variables, and uses a custom constraint handler to add cuts that eliminate fractional setup variables. ```python def sils_cut(T, f, c, d, h, conshdlr): """solve_sils -- solve the lot sizing problem with cutting planes - start with a relaxed model - used lazy constraints to elimitate fractional setup variables with cutting planes Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns the final model solved, with all necessary cuts added. """ Ts = range(1, T + 1) model = sils(T, f, c, d, h) y, x, I = model.data # relax integer variables for t in Ts: model.chgVarType(y[t], "C") model.addVar(vtype="B", name="fake") # for making the problem MIP # compute D[i,j] = sum_{t=i}^j d[t] D = {} for t in Ts: s = 0 for j in range(t, T + 1): s += d[j] D[t, j] = s # include the lot sizing constraint handler model.includeConshdlr(conshdlr, "SILS", "Constraint handler for single item lot sizing", sepapriority=0, enfopriority=-1, chckpriority=-1, sepafreq=-1, propfreq=-1, eagerfreq=-1, maxprerounds=0, delaysepa=False, delayprop=False, needscons=False, presoltiming=SCIP_PRESOLTIMING.FAST, proptiming=SCIP_PROPTIMING.BEFORELP) ``` -------------------------------- ### Solve Traveling Salesman Problem with PySCIPOpt Source: https://scipopt.github.io/PySCIPOpt/docs/html/tsp_8py_source Solves the Traveling Salesman Problem (TSP) using a cutting plane approach with PySCIPOpt. It starts with an assignment model and iteratively adds cuts (`addcut` or `addcut2`) to eliminate sub-cycles until an optimal solution is found. It requires nodes `V` and edge costs `c`. Returns the objective value and the list of edges. ```python def solve_tsp(V, c): """solve_tsp -- solve the traveling salesman problem - start with assignment model - add cuts until there are no sub-cycles Parameters: - V: set/list of nodes in the graph - c[i,j]: cost for traversing edge (i,j) Returns the optimum objective value and the list of edges used. """ def addcut(cut_edges): G = networkx.Graph() G.add_edges_from(cut_edges) Components = list(networkx.connected_components(G)) if len(Components) == 1: return False model.freeTransform() for S in Components: model.addCons([quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(x[i, j] for i in S for j in S if j > i) <= len(S) - 1) print("cut: len(%s) <= %s" % (S, len(S) - 1)) return True def addcut2(cut_edges): G = networkx.Graph() G.add_edges_from(cut_edges) Components = list(networkx.connected_components(G)) if len(Components) == 1: return False model.freeTransform() for S in Components: T = [set](https://scip.zib.de/doc/html/structset.php)(V) - [set](https://scip.zib.de/doc/html/structset.php)(S) print("S:", S) print("T:", T) model.addCons([quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(x[i, j] for i in S for j in T if j > i) + [quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(x[i, j] for i in T for j in S if j > i) >= 2) print("cut: %s >= 2" % "+".join([("x[%s,%s]" % (i, j)) for i in S for j in T if j > i])) return True # main part of the solution process: model = Model("tsp") model.hideOutput() # silent/verbose mode x = {} for i in V: for j in V: if j > i: x[i, j] = model.addVar(ub=1, name="x(%s,%s)" % (i, j)) for i in V: model.addCons([quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(x[j, i] for j in V if j < i) + \ [quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(x[i, j] for j in V if j > i) == 2, "Degree(%s)" % i) model.setObjective([quicksum](namespacepyscipopt_1_1expr.html#aa1762100a5cda9d1007ae3741f12b693)(c[i, j] * x[i, j] for i in V for j in V if j > i), "minimize") EPS = 1.e-6 isMIP = False while True: model.optimize() edges = [] for (i, j) in x: if model.getVal(x[i, j]) > EPS: edges.append((i, j)) if addcut(edges) == False: if isMIP: # integer variables, components connected: solution found break model.freeTransform() for (i, j) in x: # all components connected, switch to integer model model.chgVarType(x[i, j], "B") isMIP = True return model.getObjVal(), edges ``` -------------------------------- ### Presol Class Methods Source: https://scipopt.github.io/PySCIPOpt/docs/html/classpyscipopt_1_1presol_1_1Presol Documentation for the Presol class methods, including initialization, execution, and deinitialization of the presolver. ```APIDOC Presol Class Documentation: This class provides methods to interact with the SCIP presolver. Member Functions: - presolexec(self, nrounds, presoltiming) - Executes the presolver. - Parameters: - self: The instance of the Presol class. - nrounds: The number of presolving rounds to execute. - presoltiming: A flag or value indicating presolver timing behavior. - Description: executes presolver - presolexit(self) - Deinitializes the presolver. - Parameters: - self: The instance of the Presol class. - Description: deinitializes presolver - presolexitpre(self) - Informs the presolver that the presolving process is finished. - Parameters: - self: The instance of the Presol class. - Description: informs presolver that the presolving process is finished - presolfree(self) - Frees the memory allocated for the presolver. - Parameters: - self: The instance of the Presol class. - Description: frees memory of presolver - presolinit(self) - Initializes the presolver. - Parameters: - self: The instance of the Presol class. - Description: initializes presolver - presolinitpre(self) - Informs the presolver that the presolving process is being started. - Parameters: - self: The instance of the Presol class. - Description: informs presolver that the presolving process is being started ``` -------------------------------- ### Model Write LP Method Example Source: https://scipopt.github.io/PySCIPOpt/docs/html/md_CHANGELOG Example of using the `Model.writeLP` method to save the current problem formulation to an LP file. ```Python from pyscipopt import Model model = Model() # Add variables and constraints to the model # ... # Write the problem to an LP file model.writeLP("my_problem.lp") ``` -------------------------------- ### make_data: Generate Example Data for PySCIPOpt Source: https://scipopt.github.io/PySCIPOpt/docs/html/prodmix__soco_8py_source Creates a sample dataset for the robust production planning problem. It defines the coefficients matrix 'a', material prices 'p', and required component amounts 'LB' using PySCIPOpt's multidict utility. This function is useful for testing or demonstrating the prodmix model. ```python from pyscipopt import Model, quicksum, multidict def make_data(): """creates example data set""" a = {(1, 1): .25, (1, 2): .15, (1, 3): .2, (2, 1): .3, (2, 2): .3, (2, 3): .1, (3, 1): .15, (3, 2): .65, (3, 3): .05, (4, 1): .1, (4, 2): .05, (4, 3): .8 } epsilon = 0.01 I, p = multidict({1: 5, 2: 6, 3: 8, 4: 20}) K, LB = multidict({1: .2, 2: .3, 3: .2}) return I, K, a, p, epsilon, LB ``` -------------------------------- ### Logical Constraints Tutorial (Python) Source: https://scipopt.github.io/PySCIPOpt/docs/html/dir_a562ccaa5e17bafcab246de9ef084f0c This Python script serves as a tutorial example on how to use AND, OR, and XOR constraints within SCIP. It demonstrates modeling complex logical relationships. ```python ``` -------------------------------- ### PySCIPOpt Core Functions and Classes Source: https://scipopt.github.io/PySCIPOpt/docs/html/eoq__en_8py_source Documentation for key PySCIPOpt components used in the EOQ example, including `quicksum` for efficient summation, `multidict` for data handling, and the `eoq` function itself. ```APIDOC pyscipopt.expr.quicksum def quicksum(termlist) Parameters: - termlist: A list of terms to be summed. Description: Efficiently computes the sum of terms, often used for creating constraints and objectives. Definition: expr.pxi:357 ``` ```APIDOC pyscipopt.Multidict.multidict def multidict(D) Parameters: - D: A dictionary or list of tuples to convert into a multidict. Description: Creates a multidict object, which is a dictionary where keys can map to multiple values or be accessed by index. Definition: Multidict.py:3 ``` ```APIDOC eoq_en.eoq def eoq(I, F, h, d, w, W, a0, aK, K) Parameters: - I: set of items - F[i]: ordering cost for item i - h[i]: holding cost for item i - d[i]: demand for item i - w[i]: unit weight for item i - W: capacity (limit on order quantity) - a0: lower bound on the cycle time (x axis) - aK: upper bound on the cycle time (x axis) - K: number of linear pieces to use in the approximation Description: Implements the multi-item capacitated economic ordering quantity (EOQ) model using a convex combination formulation. Returns: A PySCIPOpt model object ready to be solved. Definition: eoq_en.py:11 ``` -------------------------------- ### PySCIPOpt Propagator Initialization Source: https://scipopt.github.io/PySCIPOpt/docs/html/propagator_8pxi_source Provides documentation for the initialization methods of the SCIP propagator. Includes general initialization and pre-solve initialization. ```python def propinit(self) **Definition:** propagator.pxi:10 ``` ```python def propinitpre(self) **Definition:** propagator.pxi:26 ``` -------------------------------- ### Model Creation, Optimization, and Output Source: https://scipopt.github.io/PySCIPOpt/docs/html/mctransp_8py_source This snippet demonstrates the main execution flow: initializing the optimization model with the prepared data, writing the problem to a file, solving it, and printing the objective value and the details of the optimal shipments. ```python if __name__ == "__main__": # Assuming make_inst3() returns I, J, K, c, d, M as defined above I, J, K, c, d, M = make_inst3() model = mctransp(I, J, K, c, d, M) model.writeProblem("transp.lp") model.optimize() print("Optimal value:", model.getObjVal()) EPS = 1.e-6 x = model.data for (i, j, k) in x: if model.getVal(x[i, j, k]) > EPS: print("sending %10s units of %3s from plant %3s to customer %3s" % (model.getVal(x[i, j, k]), k, j, i)) ``` -------------------------------- ### SEPA Module Initialization and Execution Workflow Source: https://scipopt.github.io/PySCIPOpt/docs/html/sepa_8pxi_source Demonstrates a typical workflow for initializing and executing a separator within PySCIPOpt. It involves creating a solution object, associating data with a SEPA instance, executing the separator on the solution, and retrieving results. ```python solution = Solution.create(scip, sol) PySepa = sepadata result_dict = PySepa.sepaexecsol(solution) result[0] = result_dict.get("result", result[0]) return SCIP_OKAY ``` -------------------------------- ### PySCIPOpt Lotsizing Example Generator API Source: https://scipopt.github.io/PySCIPOpt/docs/html/lotsizing__lazy_8py_source Generates an example dataset for the single-item lot sizing problem. It returns time horizon, fixed costs, variable costs, demands, and holding costs. ```APIDOC lotsizing_lazy.mk_example def mk_example() **Definition:** [lotsizing_lazy.py:134](lotsizing__lazy_8py_source.html#l00134) ```