### Setup Times Example in Python Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/visu.setup_times.py.html This Python script demonstrates the use of setup times in a scheduling problem using DOcplex.CP. It requires the DOcplex library to be installed. ```python from docplex.cp.model import CPModel from docplex.cp.utils import add_interval_var model = CPModel() # Define tasks tasks = [ {'name': 'Task A', 'duration': 5, 'setup': 2}, {'name': 'Task B', 'duration': 3, 'setup': 3}, {'name': 'Task C', 'duration': 4, 'setup': 1} ] # Create interval variables for each task interval_vars = {} for task in tasks: iv = add_interval_var(model, name=task['name'], size=task['duration']) interval_vars[task['name']] = iv # Add setup time constraints # For simplicity, assume tasks are executed sequentially on a single machine # This is a basic example; more complex sequencing and resource constraints can be added. # Sort tasks by their original order for a simple sequential execution sorted_tasks = sorted(tasks, key=lambda x: tasks.index(x)) for i in range(len(sorted_tasks) - 1): current_task_name = sorted_tasks[i]['name'] next_task_name = sorted_tasks[i+1]['name'] current_task_iv = interval_vars[current_task_name] next_task_iv = interval_vars[next_task_name] # Add setup time: the start of the next task must be at least the end of the current task + setup time setup_time = next(task['setup'] for task in tasks if task['name'] == next_task_name) model.add(next_task_iv.start >= current_task_iv.end + setup_time) # Solve the model solvers = model.get_solver_list() if 'docplex.cp' in solvers: msol = model.get_solver('docplex.cp') solution = msol.solve() if solution: print("Solution found:") for task in tasks: iv = interval_vars[task['name']] start = solution.get_var_value(iv.start) end = solution.get_var_value(iv.end) print(f" {task['name']}: Start={start}, End={end}") else: print("No solution found.") else: print("CPLEX CP solver not available.") ``` -------------------------------- ### Set Starting Point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.model.py.html Configures a starting point for the CP Optimizer search, which can be a partial solution to guide the solver. ```APIDOC ## POST /api/set_starting_point ### Description Sets a model starting point, which is a (possibly partial) solution that CP Optimizer can use to begin its search. Only integer and interval variables are considered. The starting point is represented by a `CpoModelSolution` object. ### Method POST ### Endpoint /api/set_starting_point ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stpoint** (CpoModelSolution) - Required - The starting point object. ### Request Example ```json { "stpoint": { "example": "CpoModelSolution object" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### GET /api/model/mip_starts Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/model.html Retrieves a list of all MIP start solutions associated with the model. ```APIDOC ## GET /api/model/mip_starts ### Description This property returns the list of MIP start solutions (a list of instances of :class:`docplex.mp.solution.SolveSolution`) attached to the model if MIP starts have been defined, possibly an empty list. ### Method GET ### Endpoint /api/model/mip_starts ### Response #### Success Response (200) - **mip_starts** (list[SolveSolution]) - A list of MIP start solution objects. ### Response Example ```json { "mip_starts": [ { ... }, { ... } ] } ``` ``` -------------------------------- ### Configuration Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solver/solver.html Example of how to configure the solver agent and its details. ```APIDOC ## Configuration Example ### Description This example shows the minimum configuration elements required for the default solver agent ('local') to solve models using the local process 'CP Optimizer Interactive'. ### Configuration Snippet ``` context.solver.agent = 'local' context.solver.local.execfile = ``` ``` -------------------------------- ### Get Starting Point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.model.py.html Retrieves the starting point configuration for the model. ```APIDOC ## GET /api/model/starting_point ### Description Gets the model starting point. Returns None if no starting point is defined. ### Method GET ### Endpoint /api/model/starting_point ### Returns - **object | None**: The model starting point, or None if none. ``` -------------------------------- ### Solver Configuration Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.solver.solver.py.html Example of how to configure the solver agent and its properties. ```APIDOC ## Configuration Example ### Description Demonstrates the configuration settings for specifying the solver agent and its executable file. ### Configuration Properties - **context.solver.agent**: Specifies the name of the agent to be used (e.g., 'local'). - **context.solver.local.execfile**: The name or path of the process for the 'local' solver agent (e.g., 'CP Optimizer Interactive'). ### Example ``` context.solver.agent = 'local' context.solver.local.execfile = ``` ``` -------------------------------- ### Get MIP Starts from Model Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/model.html Returns a list of MIP start solutions attached to the model. This property is deprecated; use Model.iter_mip_starts instead. ```python return [s for (s, _) in self.iter_mip_starts()] ``` -------------------------------- ### Install DOcplex Library Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/README.md Use pip to install the DOcplex library. This command installs the necessary package for using the optimization modeling capabilities. ```bash pip install docplex ``` -------------------------------- ### SolutionRecorder Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/progress.html An example of a solution listener that records intermediate solutions found during the MIP solve. ```APIDOC ## SolutionRecorder ### Description An example of a solution listener that records intermediate solutions. This class likely derives from `SolutionListener` and implements the `notify_solution` method to store the solutions. ### Usage Instantiate `SolutionRecorder` and add it to your DOcplex model using `model.add_progress_listener(recorder_instance)`. ``` -------------------------------- ### Set PYTHONPATH and run a DOcplex example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/getting_started.html Set the PYTHONPATH environment variable to the current directory and run a Python example script. This is useful for testing installed libraries. ```bash > set PYTHONPATH=. > python examples/cp/basic/color.py ``` -------------------------------- ### Set Model Starting Point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.model.py.html Use this method to provide a partial or complete solution to guide the solver's search. Only integer and interval variables are considered. Ensure the starting point is represented by a CpoModelSolution object. ```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) ``` -------------------------------- ### Add MIP Start Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.model.html Adds a solution to be used as a starting point for a Mixed Integer Programming (MIP) problem. This is also known as a 'warm start'. ```APIDOC ## POST /model/add_mip_start ### Description Adds a (possibly partial) solution to use as a starting point for a MIP. This is valid only for models with binary or integer decision variables. The given solution must contain the value for at least one binary or integer variable. This feature is also known as ‘warm start’. ### Method POST ### Endpoint /model/add_mip_start ### Parameters #### Request Body - **mip_start_sol** (object) - Required - The solution object to use as a starting point. It should conform to the SolveSolution structure. - **write_level** (string) - Optional - An enumerated value from class `WriteLevel`, controlling which variables are copied to the MIP start solution. By default, only discrete variables are copied. Example values: `NonZeroDiscreteVars`, `AllVars`. - **complete_vars** (boolean) - Optional - If False (default), only variables mentioned in the solution are copied. If True, all variables in the model are copied to the MIP start. - **effort_level** (string) - Optional - An enumerated value of class `EffortLevel`, or None. ### Request Example ```json { "mip_start_sol": { "variables": { "x": 10, "y": 5 } }, "write_level": "NonZeroDiscreteVars", "complete_vars": false } ``` ### Response #### Success Response (200) - **solve_solution** (object) - An instance of `SolveSolution`, different from the one passed in input if the conversion succeeds, else None (typically for LP models). #### Response Example ```json { "solve_solution": { "variables": { "x": 10, "y": 5 }, "objective": 50 } } ``` ``` -------------------------------- ### Install DOcplex Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/warehouse.html Installs the DOcplex library if it's not already present. This is a prerequisite for using DOcplex functionalities. ```python try: import docplex.mp except: !pip install docplex ``` -------------------------------- ### Start Solve Callback Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solver/solver_listener.html Callback executed when the solve process starts. It creates and initializes the solver progress panel. ```python # Create progress panel self.progress_panel = _CpoSolverProgressPanel(solver) ``` -------------------------------- ### Install CPLEX with pip Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/getting_started.html Use pip to install the CPLEX library. This is the standard tool for Python package installation. ```bash pip install cplex ``` -------------------------------- ### CpoIntervalVar - Get Start Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/expression.html Method for getting the start of an interval variable. ```APIDOC ## GET /api/interval/get_start ### Description Gets the start of the interval. ### Method GET ### Endpoint /api/interval/get_start ### Response #### Success Response (200) - **start** (tuple) - Start of the interval (interval expressed as a tuple of 2 integers). #### Response Example ```json { "start": [10, 20] } ``` ``` -------------------------------- ### SolveSolution.as_mip_start() Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/solution.html Converts the current solution into a MIP start object. ```APIDOC ## SolveSolution.as_mip_start() ### Description Converts the current solution into a MIP start object. This can be used to provide an initial feasible solution for a mixed-integer programming problem. ### Method ```python def as_mip_start(self, write_level=WriteLevel.DiscreteVars, complete_vars=False, eps_zero=1e-6) ``` ### Parameters - **write_level** (WriteLevel, optional) - Specifies the level of detail for variables to include. Defaults to `WriteLevel.DiscreteVars`. - **complete_vars** (boolean, optional) - If True, includes all variables; otherwise, only includes variables with non-zero values. Defaults to False. - **eps_zero** (float, optional) - Tolerance for considering a value as zero. Defaults to 1e-6. ### Returns - SolveSolution: A new SolveSolution object representing the MIP start. ### Request Example ```json { "write_level": "all", "complete_vars": true, "eps_zero": 0.0001 } ``` ### Response Example ```json { "message": "MIP start object created successfully." } ``` ``` -------------------------------- ### Example usage of SomeSolver Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.publish.html This demonstrates how to instantiate a solver that publishes results as a DataFrame and then call its `solve` and `write_output_table` methods. ```python solver = SomeSolver() results = solver.solve() solver.write_output_table(results) ``` -------------------------------- ### Get Interval Start Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/expression.html Retrieves the start of the interval as a tuple of two integers. ```python def get_start(self): """ Gets the start of the interval. Returns: Start of the interval (interval expressed as a tuple of 2 integers). """ return self.start ``` -------------------------------- ### Run diet.py example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/samples.html This command runs the diet.py example script. It submits the problem to the optimization engine and displays the results, including the solved model and key performance indicators. ```bash 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 ``` -------------------------------- ### Get Model Starting Point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/model.html Retrieves the model's starting point, if one has been set. Returns None if no starting point is defined. ```python def get_starting_point(self): """ Get the model starting point Returns: Model starting point, None if none """ return self.starting_point ``` -------------------------------- ### Chrono Get Start Time Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/utils.html Retrieves the timestamp when the chronometer was initially started or last restarted. ```python def get_start(self): """ Get the chrono start time. Returns: Time when chronometer has been started """ return self.startTime ``` -------------------------------- ### Initialize SolverContext Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/context.html Initializes SolverContext with default settings for logging, max threads, auto-publish, and KPI reporting. ```python def __init__(self, **kwargs): super(SolverContext, self).__init__(**kwargs) self.log_output = False self.max_threads = get_environment().get_available_core_count() self.auto_publish = create_default_auto_publish_context() self.kpi_reporting = BaseContext() from docplex.mp.progress import ProgressClock self.kpi_reporting.filter_level = ProgressClock.Gap ``` -------------------------------- ### CpoModel.set_starting_point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/model.html Sets a starting point for the CP Optimizer search. The starting point can be a partial solution to guide the solver. ```APIDOC ## CpoModel.set_starting_point ### 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. ### Method `set_starting_point(self, stpoint)` ### Parameters * **stpoint** (:class:`~docplex.cp.solution.CpoModelSolution` or None) - Starting point, object of class :class:`~docplex.cp.solution.CpoModelSolution`. ``` -------------------------------- ### Main Execution Block Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/load_balancing.html Sets up and solves the load balancing model, then saves the solution to a JSON file. Requires importing get_environment from docplex.util.environment. ```python if __name__ == '__main__': lbm = make_default_load_balancing_model() # Run the model. lbs = lbm.solve(log_output=True) lb_report(lbm) # save json, used in worker tests from docplex.util.environment import get_environment with get_environment().get_output_stream("solution.json") as fp: lb_save_solution_as_json(lbm, fp) lbm.end() ``` -------------------------------- ### Run Basic Color Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/samples.html Executes a basic constraint programming example to solve the map coloring problem. The output shows the solution status and the assigned colors for each country. ```text > python examples/cp/basic/color.py Solving model.... Solution status: Feasible Belgium: Yellow Denmark: Yellow France: Red Germany: Green Luxembourg: Blue Netherlands: Red ``` -------------------------------- ### CpoIntervalVarSolution: Get Start Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solution.html Retrieves the start value of the interval. Returns the value or domain if not fully instantiated. Returns None if the interval is absent. ```python def get_start(self): """ Gets the interval start. To get the bounds of the returned domain, in particular if not fixed, use methods :meth:`docplex.cp.expression.get_domain_min` and :meth:`docplex.cp.expression.get_domain_max` Returns: Interval start value, or domain (tuple (min, max)) if not fully instantiated. None if interval is absent. """ return self.start ``` -------------------------------- ### Get Start of Previous Interval in Sequence Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/modeler.html Returns an integer expression for the start of the previous interval in a sequence. Handles cases where the interval is the first or absent. ```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) ``` -------------------------------- ### Initialize Production Problem Data Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/production.html Sets up the initial data for the production problem, including product details (demand, inside/outside costs), resource capacities, and consumption rates. ```python PRODUCTS = [("kluski", 100, 0.6, 0.8), ("capellini", 200, 0.8, 0.9), ("fettucine", 300, 0.3, 0.4)] # resources are a list of simple tuples (name, capacity) RESOURCES = [("flour", 20), ("eggs", 40)] CONSUMPTIONS = {("kluski", "flour"): 0.5, ("kluski", "eggs"): 0.2, ("capellini", "flour"): 0.4, ("capellini", "eggs"): 0.4, ("fettucine", "flour"): 0.3, ("fettucine", "eggs"): 0.6} ``` -------------------------------- ### Create a CP Model Instance Source: https://context7.com/ibmdecisionoptimization/docplex-doc/llms.txt Demonstrates the creation of a constraint programming model using the CpoModel class. Shows how to use the model as a factory for creating variables and adding constraints. ```python from docplex.cp.model import CpoModel # Create a constraint programming model mdl = CpoModel(name='my_cp_model') # Using model as factory (recommended) x = mdl.integer_var(0, 10, name='x') mdl.add(x >= 5) ``` -------------------------------- ### Get Start of Next Interval in Sequence Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/modeler.html Returns an integer expression for the start of the next interval in a sequence. Handles cases where the interval is the last or absent. ```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) ``` -------------------------------- ### Get Start of Interval Variable Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/modeler.html Returns an integer expression for the start of an interval variable. If the interval is absent, returns the specified absentValue (defaults to 0). ```python def start_of(interval, absentValue=None): """ Returns the start of specified interval variable. This function returns an integer expression that is equal to the 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 """ 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))) ``` -------------------------------- ### Initialize SolutionRecorder Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/progress.html Initializes a SolutionRecorder, which stores all intermediate solutions found during the optimization process. ```python def __init__(self, clock=ProgressClock.Gap, absdiff=None, reldiff=None): super(SolutionRecorder, self).__init__(clock, absdiff, reldiff) self._solutions = [] ``` -------------------------------- ### Basic Model Creation in DOcplex.MP Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/sport_scheduling.html Demonstrates the fundamental steps to create a mathematical programming model using DOcplex.MP. This includes importing the library and initializing a model object. ```python from docplex.mp.model import Model mdl = Model(name='my_first_model') ``` -------------------------------- ### GET /api/model/iter_mip_starts Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/model.html Returns an iterator over the MIP starts associated with the model. ```APIDOC ## GET /api/model/iter_mip_starts ### Description This property returns an iterator on the MIP starts associated with the model. It returns tuples of size 2: (MIP start solution, effort level). ### Method GET ### Endpoint /api/model/iter_mip_starts ### Response #### Success Response (200) - **mip_starts_iterator** (iterator) - An iterator yielding tuples of (SolveSolution, EffortLevel). ### Response Example ```json [ [ { ... }, "HIGH" ], [ { ... }, "LOW" ] ] ``` ``` -------------------------------- ### GET /api/model/number_of_mip_starts Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/model.html Returns the total number of MIP starts associated with the model. ```APIDOC ## GET /api/model/number_of_mip_starts ### Description This property returns the number of MIP start associated with the model. ### Method GET ### Endpoint /api/model/number_of_mip_starts ### Response #### Success Response (200) - **number_of_mip_starts** (integer) - The count of MIP starts. ### Response Example ```json { "number_of_mip_starts": 5 } ``` ``` -------------------------------- ### Initialize Problem Data Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/lagrangian_relaxation.html Sets up the input data for the Generalized Assignment Problem, including capacities, costs, and profits. ```python B = [15, 15, 15] C = [ [ 6, 10, 1], [12, 12, 5], [15, 4, 3], [10, 3, 9], [8, 9, 5] ] A = [ [ 5, 7, 2], [14, 8, 7], [10, 6, 12], [ 8, 4, 15], [ 6, 12, 5] ] ``` -------------------------------- ### Handle Initial State Constraints Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/ucp_pandas.html Implements constraints to account for the initial state of units, determining 'turn_on' and 'turn_off' variables for the first time period based on initial production levels. ```python for u in units: if df_up.initial[u] > 0: ucpm.add_constraint(turn_on[u, 1] == 0) ucpm.add_constraint(turn_off[u, 1] + in_use[u, 1] == 1) else: ucpm.add_constraint(turn_on[u, 1] == in_use[u, 1]) ucpm.add_constraint(turn_off[u, 1] == 0) ``` -------------------------------- ### Get Start of Interval Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/modeler.html Returns an integer expression equal to the start of the specified interval variable if it is present. Handles absent interval variables by returning a specified absent value. ```python def 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. ``` -------------------------------- ### ParameterGroup.qualified_name() Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/params/parameters.html Demonstrates how to get the qualified name of a parameter group, showing its position in the hierarchy. ```APIDOC ## Method: ParameterGroup.qualified_name ### Description Computes a string with all the parents of the parameters, representing the full path to the group. ### Endpoint N/A (This is a class method, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'group' is an instance of ParameterGroup # Example: group.qualified_name() ``` ### Response #### Success Response (string) Returns the qualified name of the parameter group. #### Response Example ```json { "example": "group.subgroup.parameter_name" } ``` ``` -------------------------------- ### Main Execution Block for Cutstock Example Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/cutstock.html This block demonstrates how to run the cutting stock solver with default parameters and save the solution to a JSON file. It includes an assertion to verify the objective value. ```python if __name__ == '__main__': m,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(m, fp) m.end() ``` -------------------------------- ### Chrono Get Elapsed Time Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/utils.html Calculates and returns the time elapsed since the chronometer was started, in seconds. ```python def get_elapsed(self): """ Get the chrono elapsed time. Returns: Time spent from chronometer start time (float), in seconds """ return time.time() - self.startTime ``` -------------------------------- ### Summing Input Data with Environment Utilities Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/util/environment.html This example demonstrates how to read data from an input file ('data.txt'), process it (summing integers), and write the result to an output file ('solution.json') using DOcplex environment utilities. Ensure 'data.txt' exists with integer data. ```python import json import docplex.util.environment as environment sum = 0 # open program input named "data.txt" and sum the contents with environment.get_input_stream("data.txt") as input: for i in input.read().split(): sum += int(i) # write the result as a simple json in program output "solution.json" with environment.get_output_stream("solution.json") as output: output.write(json.dumps({'result': sum})) ``` -------------------------------- ### Initialize DOcplex Environment Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/boxes.html Initialize the DOcplex environment and print system information. This step is useful for debugging and understanding the environment setup. ```python from docplex.mp.environment import Environment env = Environment() env.print_information() ``` -------------------------------- ### Complete N-Queens Example (CP) Source: https://context7.com/ibmdecisionoptimization/docplex-doc/llms.txt A full implementation of the N-Queens problem using DOcplex CP, demonstrating the use of all_diff constraints for row, column, and diagonal conflicts. ```python from docplex.cp.model import CpoModel # The N-Queens problem: place N queens on an NxN board # such that no two queens threaten each other NB_QUEEN = 8 mdl = CpoModel(name='n_queens') # Variables: column position of queen in each row x = mdl.integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, name='Q') # Constraints: # 1. One queen per column (all columns different) mdl.add(mdl.all_diff(x)) # 2. No two queens on same diagonal (direction /) mdl.add(mdl.all_diff([x[i] + i for i in range(NB_QUEEN)])) # 3. No two queens on same diagonal (direction \) mdl.add(mdl.all_diff([x[i] - i for i in range(NB_QUEEN)])) # Solve print(f"Solving {NB_QUEEN}-Queens...") msol = mdl.solve(TimeLimit=10) if msol: print("Solution found:") for row in range(NB_QUEEN): col = msol[x[row]] line = ['.' if c != col else 'Q' for c in range(NB_QUEEN)] print(' '.join(line)) else: print(f"No solution: {msol.get_solve_status()}") ``` -------------------------------- ### Get Variable Values as DataFrame Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.solution.html Returns values of a dictionary of variables as a pandas DataFrame. If pandas is not installed, it returns a dictionary of columns. ```APIDOC ## GET /solution/value_df ### Description Returns values of a dictionary of variables as a pandas DataFrame. ### Method GET ### Endpoint /solution/value_df ### Parameters #### Query Parameters - **var_dict** (dict) - Required - The dictionary of variables, as created by Model.xx_var_dict. - **value_column_name** (string) - Optional - A string to name the value column. Defaults to 'value'. - **key_column_names** (list[string]) - Optional - A list of strings to name the keys of the dictionary. If not present, keys are named 'k1', 'k2', etc. ### Response #### Success Response (200) - **dataframe** (pandas.DataFrame | dict) - A pandas DataFrame if pandas is present, otherwise a dictionary of columns. #### Response Example ```json { "dataframe": { "col1": [1, 2, 3], "col2": [4.5, 5.5, 6.5] } } ``` ``` -------------------------------- ### Enable start/next loop with solve() in docplex.cp Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/CHANGELOG.html Using the `_context.solver.solve_with_start_next` parameter enables the `solve()` method to execute a start/next loop instead of a standard solve. This improves progress accuracy for optimization problems when using SolveListeners. ```python docplex.cp.model.CpoModel.solve() ``` -------------------------------- ### Get Right Expression of a Linear Constraint Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.constr.html Retrieves the right-hand side expression of a linear constraint. For example, in 'X+Y <= Z+1', the right expression is 'Z+1'. ```python constraint.right_expr ``` -------------------------------- ### Convert Solution to MIP Start Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/solution.html Converts the current solution into a MIP start object. This is useful for warm-starting subsequent solves. It can filter discrete variables and zero values based on the specified write level. ```python def as_mip_start(self, write_level=WriteLevel.DiscreteVars, complete_vars=False, eps_zero=1e-6): write_level_ = WriteLevel.parse(write_level) filter_discrete = write_level_.filter_nondiscrete() filter_zeros = write_level_.filter_zeros() mdl = self.model mipstart_dict = {} def generate_completed_var_values(): for dv_ in mdl.generate_user_variables(): yield dv_, self._get_var_value(dv_) if not complete_vars: vv_iter = self.iter_var_values() else: vv_iter = generate_completed_var_values() for dv, dvv in vv_iter: if filter_discrete and not dv.is_discrete(): continue if filter_zeros and abs(dvv) <= eps_zero: continue mipstart_dict[dv] = dvv mipstart = SolveSolution(self.model, name=self.name, var_value_map=None, obj=self.objective_value, solved_by=self.solved_by, keep_zeros=True) mipstart._var_value_map = mipstart_dict return mipstart ``` -------------------------------- ### Get Parameter Default Value Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/params/parameters.html Retrieves the default value of a parameter. Examples include 'parameters.workdir' with default '.', 'parameters.optimalitytarget' with default 0, and 'parameters.mip.tolerances.mipgap' with default 0.0001. ```python return self._default_value ``` -------------------------------- ### Get Length of Interval Variable Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/modeler.html Returns an integer expression for the length (end - start) of an interval variable. If the interval is absent, returns the specified absentValue (defaults to 0). ```python def 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 """ 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))) ``` -------------------------------- ### Context Creation and Initialization Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/context.html Demonstrates how to create and initialize a DOcplex context, including handling solver contexts and updating with keyword arguments. ```APIDOC ## Context Initialization ### Description Initializes a DOcplex context, optionally accepting a `solver_context` or creating a default one. It also handles updates from keyword arguments. ### Method `__init__` ### Parameters - **solver_context** (SolverContext) - Optional - The solver context to use. - **kwargs** (dict) - Additional keyword arguments to update the context. ### Request Example ```python from docplex.mp.context import Context, SolverContext # Using a default solver context context1 = Context() # Providing a specific solver context solver_ctx = SolverContext() context2 = Context(solver_context=solver_ctx) # Updating with keyword arguments context3 = Context(url='http://example.com', api_key='12345') ``` ### Response - **Context** - The initialized context object. ``` -------------------------------- ### Get Function Steps from CpoStateFunctionSolution Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solution.html Retrieves the list of steps defining the state function solution. Each step is a tuple containing the start time, end time, and value. ```python def get_function_steps(self): """ Gets the list of function steps. Returns: List of function steps. Each step is a tuple (start, end, value). """ return self.steps ``` -------------------------------- ### Get Linear Part of a Quadratic Expression Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/quad.html The 'linear_part' property returns the linear component of a quadratic expression. For example, in x^2 + 2x + 1, the linear part is (2x + 1). ```python @property def linear_part(self): """ This property returns the linear part of a quadratic expression. For example, the linear part of x^2 +2x+1 is (2x+1) :return: an instance of :class:`docplex.mp.LinearExpr` """ return self.get_linear_part() ``` -------------------------------- ### Get Variable Values as DataFrame Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/solution.html Retrieves variable values from a dictionary and returns them as a pandas DataFrame. If pandas is not installed, it returns a dictionary of columns. Handles both single and tuple keys for variables. ```python def get_value_df(self, var_dict, value_column_name=None, key_column_names=None): """ Returns values of a dicitonary of variables, as a pandas dataframe. If pandas is not present, returns a dicitonary of columns. :param var_dict: the dicitonary of variables, as created by Model.xx_var_dict :param value_column_name: an optional string to name the value column. Default is 'value' :param key_column_names: an optional list of strings to name th ekeys of the dicitonary. If not present, keys are named 'k1', 'k2', ... :return: a pandas DataFrame, if pandas is present. """ keys = list(var_dict.keys()) values = self.get_values((dv for dv in var_dict.values())) if isinstance(keys[0], tuple): keys = list(zip(*keys)) knames = None if key_column_names: if len(key_column_names) == len(keys): knames = key_column_names if not knames: knames = ['key_%d' % k for k in range(1, len(keys) + 1)] kd = {kn: ks for kn, ks in zip(knames, keys)} else: kn = key_column_names or 'key' kd = {kn: keys} value_col_name = value_column_name or 'value' kd[value_col_name] = values try: import pandas as pd return pd.DataFrame(kd) except ImportError: self.model.warning("pandas module not found, returning a dict instead of DataFrame") return kd ``` -------------------------------- ### CpoSolverListener start_solve Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solver/solver_listener.html Notifies that the solve is started. The default implementation does nothing. ```python def start_solve(self, solver): """ Notify that the solve is started. Args: solver: Originator CPO solver (object of class :class:~docplex.cp.solver.solver.CpoSolver~) """ pass ``` -------------------------------- ### Get Python Module Version Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/utils.html Retrieves the version of a specified Python module. Returns the version string, None if the module is not installed, or 'Unknown' if the version is not defined. Requires the 'importlib' module. ```python import importlib def get_module_version(mname): """ Get the version of a Python module Args: mname: Module name Returns: Version of the module, None if not installed, "Unknown" if not set in the module """ try: m = importlib.import_module(mname) try: ``` -------------------------------- ### Get Interval Value Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solution.html Retrieves the interval variable's value as a tuple (start, end, size). For partially instantiated variables, it includes length. Returns an empty tuple if the 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 () ``` -------------------------------- ### Model Initialization in Solver Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solver/solver.html Handles the initialization of the model within the solver, including registering callbacks and blackbox functions if not already done. ```APIDOC ## Initialize Model in Solver ### Description Sends the model to the solver if it has not been sent already. This method also handles the registration of callbacks and blackbox functions, checking solver versions and ensuring implementations exist. ### Method Internal method (not directly callable by users) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ### Error Handling - Raises `CpoSolverException` if the solver version does not support callbacks or blackbox functions. - Raises `CpoSolverException` if a registered blackbox function lacks an implementation. ``` -------------------------------- ### Instantiate CpoParameters with arguments Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.parameters.py.html Instantiate CpoParameters by passing individual parameters as keyword arguments. This is a convenient way to set parameters directly during object creation. ```python myparams = CpoParameters(TimeLimit=20, LogPeriod=5000) ``` -------------------------------- ### Get Problem Type String Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/_modules/docplex/mp/model.html Returns a string describing the type of the problem (e.g., LP, MILP, QP). Requires CPLEX to be installed and available in PYTHONPATH. Raises an exception if the CPLEX runtime cannot be found. ```python @property def problem_type(self): """ Returns a string describing the type of problem. This method requyires that CPLEX is installed and available in PYTHONPATH. If the CPLEX runtime cannot be found, an exception is raised. Possible values: LP, MILP, QP, MIQP, QCP, MIQCP, *New in version 2.20* """ cpx = self._get_cplex(do_raise=True, msgfn=lambda: "Model.problem_type requites CPLEX") return self._problem_type_from_cplex(cpx, fallback=None) ``` -------------------------------- ### Get Problem Type Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.model.html Returns a string describing the type of problem (e.g., LP, MILP, QP). This method requires CPLEX to be installed and available in PYTHONPATH. It will raise an exception if the CPLEX runtime cannot be found. ```python problem_type ``` -------------------------------- ### Add MIP Start Solution Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/mp/docplex.mp.model.html Adds a solution to be used as a starting point for a Mixed Integer Programming (MIP) problem. This is valid only for models with binary or integer decision variables. The solution must contain values for at least one such variable. The 'write_level' parameter controls which variables are copied, and 'complete_vars' determines if all model variables should be included. ```python mdl.add_mip_start(sol, write_level=WriteLevel.NonZeroDiscreteVars) ``` ```python mdl.add_mip_start(sol, write_level=WriteLevel.AllVars, complete_vars=True) ``` -------------------------------- ### Get Interval Length Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/solution.html Calculates the length of an interval variable as the difference between its end and start times. Handles both fully instantiated and partially instantiated variables, returning bounds if necessary. Returns None if the interval is absent. ```python def get_length(self): """ Gets the length of the interval. Length of the interval is the difference between end and start. To get the bounds of the returned domain, in particular if not fixed, use methods :meth:`docplex.cp.expression.get_domain_min` and :meth:`docplex.cp.expression.get_domain_max` Returns: Interval length value, or domain (tuple (min, max)) if not fully instantiated. None if interval is absent. """ if self.length is None: dstrt = self.start dend = self.end if dstrt is None or dend is None: return None if is_int(dstrt) and is_int(dend): return dend - dstrt lw = builtin_max(_get_interval_domain_min(dend) - _get_interval_domain_max(dstrt), 0) up = builtin_max(_get_interval_domain_max(dend) - _get_interval_domain_min(dstrt), 0) return lw if lw == up else (lw, up) return self.length ``` -------------------------------- ### Start Search Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/docplex.cp.solver.solver.py.html Initiates a new search process. Solutions can be retrieved sequentially using the `search_next()` method. ```APIDOC ## Start Search ### Description Starts a new search process. Subsequent solutions can be retrieved using the `search_next()` method. ### Method `start_search()` ### Endpoint (Not applicable, this is a method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python solver.start_search() ``` ### Response (No specific response defined, likely void or status indicator) ### Errors - **CpoNotSupportedException**: Method not available in this solver agent. ``` -------------------------------- ### Create Empty Solution for Starting Point Source: https://github.com/ibmdecisionoptimization/docplex-doc/blob/master/docs/cp/_modules/docplex/cp/model.html Creates a new, empty CpoModelSolution object that can be populated to serve as a starting point for the CP Optimizer search. ```python def create_empty_solution(self): """ Create an empty model solution that can be filled to be used as a starting point. *New in version 2.9* Returns: New empty model solution, object of class :class:~docplex.cp.solution.CpoModelSolution """ return CpoModelSolution() ```