### Execute DOcplex CP Example Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/getting_started Commands to set the Python path and run a specific DOcplex Constraint Programming example script, 'color.py', from the command line. This demonstrates how to execute a DOcplex example after installation. ```bash set PYTHONPATH=. python examples/cp/basic/color.py ``` -------------------------------- ### Install DOcplex Python Library Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/getting_started Command to install the IBM Decision Optimization CPLEX Modeling for Python (DOcplex) library using the pip package manager. Pip is the standard tool for installing Python packages. ```bash pip install docplex ``` -------------------------------- ### Solve Scheduling Problem with Setup Times using docplex.cp Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.setup_times.py This Python script demonstrates how to solve a scheduling problem involving two alternative heterogeneous machines using IBM's docplex.cp library. The problem includes sequence-dependent setup times and forbidden transitions between different task types. It aims to minimize the makespan by modeling setup times with transition distances and enforcing sequencing with `no_overlap` constraints. The script initializes problem data, prepares it for modeling, and begins building the CP model by defining tasks and their alternatives on different machines. ```python # -------------------------------------------------------------------------- # # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- """ This example solves a scheduling problem on two alternative heterogeneous machines. A set of tasks {a_1,...,a_n} has to be executed on either one of the two machines. Different types of tasks are distinguished, the type of task a_i is denoted tp_i. A machine m needs a sequence dependent setup time setup(tp,tp') to switch from a task of type tp to the next task of type tp'. Furthermore some transitions tp->tp' are forbidden. The two machines are different: they process tasks with different speed and have different setup times and forbidden transitions. The objective is to minimize the makespan. The model uses transition distances and no_overlap constraints to model machines setup times. The no_overlap constraint is specified to enforce transition distance between immediate successors on the sequence. Forbidden transitions are modeled with a very large transition distance. Please refer to documentation for appropriate setup of solving configuration. """ from docplex.cp.model import * #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- # Number of types NB_TYPES = 5 # Setup times of machine M1. -1 means forbidden transition SETUP_M1 = [[0, 26, 8, 3, -1], [22, 0, -1, 4, 22], [28, 0, 0, 23, 9], [29, -1, -1, 0, 8], [26, 17, 11, 7, 0]] # Setup times of machine M2. -1 means forbidden transition SETUP_M2 = [[0, 5, 28, -1, 2], [-1, 0, -1, 7, 10], [19, 22, 0, 28, 17], [7, 26, 13, 0, -1], [13, 17, 26, 20, 0]] # Task types TASK_TYPE = [3, 3, 1, 1, 1, 1, 2, 0, 0, 2, 4, 4, 3, 3, 2, 3, 1, 4, 4, 2, 2, 1, 4, 2, 2, 0, 3, 3, 2, 1, 2, 1, 4, 3, 3, 0, 2, 0, 0, 3, 2, 0, 3, 2, 2, 4, 1, 2, 4, 3] # Number of tasks NB_TASKS = len(TASK_TYPE) # Task duration if executed on machine M1 TASK_DUR_M1 = [ 4, 17, 4, 7, 17, 14, 2, 14, 2, 8, 11, 14, 4, 18, 3, 2, 9, 2, 9, 17, 18, 19, 5, 8, 19, 12, 17, 11, 6, 3, 13, 6, 19, 7, 1, 3, 13, 5, 3, 6, 11, 16, 12, 14, 12, 17, 8, 8, 6, 6] # Task duration if executed on machine M2 TASK_DUR_M2 = [12, 3, 12, 15, 4, 9, 14, 2, 5, 9, 10, 14, 7, 1, 11, 3, 15, 19, 8, 2, 18, 17, 19, 18, 15, 14, 6, 6, 1, 2, 3, 19, 18, 2, 7, 16, 1, 18, 10, 14, 2, 3, 14, 1, 1, 6, 19, 5, 17, 4] #----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Put max value for forbidden transitions in setup times for i in range(NB_TYPES): for j in range(NB_TYPES): if SETUP_M1[i][j] < 0: SETUP_M1[i][j] = INTERVAL_MAX; if SETUP_M2[i][j] < 0: SETUP_M2[i][j] = INTERVAL_MAX; #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Build tasks for machine M1 and M2 tasks_m1 = [interval_var(name='A{}_M1_TP{}'.format(i, TASK_TYPE[i]), optional=True, size=TASK_DUR_M1[i]) for i in range(NB_TASKS)] tasks_m2 = [interval_var(name='A{}_M2_TP{}'.format(i, TASK_TYPE[i]), optional=True, size=TASK_DUR_M1[i]) for i in range(NB_TASKS)] # Build actual tasks as an alternative between machines tasks = [interval_var(name='A{}_TP{}'.format(i, TASK_TYPE[i])) for i in range(NB_TASKS)] mdl.add(alternative(tasks[i], [tasks_m1[i], tasks_m2[i]]) for i in range(NB_TASKS)) # Build a map to retrieve task id from variable name (for display purpose) task_id = dict() for i in range(NB_TASKS): task_id[tasks_m1[i].get_name()] ``` -------------------------------- ### System and Library Version Check Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/ucp_pandas Provides details about the operating system, Python version, and installed versions of DOcplex and pandas libraries. This output confirms the environment setup and the availability of necessary dependencies for the optimization model. ```Python Console Output * system is: Windows 64bit * Python version 3.7.3, located at: c:\local\python373\python.exe * docplex is present, version is (2, 11, 0) * pandas is present, version is 0.25.1 ``` -------------------------------- ### Set Starting Point for CpoModel Solver Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/model Defines an initial partial solution for CP Optimizer to guide the search. It must be a CpoModelSolution object, primarily considering integer and interval variables. Provides an example of how to create and populate a starting point. ```APIDOC CpoModel.set_starting_point(stpoint) Description: Set a model starting point. A starting point specifies a (possibly partial) solution that could be used by CP Optimizer to start the search. This starting point is represented by an object of class :class:`~docplex.cp.solution.CpoModelSolution`, with the following restrictions: * Only integer and interval variables are taken into account. If present, all other elements are simply ignored. * In integer variable, if the domain is not fixed to a single value, only a single range of values is allowed. If the variable domain is sparse, the range domain_min..domain_max is used. An empty starting point can be created using method :meth:`~CpoModel.create_empty_solution`, and then filled using dedicated methods :meth:`~docplex.cp.solution.CpoModelSolution.add_integer_var_solution` and :meth:`~docplex.cp.solution.CpoModelSolution.add_interval_var_solution`, or using indexed assignment as in the following example: :: mdl = CpoModel() a = integer_var(0, 3) b = interval_var(length=(1, 4)) . . . stp = mdl.create_empty_solution() stp[a] = 2 stp[b] = (2, 3, 4) mdl.set_starting_point(stp) Starting point is available for CPO solver release greater or equal to 12.7.0. Args: stpoint: Starting point, object of class :class:`~docplex.cp.solution.CpoModelSolution` ``` ```Python def set_starting_point(self, stpoint): assert (stpoint is None) or isinstance(stpoint, CpoModelSolution), \ "Argument 'stpoint' should be None or an object of class CpoModelSolution" self.starting_point = stpoint ``` -------------------------------- ### Define Utility Functions for Solution Visualization in DOcplex.CP Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.setup_times.py This section defines two Python functions: `compact` and `showsequence`. The `compact` function extracts a numeric identifier from a task name. The `showsequence` function uses `docplex.cp.utils_visu` to visualize a sequence variable's solution, displaying intervals for tasks and transitions between them, incorporating setup times. ```python def compact(name): # Example: A31_M1_TP1 -> 31 task, foo = name.split('_', 1) return task[1:] import docplex.cp.utils_visu as visu def showsequence(s, setup): seq = res.get_var_solution(s) visu.sequence(name=s.get_name()) vs = seq.get_value() for v in vs: nm = v.get_name() visu.interval(v, TASK_TYPE[task_id[nm]], compact(nm)) for i in range(len(vs) - 1): end = vs[i].get_end() tp1 = TASK_TYPE[task_id[vs[i].get_name()]] tp2 = TASK_TYPE[task_id[vs[i + 1].get_name()]] visu.transition(end, end + setup[tp1][tp2]) ``` -------------------------------- ### CpoModel.set_starting_point Method and Example Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.model.py Sets a starting point for the CP Optimizer search. This starting point is a possibly partial solution represented by a `CpoModelSolution` object, primarily considering integer and interval variables. An empty starting point can be created and then populated with variable assignments. ```APIDOC CpoModel.set_starting_point(stpoint) stpoint: Starting point, object of class CpoModelSolution ``` ```Python mdl = CpoModel() a = integer_var(0, 3) b = interval_var(length=(1, 4)) . . . stp = mdl.create_empty_solution() stp[a] = 2 stp[b] = (2, 3, 4) mdl.set_starting_point(stp) ``` -------------------------------- ### Execute a DOcplexMP Python Example from Command Line Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/samples This snippet demonstrates how to run a DOcplexMP example Python script, specifically 'diet.py', from a Windows command prompt. It shows the command to execute the script and the typical output, which includes the objective function value and various Key Performance Indicators (KPIs) calculated by the optimization solver. ```Shell c:\docplex\examples\mp\modeling> python diet.py * model solved as function with objective: 2.69041 1> Servings of ({Spaghetti W/ Sauce}) = 2.155 2> Servings of ({Chocolate Chip Cookies}) = 10.000 3> Servings of ({2% Lowfat Milk}) = 1.831 4> Servings of ({Hotdog}) = 0.930 * KPI: Total Calories=2000.000 * KPI: Total Calcium=800.000 * KPI: Total Iron=11.278 * KPI: Total Vit_A=8518.433 * KPI: Total Dietary_Fiber=25.000 * KPI: Total Carbohydrates=256.806 * KPI: Total Protein=51.174 ``` -------------------------------- ### Define Scheduling Model Constraints and Objective with DOcplex.CP Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.setup_times.py This snippet defines sequence variables for two machines (M1 and M2) and applies no-overlap constraints to prevent tasks from overlapping on each machine, considering setup times. It also sets the objective to minimize the overall makespan of the schedule by minimizing the maximum end time of all tasks. ```python = i task_id[tasks_m2[i].get_name()] = i # Constrain tasks to no overlap on each machine s1 = sequence_var(tasks_m1, types=TASK_TYPE, name='M1') s2 = sequence_var(tasks_m2, types=TASK_TYPE, name='M2') mdl.add(no_overlap(s1, SETUP_M1, 1)) mdl.add(no_overlap(s2, SETUP_M2, 1)) # Minimize the makespan mdl.add(minimize(max([end_of(tasks[i]) for i in range(NB_TASKS)]))) ``` -------------------------------- ### Execute DOcplex CP Example (color.py) Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/samples This snippet demonstrates the command-line execution of a DOcplex CP example script named 'color.py' using Python. It shows the typical output, including the model's solving status and the detailed feasible solution with assigned colors for different entities. ```Bash > python examples/cp/basic/color.py Solving model.... Solution status: Feasible Belgium: Yellow Denmark: Yellow France: Red Germany: Green Luxembourg: Blue Netherlands: Red ``` -------------------------------- ### Python: Example Implementation for Multiple Solver Runs Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/model An example Python implementation showing how to create a solver, execute multiple runs with seeds, and clean up the solver instance. ```Python solver = self.create_solver(**kwargs) rsol = solver.run_seeds(nbrun) solver.end() return rsol ``` -------------------------------- ### Install DOcplex Python Library Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/README.md Command to install the IBM Decision Optimization Modeling for Python (DOcplex) library using pip. This command will also automatically install the necessary third-party dependencies. ```Bash pip install docplex ``` -------------------------------- ### Install DOcplex using pip Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/getting_started_python This command installs the IBM Decision Optimization CPLEX Modeling for Python (DOcplex) library from PyPI using the pip package manager. Pip is the standard tool for installing Python packages and is included with recent Python versions. ```Shell pip install docplex ``` -------------------------------- ### Python: Example Implementation for Explaining Solve Failures Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/model An example Python implementation demonstrating how to use the `explain_failure` method to diagnose solver issues. ```Python solver = self.create_solver(**kwargs) msol = solver.explain_failure(ltags) solver.end() return msol ``` -------------------------------- ### Python: Example Implementation for Adding Solver Listener Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/model An example Python implementation showing how to add a solver listener, including an assertion for type checking. ```Python assert isinstance(lstnr, CpoSolverListener), \ "Listener should be an object of class docplex.cp.solver.solver_listener.CpoSolverListener" self.listeners.append(lstnr) ``` -------------------------------- ### Python: Example Implementation for Adding Solver Callback Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/model An example Python implementation showing how to add a solver callback, including an assertion for type checking. ```Python assert isinstance(cback, CpoCallback), \ "CPO callback should be an object of class docplex.cp.solver.cpo_callback.CpoCallback" self.callbacks.append(cback) ``` -------------------------------- ### Solve DOcplex.CP Model and Display Results with Visualization Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.setup_times.py This snippet demonstrates how to solve the defined DOcplex.CP model using `mdl.solve` with specified failure and time limits. After solving, it prints the solution. If visualization is enabled, it generates a timeline view of the solution for both machines (M1 and M2) using the `showsequence` utility function and displays it. ```python print('Solving model...') res = mdl.solve(FailLimit=100000, TimeLimit=10) print('Solution: ') res.print_solution() if res and visu.is_visu_enabled(): visu.timeline('Solution for SchedSetup') showsequence(s1, SETUP_M1) showsequence(s2, SETUP_M2) visu.show() ``` -------------------------------- ### Get Model Starting Point Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.model.py Retrieves the starting point defined for the model. Returns None if no starting point is specified. ```APIDOC CpoModel.get_starting_point() -> Any | None Returns: Model starting point, None if none. ``` -------------------------------- ### Configure DOcplex MIP Start to Include All Variables Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/docplex.mp.model This Python example shows how to add a MIP start solution to a DOcplex model, ensuring that all variables, including continuous ones, are considered. The `complete_vars=True` argument ensures a comprehensive start. ```Python mdl.add_mip_start(sol, write_level=WriteLevel.AllVars, complete_vars=True) ``` -------------------------------- ### Python Function: Get Start Time of Interval Variable Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/modeler Retrieves an integer expression representing the start time of a specified interval variable. An optional `absentValue` can be provided for cases where the interval is not present. ```python def start_of(interval, absentValue=None): interval = _convert_arg(interval, "interval", Type_IntervalVar) if absentValue is None: return CpoFunctionCall(Oper_start_of, Type_IntExpr, (interval,)) return CpoFunctionCall(Oper_start_of, Type_IntExpr, (interval, _convert_arg(absentValue, "absentValue", Type_Int))) ``` ```APIDOC start_of(interval, absentValue=None) Returns the start of a specified interval variable. This function returns an integer expression that is equal to start of the interval variable *interval* if it is present. If it is absent, then the value of the expression is *absentValue* (zero by default). Args: interval: Interval variable. absentValue (Optional): Value to return if the interval variable interval becomes absent. Zero if not given. Returns: An integer expression ``` -------------------------------- ### Get MIP Starts Iterator from DOcplex Model Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/docplex.mp.model This method returns an iterator for the MIP starts associated with the DOcplex model. Each element yielded by the iterator is a tuple containing a solution object and an effort level. This functionality was introduced in version 2.10 of DOcplex. ```APIDOC iter_mip_starts() Returns: An iterator of tuples (solution, effort_level) solution: An instance of docplex.mp.solution.SolveSolution effort_level: An enumerated value of type docplex.mp.constants.EffortLevel New in version 2.10 ``` -------------------------------- ### Example: Implementing and Using PublishResultAsDf Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/_modules/docplex/mp/publish Demonstrates how to define a solver class that inherits from `PublishResultAsDf` and configures its output properties. It also shows how to use the `write_output_table` method to publish results obtained from the solver. ```python class SomeSolver(PublishResultAsDf): def __init__(self, output_customizer): # output something if context.solver.autopublish.somesolver_output is set self.output_table_property_name = 'somesolver_output' # output filename unless specified by somesolver_output: self.default_output_table_name = 'somesolver.csv' # customizer if users wants one self.output_table_customizer = output_customizer # uses pandas.DataFrame if possible, otherwise will use namedtuples self.output_table_using_df = True def solve(self): # do something here and return a result as a df result = pandas.DataFrame(columns=['A','B','C']) return result solver = SomeSolver() results = solver.solve() solver.write_output_table(results) ``` -------------------------------- ### Get Start Time of Previous Interval in Sequence Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/modeler This function returns an integer expression representing the start time of the interval variable immediately preceding the given `interval` in the `sequence`. It handles cases where `interval` is the first in the sequence or is absent, returning `firstValue` or `absentValue` respectively. ```python def start_of_prev(sequence, interval, firstValue=None, absentValue=None): """ Returns an integer expression that represents the start of the interval variable that is previous. This function returns an integer expression that represents the start of the interval variable that is previous to *interval* in sequence variable *sequence*. When *interval* is present and is the first interval of *sequence*, it returns the constant integer value *firstValue* (zero by default). When *interval* is absent, it returns the constant integer value *absentValue* (zero by default). Args: sequence: Sequence variable. interval: Interval variable. firstValue: (Optional) Value to return if interval variable interval is the first one in sequence. absentValue (Optional): Value to return if interval variable interval becomes absent. Returns: An integer expression """ return _sequence_operation(Oper_start_of_prev, sequence, interval, firstValue, false, absentValue) ``` ```APIDOC start_of_prev(sequence, interval, firstValue=None, absentValue=None) Description: Returns an integer expression that represents the start of the interval variable that is previous. Parameters: sequence: Sequence variable. interval: Interval variable. firstValue: (Optional) Value to return if interval variable interval is the first one in sequence. absentValue: (Optional) Value to return if interval variable interval becomes absent. Returns: An integer expression ``` -------------------------------- ### Get Start Time of Next Interval in Sequence Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/modeler This function returns an integer expression representing the start time of the interval variable immediately following the given `interval` in the `sequence`. It handles cases where `interval` is the last in the sequence or is absent, returning `lastValue` or `absentValue` respectively. ```python def start_of_next(sequence, interval, lastValue=None, absentValue=None): """ Returns an integer expression that represents the start of the interval variable that is next. This function returns an integer expression that represents the start of the interval variable that is next to *interval* in sequence variable *sequence*. When *interval* is present and is the last interval of *sequence*, it returns the constant integer value *lastValue* (zero by default). When *interval* is absent, it returns the constant integer value *absentValue* (zero by default). Args: sequence: Sequence variable. interval: Interval variable. lastValue: (Optional) Value to return if interval variable interval is the last one in sequence. absentValue (Optional): Value to return if interval variable interval becomes absent. Returns: An integer expression """ return _sequence_operation(Oper_start_of_next, sequence, interval, lastValue, true, absentValue) ``` ```APIDOC start_of_next(sequence, interval, lastValue=None, absentValue=None) Description: Returns an integer expression that represents the start of the interval variable that is next. Parameters: sequence: Sequence variable. interval: Interval variable. lastValue: (Optional) Value to return if interval variable interval is the last one in sequence. absentValue: (Optional) Value to return if interval variable interval becomes absent. Returns: An integer expression ``` -------------------------------- ### Main Execution Block for Production Model Solving Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/production This Python block demonstrates the main entry point for the production optimization script. It initializes and builds the optimization model, prints its information, attempts to solve it, and then either displays the solution and exports it to a 'solution.json' file if successful, or indicates that no solution was found. ```Python if __name__ == '__main__': # Build the model model = build_production_problem(PRODUCTS, RESOURCES, CONSUMPTIONS) model.print_information() # Solve the model. if model.solve(): print_production_solution(model, PRODUCTS) # Save the CPLEX solution as "solution.json" program output with get_environment().get_output_stream("solution.json") as fp: model.solution.export(fp, "json") else: print("Problem has no solution") ``` -------------------------------- ### Solve and Visualize Job-Shop Scheduling Solution with docplex.cp Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.job_shop_basic.py This final section solves the formulated docplex.cp model with a specified time limit. Upon finding a solution, it prints the solution details. If visualization is enabled, it uses `docplex.cp.utils_visu` to generate a timeline visualization of the schedule, showing operations on both job and machine panels. ```python #----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- # Solve model print('Solving model...') res = mdl.solve(TimeLimit=10) print('Solution:') res.print_solution() # Draw solution import docplex.cp.utils_visu as visu if res and visu.is_visu_enabled(): visu.timeline('Solution for job-shop ' + filename) visu.panel('Jobs') for i in range(NB_JOBS): visu.sequence(name='J' + str(i), intervals=[(res.get_var_solution(job_operations[i][j]), MACHINES[i][j], 'M' + str(MACHINES[i][j])) for j in range(NB_MACHINES)]) visu.panel('Machines') for k in range(NB_MACHINES): visu.sequence(name='M' + str(k), intervals=[(res.get_var_solution(machine_operations[k][i]), k, 'J' + str(i)) for i in range(NB_JOBS)]) visu.show() ``` -------------------------------- ### Python: Get Interval Variable Value (CpoIntervalVarSolution) Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/solution Returns the complete value of the interval variable as a tuple. If the variable is fully instantiated, it returns a tuple of three integers (start, end, size). If partially instantiated, it returns (start, end, size, length), where individual components can be integers or domains. An empty tuple is returned if the interval variable is absent. ```Python def get_value(self): """ Gets the interval variable value as a tuple (start, end, size), or () if absent. If the variable is absent, then the result is an empty tuple. If the variable is fully instantiated, the result is a tuple of 3 integers (start, end, size). The variable length, easy to compute as end - start, can also be retrieved by calling :meth:`get_length`. If the variable is partially instantiated, the result is a tuple (start, end, size, length) where each individual value can be an integer or an interval expressed as a tuple. Returns: Interval variable value as a tuple. """ if self.is_present(): if self.length is None: return IntervalVarValue(self.start, self.end, self.size) else: return IntervalVarPartialValue(self.start, self.end, self.size, self.length) return () ``` -------------------------------- ### Python Example: Using a Solver to Publish Results Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/docplex.mp.publish Demonstrates the typical usage pattern for a solver class that implements `PublishResultAsDf`. It shows how to instantiate the solver, execute its `solve` method to obtain results, and then use `write_output_table` to publish those results. ```Python solver = SomeSolver() results = solver.solve() solver.write_output_table(results) ``` -------------------------------- ### Python Function: Get Length of Interval Variable Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/modeler Retrieves an integer expression representing the length (end - start) of a specified interval variable. An optional `absentValue` can be provided for cases where the interval is not present. ```python def length_of(interval, absentValue=None): interval = _convert_arg(interval, "interval", Type_IntervalVar) if absentValue is None: return CpoFunctionCall(Oper_length_of, Type_IntExpr, (interval,)) return CpoFunctionCall(Oper_length_of, Type_IntExpr, (interval, _convert_arg(absentValue, "absentValue", Type_Int))) ``` ```APIDOC length_of(interval, absentValue=None) Returns the length of specified interval variable. This function returns an integer expression that is equal to the length (*end - start*) of the interval variable *interval* if it is present. If it is absent, then the value of the expression is *absentValue* (zero by default). Args: interval: Interval variable. absentValue (Optional): Value to return if the interval variable interval becomes absent. Zero if not given. Returns: An integer expression ``` -------------------------------- ### Start Search (docplex.cp.solver) Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.solver.solver.py Begins a new search process within the solver. Solutions can then be retrieved iteratively using the `search_next()` method. ```APIDOC start_search() Description: Start a new search. Solutions are retrieved using method search_next(). Raises: CpoNotSupportedException - method not available in this solver agent. ``` -------------------------------- ### docplex.mp.solution.SolutionListener API Reference Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/_modules/docplex/mp/progress API documentation for the `SolutionListener` class, detailing its methods for handling intermediate solutions during CPLEX search, including `notify_solution` for processing solutions and `notify_start` for initialization. ```APIDOC class SolutionListener: notify_solution(sol: docplex.mp.solution.SolveSolution) Description: Generic method to be redefined by custom listeners to handle intermediate solutions. This method is called by the CPLEX search with an intermediate solution. Parameters: sol: An instance of :class:`docplex.mp.solution.SolveSolution`. Note: Called at each node of the MIP search; identical solutions (different objects, same values) may be passed multiple times. notify_start() Description: Redefinition of the generic notify_start() method to clear all data modified by solve(). ``` -------------------------------- ### Python Environment and Library Versions Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/sports_scheduling This snippet displays the system architecture, Python version, and the installed versions of key libraries like DOcplex and pandas, confirming the development environment setup. ```Console Output * system is: Windows 64bit * Python version 3.7.3, located at: c:\local\python373\python.exe * docplex is present, version is (2, 11, 0) * pandas is present, version is 0.25.1 ``` -------------------------------- ### APIDOC: CpoSolverListener.start_operation Method Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.solver.solver_listener.py Notifies that a general operation is started by the solver. ```APIDOC CpoSolverListener: start_operation(solver: CpoSolver, op: OPERATION_*): solver: Originator CPO solver (object of class CpoSolver) op: Operation that is started, in constants OPERATION_* ``` -------------------------------- ### System and Library Version Check for DOcplex Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/boxes This output block details the environment configuration, including the operating system, Python version, and the installed versions of the DOcplex and Pandas libraries, confirming the setup for optimization tasks. ```Log * system is: Windows 64bit * Python version 3.7.3, located at: c:\local\python373\python.exe * docplex is present, version is (2, 11, 0) * pandas is present, version is 0.25.1 ``` -------------------------------- ### Get Problem Type of DOCPLEX Model Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/docplex.mp.model Returns a string describing the type of problem. This method requires CPLEX to be installed and available in PYTHONPATH. An exception is raised if the CPLEX runtime cannot be found. Possible values include LP, MILP, QP, MIQP, QCP, and MIQCP. ```APIDOC Model.problem_type: str Description: Returns a string describing the type of problem. Requirements: CPLEX installed and available in PYTHONPATH. Raises: Exception if CPLEX runtime not found. Possible values: LP, MILP, QP, MIQP, QCP, MIQCP. New in version: 2.20 ``` -------------------------------- ### Define Nurse Association Equality Constraint Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/nurses This snippet defines a constraint that ensures two associated nurses are assigned to the same shift. It assumes iteration over nurse pairs and shifts, adding an equality constraint for their assignment variables. This is typically part of a larger constraint setup function within a Docplex model. ```Python nurse_id1 in nurses_by_id and nurse_id2 in nurses_by_id: nurse1 = nurses_by_id[nurse_id1] nurse2 = nurses_by_id[nurse_id2] for s in all_shifts: c += 1 ctname = 'medium_ct_nurse_assoc_{0!s}_{1!s}_{2:d}'.format(nurse_id1, nurse_id2, c) model.add_constraint(nurse_assigned[nurse1, s] == nurse_assigned[nurse2, s], ctname) ``` -------------------------------- ### Build CP Optimizer Model: Quick N-Queens Example Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/creating_model Demonstrates the quickest way to build a CP Optimizer model using `docplex.cp.model`, illustrating the creation of a CpoModel instance, integer variables, and adding `all_diff` constraints for the N-Queens problem. This approach directly imports all modeling functions. ```Python from docplex.cp.model import * NB_QUEEN = 8 mdl = CpoModel() x = integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, "X") mdl.add(all_diff(x)) mdl.add(all_diff([x[i] + i for i in range(NB_QUEEN)])) mdl.add(all_diff([x[i] - i for i in range(NB_QUEEN)])) ``` -------------------------------- ### Job-Shop Scheduling Problem Overview and Library Imports Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/visu.job_shop_basic.py This section provides a high-level description of the classical Job-Shop Scheduling problem, outlining its core components like jobs, machines, operations, and the objective of minimizing makespan. It also includes the necessary Python imports for the docplex.cp optimization library and the os module for file path handling. ```python # -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- """ In the classical Job-Shop Scheduling problem a finite set of jobs is processed on a finite set of machines. Each job is characterized by a fixed order of operations, each of which is to be processed on a specific machine for a specified duration. All machines are used by each job. Each machine can process at most one operation at a time and once an operation initiates processing on a given machine it must complete processing uninterrupted. The objective of the problem is to find a schedule that minimizes the makespan (end date) of the schedule. Please refer to documentation for appropriate setup of solving configuration. """ from docplex.cp.model import * import os ``` -------------------------------- ### Set Start Interval for CpoIntervalVar Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.expression.py Defines the start time of the interval variable. The start can be specified as a single integer or as a range (tuple of two integers) representing minimum and maximum allowed start times. ```APIDOC set_start(intv) intv: Start of the interval (single integer or interval expressed as a tuple of 2 integers). ``` -------------------------------- ### Initialize Docplex CpoSolver Instance Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/_modules/docplex/cp/solver/solver Initializes a `CpoSolver` instance, setting up internal attributes, processing the solving context from provided arguments, and applying platform-specific limitations like maximum threads. It also determines the appropriate solver agent and adds configured default listeners. ```python super(CpoSolver, self).__init__() self.agent = None self.process_infos = CpoProcessInfos() self.cpostr = None self.expr_map = None self.blackbox_map = None self.last_result = None self.status = STATUS_IDLE self.status_lock = threading.Lock() self.listeners = [] self.callbacks = [] self.operation = None self.abort_supported = False self.model_published = False self.model_sent = False self.callbacks_registered = False # Build effective context from args # OO's version # context = config._get_effective_context(**kwargs) # context.params = model.merge_with_parameters(context.params) ## trying to fix CP#303 ctx = config._get_effective_context() if model.parameters: ctx.params.set_other(model.parameters) ctx = config._get_effective_context(context=ctx, **kwargs) # If defined, limit the number of threads mxt = ctx.solver.max_threads if isinstance(mxt, int): # Maximize number of workers nbw = ctx.params.Workers if (nbw is None) or (nbw > mxt): ctx.params.Workers = mxt print("WARNING: Number of workers has been reduced to " + str(mxt) + " to comply with platform limitations.") # Save attributes self.model = model self.context = ctx # Determine appropriate solver agent self.agent = self._get_solver_agent() self.abort_supported = self.agent._is_abort_search_supported() # Add configured default listeners if any # Note: calling solver_created() is not required as it is done by add_listener(). lstnrs = ctx.solver.listeners if lstnrs is not None: if is_array(lstnrs): for lstnr in lstnrs: self._add_listener_from_class(lstnr) else: self._add_listener_from_class(lstnrs) ``` -------------------------------- ### Get Solution as Constraints (Python API) Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/cp/docplex.cp.solution.py Builds a list of constraints that force the model variables to correspond to the current solution. This method focuses only on decision variables (integer, floating point, interval, sequence variables, and state functions), excluding KPIs and objective values. The resulting constraints can be used, for example, with `CpoModel.add()` or `CpoModel.refine_conflict()`. ```APIDOC CpoModelSolution.get_as_constraints() Returns: List of constraints corresponding to this solution ``` -------------------------------- ### Setup Docplex Optimization Objective and KPIs Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/nurses This function defines the objective for the optimization model, which is to minimize a combination of total salary cost, total fairness (sum of over/under average worktime), and total number of assignments. It also adds several Key Performance Indicators (KPIs) to the model for detailed reporting of solution metrics. ```Python def setup_objective(model): model.add_kpi(model.total_salary_cost, "Total salary cost") model.add_kpi(model.total_number_of_assignments, "Total number of assignments") model.add_kpi(model.average_nurse_work_time, "average work time") total_over_average_worktime = model.sum(model.nurse_over_average_time_vars[n] for n in model.nurses) total_under_average_worktime = model.sum(model.nurse_under_average_time_vars[n] for n in model.nurses) model.add_kpi(total_over_average_worktime, "Total over-average worktime") model.add_kpi(total_under_average_worktime, "Total under-average worktime") total_fairness = total_over_average_worktime + total_under_average_worktime model.add_kpi(total_fairness, "Total fairness") model.minimize(model.total_salary_cost + total_fairness + model.total_number_of_assignments) ``` -------------------------------- ### Cutting Stock Problem Example Execution and Solution Output Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/cutstock This Python block demonstrates the typical entry point for running the cutting stock problem example. It calls the default solver, asserts the expected objective value for verification, and then saves the generated solution model to a JSON file named 'solution.json' using the DOcplex environment's output stream. ```Python if __name__ == '__main__': s = cutstock_solve_default() assert abs(s.objective_value - 46.25) <= 0.1 # Save the solution as "solution.json" program output. with get_environment().get_output_stream("solution.json") as fp: cutstock_save_as_json(s.model, fp) ``` -------------------------------- ### Install CPLEX Optimization Library via pip Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/getting_started This command installs the IBM ILOG CPLEX Optimization library using pip, the standard Python package installer. It's suitable for Python 2.7.9+ and 3.6+ environments. ```Shell pip install cplex ``` -------------------------------- ### Python Example: Implementing a Solver with PublishResultAsDf Source: https://ibmdecisionoptimization.github.io/docplex-doc/2.23.222/mp/docplex.mp.publish Illustrates how to create a custom solver class, `SomeSolver`, that inherits from `PublishResultAsDf`. This example demonstrates initializing properties for output table naming and customization, and a `solve` method that returns a pandas DataFrame. ```Python class SomeSolver(PublishResultAsDf): def __init__(self, output_customizer): # output something if context.solver.autopublish.somesolver_output is set self.output_table_property_name = 'somesolver_output' # output filename unless specified by somesolver_output: self.default_output_table_name = 'somesolver.csv' # customizer if users wants one self.output_table_customizer = output_customizer # uses pandas.DataFrame if possible, otherwise will use namedtuples self.output_table_using_df = True def solve(self): # do something here and return a result as a df result = pandas.DataFrame(columns=['A','B','C']) return result ```