### PathsMetadata Starts Method Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Returns a collection of all start nodes. ```python def Starts(self): return _pywrapcp.PathsMetadata_Starts(self) ``` -------------------------------- ### PathsMetadata Start Method Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the start node for a given path. ```python def Start(self, path): return _pywrapcp.PathsMetadata_Start(self, path) ``` -------------------------------- ### Python Protobuf Imports and Setup Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/callback_pb2.html This snippet shows the standard imports and setup for generated protocol buffer code in Python, including runtime version validation. ```python # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: ortools/math_opt/callback.proto # Protobuf Python Version: 6.33.1 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import runtime_version as _runtime_version from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 6, 33, 1, '', 'ortools/math_opt/callback.proto' ) # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from ortools.math_opt import sparse_containers_pb2 as ortools_dot_math__opt_dot_sparse__containers__pb2 ``` -------------------------------- ### Xpress Parameters Example Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/solvers/xpress_pb2.html Example of setting Xpress parameters, specifically the 'BarIterLimit'. Parameters are applied in a specific order: ortools parameters, then param_values in insertion order. ```cpp XpressParameters xpress; xpress.param_values["BarIterLimit"] = "10"; ``` -------------------------------- ### IntervalVar Start Methods Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Methods to query, set, and watch the start position of an interval variable. ```APIDOC ## IntervalVar Start Methods ### Description Methods to query, set, and watch the start position of an interval variable. ### Methods - **StartMin(self)**: Returns the minimum possible start time. - **StartMax(self)**: Returns the maximum possible start time. - **SetStartMin(self, m)**: Sets the minimum possible start time. - **SetStartMax(self, m)**: Sets the maximum possible start time. - **SetStartRange(self, mi, ma)**: Sets the minimum and maximum possible start times. - **OldStartMin(self)**: Returns the old minimum start time (for internal use). - **OldStartMax(self)**: Returns the old maximum start time (for internal use). - **WhenStartRange(self, *args)**: Registers a callback for when the start range changes. - **WhenStartBound(self, *args)**: Registers a callback for when the start bound changes. ``` -------------------------------- ### Interval Starts At Start Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Requires an interval to begin at the same time another interval starts. This is used for synchronizing the initiation of related tasks. ```python def StartsAtStart(self, other): return _pywrapcp.IntervalVar_StartsAtStart(self, other) ``` -------------------------------- ### Get Interval Start Value Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the current start time value of an interval variable. ```python def StartValue(self): return _pywrapcp.IntervalVarElement_StartValue(self) ``` -------------------------------- ### Solver Initialization and Basic Operations Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Demonstrates how to initialize the Solver, access its parameters, and add constraints to the model. It also covers the default parameter creation and the basic solving process. ```APIDOC ## Solver Class ### Description The Solver class is the main entry point for the constraint programming solver. It allows users to define, add constraints to, and solve constraint satisfaction problems. ### Methods #### `__init__(self, *args)` * **Description**: Initializes the Solver object. This is the primary constructor for creating a solver instance. #### `Parameters(self)` * **Description**: Returns the stored parameters of the solver. * **Return**: The solver's parameters. #### `DefaultSolverParameters()` * **Description**: Creates a `ConstraintSolverParameters` protocol buffer with all default values. * **Return**: A `ConstraintSolverParameters` object with default settings. #### `AddConstraint(self, c)` * **Description**: Adds a constraint `c` to the model. Constraints added outside of search are permanent. Constraints added during search are temporary and removed by backtracking. * **Parameters**: * `c` (Constraint): The constraint to add to the model. * **Return**: The added constraint. #### `Solve(self, *args)` * **Description**: Solves the problem using the given DecisionBuilder. Returns true if a solution was found and accepted. * **Return**: `True` if a solution is found, `False` otherwise. ``` -------------------------------- ### Get Interval Start Maximum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the maximum possible start time for an interval variable. ```python def StartMax(self): return _pywrapcp.IntervalVarElement_StartMax(self) ``` -------------------------------- ### Get Interval Start Minimum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the minimum possible start time for an interval variable. ```python def StartMin(self): return _pywrapcp.IntervalVarElement_StartMin(self) ``` -------------------------------- ### Create and Use SolutionHint Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html Demonstrates how to create a SolutionHint object with variable and dual values, and convert it to its protocol buffer representation. This is useful for providing starting points to solvers. ```python hint = SolutionHint( variable_values={'x': 1.0, 'y': 2.0}, dual_values={'c1': 3.0} ) proto = hint.to_proto() ``` -------------------------------- ### Get IntervalVar Start Maximum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the maximum possible start time for an interval variable. Used in conjunction with other methods to manage the start position. ```python def StartMax(self): return _pywrapcp.IntervalVar_StartMax(self) ``` -------------------------------- ### Get Assigned Start Time of an Interval Variable Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the assigned start time for an interval variable. ```python def StartValue(self, var): return _pywrapcp.Assignment_StartValue(self, var) ``` -------------------------------- ### Get Maximum Start Time of an Interval Variable Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the maximum start time for an interval variable. ```python def StartMax(self, var): return _pywrapcp.Assignment_StartMax(self, var) ``` -------------------------------- ### Simplified MathOpt Imports Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/mathopt.html Demonstrates how to simplify imports for MathOpt by using the main mathopt module instead of importing individual sub-modules like model and solve. ```python # Copyright 2010-2025 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module exporting all classes and functions needed for MathOpt. This module defines aliases to all classes and functions needed for regular use of MathOpt. It removes the need for users to have multiple imports for specific sub-modules. For example instead of: from ortools.math_opt.python import model from ortools.math_opt.python import solve m = model.Model() solve.solve(m) we can simply do: from ortools.math_opt.python import mathopt m = mathopt.Model() mathopt.solve(m) """ # pylint: disable=unused-import # pylint: disable=g-importing-member from ortools.math_opt.python.callback import BarrierStats from ortools.math_opt.python.callback import CallbackData from ortools.math_opt.python.callback import CallbackRegistration from ortools.math_opt.python.callback import CallbackResult from ortools.math_opt.python.callback import Event from ortools.math_opt.python.callback import GeneratedConstraint from ortools.math_opt.python.callback import MipStats from ortools.math_opt.python.callback import parse_callback_data from ortools.math_opt.python.callback import PresolveStats from ortools.math_opt.python.callback import SimplexStats from ortools.math_opt.python.compute_infeasible_subsystem_result import ( ComputeInfeasibleSubsystemResult, ) from ortools.math_opt.python.compute_infeasible_subsystem_result import ModelSubset from ortools.math_opt.python.compute_infeasible_subsystem_result import ( ModelSubsetBounds, ) from ortools.math_opt.python.compute_infeasible_subsystem_result import ( parse_compute_infeasible_subsystem_result, ) from ortools.math_opt.python.compute_infeasible_subsystem_result import ( parse_model_subset, ) from ortools.math_opt.python.compute_infeasible_subsystem_result import ( parse_model_subset_bounds, ) from ortools.math_opt.python.errors import InternalMathOptError from ortools.math_opt.python.errors import status_proto_to_exception from ortools.math_opt.python.expressions import evaluate_expression from ortools.math_opt.python.expressions import fast_sum from ortools.math_opt.python.indicator_constraints import IndicatorConstraint from ortools.math_opt.python.init_arguments import gurobi_isv_key_from_proto from ortools.math_opt.python.init_arguments import GurobiISVKey from ortools.math_opt.python.init_arguments import ( streamable_gurobi_init_arguments_from_proto, ) from ortools.math_opt.python.init_arguments import ( streamable_solver_init_arguments_from_proto, ) from ortools.math_opt.python.init_arguments import StreamableCpSatInitArguments from ortools.math_opt.python.init_arguments import StreamableEcosInitArguments from ortools.math_opt.python.init_arguments import StreamableGlopInitArguments from ortools.math_opt.python.init_arguments import StreamableGlpkInitArguments from ortools.math_opt.python.init_arguments import StreamableGScipInitArguments from ortools.math_opt.python.init_arguments import StreamableGurobiInitArguments from ortools.math_opt.python.init_arguments import StreamableHighsInitArguments from ortools.math_opt.python.init_arguments import StreamableOsqpInitArguments from ortools.math_opt.python.init_arguments import StreamablePdlpInitArguments from ortools.math_opt.python.init_arguments import StreamableSantoriniInitArguments from ortools.math_opt.python.init_arguments import StreamableScsInitArguments from ortools.math_opt.python.init_arguments import StreamableSolverInitArguments from ortools.math_opt.python.linear_constraints import LinearConstraint ``` -------------------------------- ### Get Minimum Start Time of an Interval Variable Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the minimum start time for an interval variable. ```python def StartMin(self, var): return _pywrapcp.Assignment_StartMin(self, var) ``` -------------------------------- ### StartValue Method Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html A shortcut to retrieve the start value of a specific variable ('var') in the nth solution. Useful for interval variables. ```python def StartValue(self, n, var): r"""This is a shortcut to get the StartValue of 'var' in the nth solution.""" return _pywrapcp.SolutionCollector_StartValue(self, n, var) ``` -------------------------------- ### Using IncrementalSolver with a Context Manager Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solve.html Demonstrates the recommended way to use IncrementalSolver by leveraging the 'with' statement for automatic resource management. This ensures the solver is properly closed after use. ```python with IncrementalSolver(model, SolverType.GLOP) as solver: ... ``` -------------------------------- ### Get IntervalVar Start Minimum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the minimum possible start time for an interval variable. This is part of a set of methods for querying, setting, and watching the start position. ```python def StartMin(self): return _pywrapcp.IntervalVar_StartMin(self) ``` -------------------------------- ### GetFirstSolutionHint Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Returns the current hint assignment. ```APIDOC ## GetFirstSolutionHint ### Description Returns the current hint assignment. ### Method (Not specified, likely a Python method call) ### Returns (type not specified) - The current hint assignment. ``` -------------------------------- ### Get Vehicle Start Node Index Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Returns the variable index of the starting node for a given vehicle's route. ```python def Start(self, vehicle): r""" Model inspection. Returns the variable index of the starting node of a vehicle route. """ return _pywrapcp.RoutingModel_Start(self, vehicle) ``` -------------------------------- ### Get Old IntervalVar Start Maximum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the previous maximum start time for an interval variable. Useful for understanding past constraints or state. ```python def OldStartMax(self): return _pywrapcp.IntervalVar_OldStartMax(self) ``` -------------------------------- ### Define SolutionHint for MIP and LP Solvers Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html Defines a suggested starting solution for MIP and LP solvers. MIP solvers primarily use primal information, while LP solvers can use both primal and dual information. This hint can be partial or infeasible for MIP solvers. ```python import dataclasses from typing import Dict from ortools.math_opt.python import variables from ortools.math_opt.python import linear_constraints from ortools.math_opt.python import model_parameters_pb2 from ortools.math_opt.python import sparse_containers @dataclasses.dataclass class SolutionHint: """A suggested starting solution for the solver. MIP solvers generally only want primal information (`variable_values`), while LP solvers want both primal and dual information (`dual_values`). Many MIP solvers can work with: (1) partial solutions that do not specify all variables or (2) infeasible solutions. In these cases, solvers typically solve a sub-MIP to complete/correct the hint. How the hint is used by the solver, if at all, is highly dependent on the solver, the problem type, and the algorithm used. The most reliable way to ensure your hint has an effect is to read the underlying solvers logs with and without the hint. Simplex-based LP solvers typically prefer an initial basis to a solution hint (they need to crossover to convert the hint to a basic feasible solution otherwise). Floating point values should be finite and not NaN, they are validated by MathOpt at Solve() time (resulting in an exception). Attributes: variable_values: a potentially partial assignment from the model's primal variables to finite (and not NaN) double values. dual_values: a potentially partial assignment from the model's linear constraints to finite (and not NaN) double values. """ variable_values: Dict[variables.Variable, float] = dataclasses.field( default_factory=dict ) dual_values: Dict[linear_constraints.LinearConstraint, float] = dataclasses.field( default_factory=dict ) def to_proto(self) -> model_parameters_pb2.SolutionHintProto: """Returns an equivalent protocol buffer to this.""" return model_parameters_pb2.SolutionHintProto( variable_values=sparse_containers.to_sparse_double_vector_proto( self.variable_values ), dual_values=sparse_containers.to_sparse_double_vector_proto( self.dual_values ), ) ``` -------------------------------- ### Get Old IntervalVar Start Minimum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the previous minimum start time for an interval variable. This may be useful for historical tracking or specific algorithm implementations. ```python def OldStartMin(self): return _pywrapcp.IntervalVar_OldStartMin(self) ``` -------------------------------- ### Interval Variable Accessors Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Methods to get the minimum, maximum, and current values for the start, duration, and end of an interval variable. ```APIDOC ## StartMin ### Description Gets the minimum start time of an interval variable. ### Method `StartMin(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## StartMax ### Description Gets the maximum start time of an interval variable. ### Method `StartMax(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## StartValue ### Description Gets the current start time of an interval variable. ### Method `StartValue(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## DurationMin ### Description Gets the minimum duration of an interval variable. ### Method `DurationMin(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## DurationMax ### Description Gets the maximum duration of an interval variable. ### Method `DurationMax(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## DurationValue ### Description Gets the current duration of an interval variable. ### Method `DurationValue(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## EndMin ### Description Gets the minimum end time of an interval variable. ### Method `EndMin(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## EndMax ### Description Gets the maximum end time of an interval variable. ### Method `EndMax(var)` ### Parameters - **var**: The interval variable. ``` ```APIDOC ## EndValue ### Description Gets the current end time of an interval variable. ### Method `EndValue(var)` ### Parameters - **var**: The interval variable. ``` -------------------------------- ### QuadraticProduct Initialization and Usage Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/variables.html Illustrates the initialization of a QuadraticProduct, representing a deferred multiplication of a scalar and a quadratic expression. This is useful for constructing quadratic forms. ```python scalar: float, quadratic: QuadraticBase) -> None: if not isinstance(scalar, (float, int)): raise TypeError( "unsupported type for scalar argument in " f"QuadraticProduct: {type(scalar).__name__!r}" ) if not isinstance(quadratic, QuadraticBase): raise TypeError( "unsupported type for linear argument in " f"QuadraticProduct: {type(quadratic).__name__!r}" ) self._scalar: float = float(scalar) self._quadratic: QuadraticBase = quadratic ``` -------------------------------- ### RoutingModel.MakeSelfDependentDimensionFinalizer Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Returns a composition of a local search decision builder with a greedy descent operator for the cumul of the start of each route and a guided slack finalizer. ```APIDOC ## RoutingModel.MakeSelfDependentDimensionFinalizer(self, dimension) ### Description Returns a composition of a local search decision builder with a greedy descent operator for the cumul of the start of each route and a guided slack finalizer. Provided there are no time windows and the maximum slacks are large enough, once the cumul of the start of route is fixed, the guided finalizer can find optimal values of the slacks for the rest of the route in time proportional to the length of the route. Therefore the composed finalizer generally works in time O(log(t)*n*m), where t is the latest possible departure time, n is the number of nodes in the network and m is the number of vehicles. ### Method `RoutingModel.MakeSelfDependentDimensionFinalizer(self, dimension)` ``` -------------------------------- ### init Source: https://or-tools.github.io/docs/pdoc/ortools/algorithms/python/knapsack_solver.html Initializes the solver and enters the problem to be solved. This method must be called before solving. ```APIDOC ## init(profits: list[int], weights: list[list[int]], capacities: list[int]) -> None ### Description Initializes the solver and enters the problem to be solved. This method must be called before solving. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **profits** (list[int]) - Required - A list of profits for each item. * **weights** (list[list[int]]) - Required - A list of lists, where each inner list represents the weights of an item across different dimensions. * **capacities** (list[int]) - Required - A list of capacities for each dimension of the knapsack. ``` -------------------------------- ### Get Depot Node Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Returns the variable index of the first starting or ending node for all routes. If all routes share a single depot, this returns that node's index. ```python def GetDepot(self): r""" Returns the variable index of the first starting or ending node of all routes. If all routes start and end at the same node (single depot), this is the node returned. """ return _pywrapcp.RoutingModel_GetDepot(self) ``` -------------------------------- ### __enter__ Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solve.html Enters the runtime context related to this solver. Returns the solver itself. ```APIDOC ## __enter__ ### Description Returns the solver itself. ### Method `__enter__() -> "IncrementalSolver"` ### Returns * "IncrementalSolver" - The solver instance. ``` -------------------------------- ### Initializing and Solving with IncrementalSolver Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solve.html This snippet shows the basic initialization of an IncrementalSolver and the structure of its solve method, including optional parameters for solve parameters, model parameters, and callbacks. ```python def __init__( self, opt_model: model.Model, solver_type: parameters.SolverType, *, streamable_init_args: Optional[ init_arguments.StreamableSolverInitArguments ] = None, remove_names: bool = False, ): streamable_init_args = ( streamable_init_args or init_arguments.StreamableSolverInitArguments() ) self._model = opt_model self._solver_type = solver_type self._update_tracker = self._model.add_update_tracker() try: self._proto_solver = solver.new( solver_type.value, self._model.export_model(remove_names=remove_names), streamable_init_args.to_proto(), ) except StatusNotOk as e: raise _status_not_ok_to_exception(e) from None self._closed = False def solve( self, *, params: Optional[parameters.SolveParameters] = None, model_params: Optional[model_parameters.ModelSolveParameters] = None, msg_cb: Optional[message_callback.SolveMessageCallback] = None, callback_reg: Optional[callback.CallbackRegistration] = None, cb: Optional[SolveCallback] = None, interrupter: Optional[solve_interrupter.SolveInterrupter] = None, ) -> result.SolveResult: """Solves the current optimization model. Args: params: The non-model specific solve parameters. model_params: The model specific solve parameters. msg_cb: An optional callback for solver messages. callback_reg: The parameters controlling when cb is called. cb: An optional callback for LP/MIP events. interrupter: An optional interrupter that the solver can use to interrupt the solve early. Returns: The result of the solve. Raises: RuntimeError: If called after being closed, or on a solve error. """ if self._closed: raise RuntimeError("the solver is closed") update = self._update_tracker.export_update() if update is not None: try: if not self._proto_solver.update(update): self._proto_solver = solver.new( self._solver_type.value, self._model.export_model(), parameters_pb2.SolverInitializerProto(), ) except StatusNotOk as e: raise _status_not_ok_to_exception(e) from None self._update_tracker.advance_checkpoint() params = params or parameters.SolveParameters() model_params = model_params or model_parameters.ModelSolveParameters() callback_reg = callback_reg or callback.CallbackRegistration() proto_cb = None if cb is not None: proto_cb = lambda x: cb( # pylint: disable=g-long-lambda callback.parse_callback_data(x, self._model) ).to_proto() try: result_proto = self._proto_solver.solve( params.to_proto(), model_params.to_proto(), msg_cb, callback_reg.to_proto(), proto_cb, interrupter.pybind_interrupter if interrupter is not None else None, ) except StatusNotOk as e: ``` -------------------------------- ### Get Fixed Cost of a Vehicle Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Retrieves the fixed cost associated with a specific vehicle's route. This cost is applied if the route is non-empty (contains more than just the start and end nodes). ```python def GetFixedCostOfVehicle(self, vehicle): r""" Returns the route fixed cost taken into account if the route of the vehicle is not empty, aka there's at least one node on the route other than the first and last nodes. """ return _pywrapcp.RoutingModel_GetFixedCostOfVehicle(self, vehicle) ``` -------------------------------- ### Get Flattened Intervals from Domain Source: https://or-tools.github.io/docs/pdoc/ortools/util/python/sorted_interval_list.html Returns the flattened list of interval bounds representing the domain. The output format is a list of integers where consecutive pairs define the start and end of each interval. ```python flat_intervals = domain.FlattenedIntervals() ``` -------------------------------- ### Model Optimization Problem Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model.html This example demonstrates how to model an optimization problem using the math_opt library. It defines binary and continuous variables, adds a linear constraint, and sets a linear objective function. The model is then solved using the GSCIP solver, and the results are printed. ```python #!/usr/bin/env python3 # Copyright 2010-2025 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A solver independent library for modeling optimization problems. Example use to model the optimization problem: max 2.0 * x + y s.t. x + y <= 1.5 x in {0.0, 1.0} y in [0.0, 2.5] model = mathopt.Model(name='my_model') x = model.add_binary_variable(name='x') y = model.add_variable(lb=0.0, ub=2.5, name='y') # We can directly use linear combinations of variables ... model.add_linear_constraint(x + y <= 1.5, name='c') # ... or build them incrementally. objective_expression = 0 objective_expression += 2 * x objective_expression += y model.maximize(objective_expression) # May raise a RuntimeError on invalid input or internal solver errors. result = mathopt.solve(model, mathopt.SolverType.GSCIP) if result.termination.reason not in (mathopt.TerminationReason.OPTIMAL, mathopt.TerminationReason.FEASIBLE): raise RuntimeError(f'model failed to solve: {result.termination}') print(f'Objective value: {result.objective_value()}') print(f'Value for variable x: {result.variable_values()[x]}') """ import math from typing import Iterator, Optional, Tuple, Union # typing.Self is only in python 3.11+, for OR-tools supports down to 3.8. from typing_extensions import Self from ortools.math_opt import model_pb2 from ortools.math_opt import model_update_pb2 from ortools.math_opt.elemental.python import cpp_elemental from ortools.math_opt.elemental.python import enums from ortools.math_opt.python import from_model from ortools.math_opt.python import indicator_constraints from ortools.math_opt.python import linear_constraints as linear_constraints_mod from ortools.math_opt.python import normalized_inequality from ortools.math_opt.python import objectives from ortools.math_opt.python import quadratic_constraints from ortools.math_opt.python import variables as variables_mod from ortools.math_opt.python.elemental import elemental class UpdateTracker: """Tracks updates to an optimization model from a ModelStorage. Do not instantiate directly, instead create through ModelStorage.add_update_tracker(). Querying an UpdateTracker after calling Model.remove_update_tracker will result in a model_storage.UsedUpdateTrackerAfterRemovalError. Example: mod = Model() x = mod.add_variable(0.0, 1.0, True, 'x') y = mod.add_variable(0.0, 1.0, True, 'y') tracker = mod.add_update_tracker() mod.set_variable_ub(x, 3.0) tracker.export_update() => "variable_updates: {upper_bounds: {ids: [0], values[3.0] }" mod.set_variable_ub(y, 2.0) tracker.export_update() => "variable_updates: {upper_bounds: {ids: [0, 1], values[3.0, 2.0] }" tracker.advance_checkpoint() tracker.export_update() => None mod.set_variable_ub(y, 4.0) tracker.export_update() => "variable_updates: {upper_bounds: {ids: [1], values[4.0] }" tracker.advance_checkpoint() mod.remove_update_tracker(tracker) """ def __init__( ``` -------------------------------- ### Cross Exchange Operator Example Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Shows the Cross operator for exchanging starting chains of two paths. It includes the possibility of exchanging entire paths, with fixed first and last nodes. ```c++ 1 -> [7] -> 3 -> 4 -> 5 6 -> [2] -> 8 1 -> [7] -> 4 -> 5 6 -> [2 -> 3] -> 8 1 -> [7] -> 5 6 -> [2 -> 3 -> 4] -> 8 ``` -------------------------------- ### SolutionHint Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html Represents a suggested starting solution for the solver. It can include primal information (variable values) and optionally dual information (dual values). This is useful for both MIP and LP solvers, with specific considerations for each. ```APIDOC ## SolutionHint ### Description A suggested starting solution for the solver. MIP solvers generally only want primal information (`variable_values`), while LP solvers want both primal and dual information (`dual_values`). Many MIP solvers can work with partial or infeasible solutions. ### Attributes - **variable_values** (Dict[variables.Variable, float]) - A potentially partial assignment from the model's primal variables to finite (and not NaN) double values. - **dual_values** (Dict[linear_constraints.LinearConstraint, float]) - A potentially partial assignment from the model's linear constraints to finite (and not NaN) double values. ### Method `to_proto()` - Returns an equivalent protocol buffer to this SolutionHint object. ``` -------------------------------- ### Make Chain Inactive Operator Example Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Shows the Make Chain Inactive operator, which removes a contiguous sequence of nodes from a path, making them inactive. The path's start and end nodes are preserved. ```c++ 1 -> 3 -> 4 with 2 inactive 1 -> 2 -> 4 with 3 inactive 1 -> 4 with 2 and 3 inactive ``` -------------------------------- ### IncrementalSolver Initialization Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solve.html Shows the constructor for the IncrementalSolver class, including its parameters for the optimization model, solver type, and optional initialization arguments. It also demonstrates exception handling for initialization errors. ```python def __init__( self, opt_model: model.Model, solver_type: parameters.SolverType, *, streamable_init_args: Optional[ init_arguments.StreamableSolverInitArguments ] = None, remove_names: bool = False, ): streamable_init_args = ( streamable_init_args or init_arguments.StreamableSolverInitArguments() ) self._model = opt_model self._solver_type = solver_type self._update_tracker = self._model.add_update_tracker() try: self._proto_solver = solver.new( solver_type.value, self._model.export_model(remove_names=remove_names), streamable_init_args.to_proto(), ) except StatusNotOk as e: raise _status_not_ok_to_exception(e) from None self._closed = False ``` -------------------------------- ### Interval Starts After Start With Delay Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Specifies that an interval must start after another interval starts, with a possible delay. Useful for managing parallel activities with staggered starts. ```python def StartsAfterStartWithDelay(self, other, delay): return _pywrapcp.IntervalVar_StartsAfterStartWithDelay(self, other, delay) ``` -------------------------------- ### Solution Class and Proto Conversion Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solution.html Demonstrates the Solution class structure and its methods for converting to and from Protocol Buffer messages. This is useful for serializing and deserializing solution data. ```python class Solution: """A solution to the optimization problem in a Model.""" primal_solution: Optional[PrimalSolution] = None dual_solution: Optional[DualSolution] = None basis: Optional[Basis] = None def to_proto(self) -> solution_pb2.SolutionProto: """Returns an equivalent proto for a solution.""" return solution_pb2.SolutionProto( primal_solution=( self.primal_solution.to_proto() if self.primal_solution is not None else None ), dual_solution=( self.dual_solution.to_proto() if self.dual_solution is not None else None ), basis=self.basis.to_proto() if self.basis is not None else None, ) def parse_solution( proto: solution_pb2.SolutionProto, mod: model.Model, *, validate: bool = True ) -> Solution: """Returns a Solution equivalent to the input proto.""" result = Solution() if proto.HasField("primal_solution"): result.primal_solution = parse_primal_solution( proto.primal_solution, mod, validate=validate ) if proto.HasField("dual_solution"): result.dual_solution = parse_dual_solution( proto.dual_solution, mod, validate=validate ) result.basis = ( parse_basis(proto.basis, mod, validate=validate) if proto.HasField("basis") else None ) return result ``` -------------------------------- ### Initialize MPSolverParameters Source: https://or-tools.github.io/docs/pdoc/ortools/linear_solver/pywraplp.html Initializes the MPSolverParameters object with default values for all parameters. This is the first step before modifying any solver settings. ```python solver_parameters = pywraplp.MPSolverParameters() ``` -------------------------------- ### Create Fixed Duration Start Synced on Start Interval Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Creates an interval variable with a fixed duration whose start is synchronized with the start of another interval, with a given offset. The performed status is also in sync. ```python def FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset): r""" Creates an interval var with a fixed duration whose start is synchronized with the start of another interval, with a given offset. The performed status is also in sync with the performed status of the given interval variable. """ return _pywrapcp.Solver_FixedDurationStartSyncedOnStartIntervalVar(self, interval_var, duration, offset) ``` -------------------------------- ### Creating a Linear Constraint Source: https://or-tools.github.io/docs/pdoc/ortools/linear_solver/python/model_builder.html Demonstrates how to create a new linear constraint with variables and coefficients. ```python x = model.new_num_var(0, 10, 'x') y = model.new_num_var(0, 10, 'y') linear_constraint = model.add(x + 2 * y == 5) ``` -------------------------------- ### SolutionHint Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html A suggested starting solution for the solver. MIP solvers generally only want primal information (`variable_values`), while LP solvers want both primal and dual information (`dual_values`). Many MIP solvers can work with partial or infeasible solutions. ```APIDOC ## class SolutionHint ### Description A suggested starting solution for the solver. MIP solvers generally only want primal information (`variable_values`), while LP solvers want both primal and dual information (`dual_values`). Many MIP solvers can work with partial or infeasible solutions. ### Attributes - **variable_values** (Dict[variables.Variable, float]) - A potentially partial assignment from the model's primal variables to finite (and not NaN) double values. - **dual_values** (Dict[linear_constraints.LinearConstraint, float]) - A potentially partial assignment from the model's linear constraints to finite (and not NaN) double values. ``` -------------------------------- ### Handle Start of Search Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Called by Start() after synchronizing the operator with the current assignment. Should be overridden instead of Start() to avoid calling IntVarLocalSearchOperator::Start explicitly. ```python def OnStart(self): r""" Called by Start() after synchronizing the operator with the current assignment. Should be overridden instead of Start() to avoid calling IntVarLocalSearchOperator::Start explicitly. """ return _pywrapcp.IntVarLocalSearchOperator_OnStart(self) ``` -------------------------------- ### new Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/core/python/solver.html Creates a new solver instance. This is a factory method for obtaining a solver object. ```APIDOC ## new ### Description Creates a new solver instance. This is a factory method for obtaining a solver object. ### Method `new` ### Parameters - **solver_type** (operations_research::math_opt::SolverTypeProto) - The type of solver to create. - **model** (operations_research::math_opt::ModelProto) - The initial optimization model. - **solver_initializer** (operations_research::math_opt::SolverInitializerProto) - Initializer for the solver. ### Returns - **operations_research::math_opt::PybindSolver** - A new solver instance. ``` -------------------------------- ### Set IntervalVar Start Minimum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the minimum possible start time for an interval variable. This method is part of the interface for controlling the start position. ```python def SetStartMin(self, m): return _pywrapcp.IntervalVar_SetStartMin(self, m) ``` -------------------------------- ### Interval Starts After Start Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Specifies that an interval must start after another interval begins. This is useful for managing parallel tasks where one must commence later than the other. ```python def StartsAfterStart(self, other): return _pywrapcp.IntervalVar_StartsAfterStart(self, other) ``` -------------------------------- ### Define SolverResources with CPU and RAM Hints Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/solver_resources.html Use this class to specify the expected CPU and RAM usage for a remote solver. The CPU parameter is a soft limit, while RAM is a hard limit. Leave parameters unset if not applicable or if defaults are preferred. ```python # Copyright 2010-2025 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Configures solver resources.""" import dataclasses from typing import Optional from ortools.math_opt import rpc_pb2 @dataclasses.dataclass class SolverResources: """The hints on the resources a remote solve is expected to use. These parameters are hints and may be ignored by the remote server (in particular in case of solve in a local subprocess, for example). When using remote_solve() and remote_compute_infeasible_subsystem(), these hints are mostly optional as some defaults will be computed based on the other parameters. When using remote_streaming_solve() these hints are used to dimension the resources available during the execution of every action; thus it is recommended to set them. MOE:begin_intracomment_strip The go/uoss server will use these parameters to do a bin-packing of all requests. Parameter cpu is a soft-limit, the solve may still be able to use more CPUs. The ram parameter is an hard-limit, an out-of-memory error will occur if the solve attempts to use more memory. MOE:end_intracomment_strip Attributes: cpu: The number of solver threads that are expected to actually execute in parallel. Must be finite and >0.0. For example a value of 3.0 means that if the solver has 5 threads that can execute we expect at least 3 of these threads to be scheduled in parallel for any given time slice of the operating system scheduler. A fractional value indicates that we don't expect the operating system to constantly schedule the solver's work. For example with 0.5 we would expect the solver's threads to be scheduled half the time. This parameter is usually used in conjunction with SolveParameters.threads. For some solvers like Gurobi it makes sense to use SolverResources.cpu = SolveParameters.threads. For other solvers like CP-SAT, it may makes sense to use a value lower than the number of threads as not all threads may be ready to be scheduled at the same time. It is better to consult each solver documentation to set this parameter. Note that if the SolveParameters.threads is not set then this parameter should also be left unset. ram: The limit of RAM for the solve in bytes. Must be finite and >=1.0 (even though it should in practice be much larger). """ cpu: Optional[float] = None ram: Optional[float] = None def to_proto(self) -> rpc_pb2.SolverResourcesProto: return rpc_pb2.SolverResourcesProto(cpu=self.cpu, ram=self.ram) ``` -------------------------------- ### Set IntervalVar Start Range Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets both the minimum and maximum possible start times for an interval variable. This efficiently defines the allowed range for the start position. ```python def SetStartRange(self, mi, ma): return _pywrapcp.IntervalVar_SetStartRange(self, mi, ma) ``` -------------------------------- ### Parse SolutionHint from Proto Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html Shows how to parse a SolutionHint protocol buffer back into a SolutionHint object, given a MathOpt Model. This is useful when receiving hints from external sources or saved states. ```python parsed_hint = parse_solution_hint(hint_proto, mod) ``` -------------------------------- ### LinearProduct Initialization and Usage Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/variables.html Demonstrates the initialization of a LinearProduct, which represents a deferred multiplication of a scalar and a linear expression. It's used for building linear expressions incrementally. ```python scalar: float, linear: LinearBase) -> None: if not isinstance(scalar, (float, int)): raise TypeError( "unsupported type for scalar argument in " f"LinearProduct: {type(scalar).__name__!r}" ) if not isinstance(linear, LinearBase): raise TypeError( "unsupported type for linear argument in " f"LinearProduct: {type(linear).__name__!r}" ) self._scalar: float = float(scalar) self._linear: LinearBase = linear ``` -------------------------------- ### Set IntervalVar Start Maximum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the maximum possible start time for an interval variable. Use this to constrain the start time within a specific range. ```python def SetStartMax(self, m): return _pywrapcp.IntervalVar_SetStartMax(self, m) ``` -------------------------------- ### Load Solution From Protocol Buffer Source: https://or-tools.github.io/docs/pdoc/ortools/linear_solver/pywraplp.html Loads a solution from a protocol buffer. ```python def LoadSolutionFromProto(self, *args): return _pywraplp.Solver_LoadSolutionFromProto(self, *args) ``` -------------------------------- ### Solution Callback Initialization Source: https://or-tools.github.io/docs/pdoc/ortools/sat/python/cp_model.html Initializes a custom solution callback by inheriting from `SolutionCallback` and calling the parent constructor. ```python cmh.SolutionCallback.__init__(self) ``` -------------------------------- ### Create Interval Variable with Start and End Source: https://or-tools.github.io/docs/pdoc/ortools/sat/python/cp_model.html Creates an interval variable given its start and end points, inferring the size. This is useful when the size is not fixed or directly known but can be derived from start and end. ```python model.new_interval_var(start=start, end=end, name=name) ``` -------------------------------- ### Example Usage of Message Callbacks Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/message_callback.html Demonstrates typical usage patterns for message callbacks when solving a model. This includes printing messages to standard output and logging them using absl.logging. ```python result = solve.solve( model, parameters.SolverType.GSCIP, msg_cb=message_callback.printer_message_callback(prefix='[solver] ')) result = solve.solve( model, parameters.SolverType.GSCIP, msg_cb=lambda msgs: message_callback.log_messages( msgs, prefix='[solver] ')) ``` -------------------------------- ### Set Interval Start Value Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the current start time value for an interval variable. ```python def SetStartValue(self, v): return _pywrapcp.IntervalVarElement_SetStartValue(self, v) ``` -------------------------------- ### LoadSolutionFromProto Source: https://or-tools.github.io/docs/pdoc/ortools/linear_solver/pywraplp.html Loads a solution from a protocol buffer. ```APIDOC ## LoadSolutionFromProto ### Description Loads a solution from a protocol buffer. ### Method `Solver.LoadSolutionFromProto(*args)` ### Parameters * **args** - Required - Arguments for loading the solution. ### Returns None ``` -------------------------------- ### Set Interval Start Maximum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the maximum possible start time for an interval variable. ```python def SetStartMax(self, m): return _pywrapcp.IntervalVarElement_SetStartMax(self, m) ``` -------------------------------- ### Set Interval Start Minimum Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the minimum possible start time for an interval variable. ```python def SetStartMin(self, m): return _pywrapcp.IntervalVarElement_SetStartMin(self, m) ``` -------------------------------- ### Search Log with Callback Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets up a callback to log search progress at a specified period. ```python 2142 def SearchLogWithCallback(self, period, callback): 2143 return _pywrapcp.Solver_SearchLogWithCallback(self, period, callback) ``` -------------------------------- ### Create Elemental model from proto Source: https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/elemental/elemental.html Constructs an Elemental model instance from an existing MathOpt model protocol buffer. This is useful for loading or converting models. ```python elemental_model = Elemental.from_model_proto(model_proto) ``` -------------------------------- ### Set Assigned Start Time for an Interval Variable Source: https://or-tools.github.io/docs/pdoc/ortools/constraint_solver/pywrapcp.html Sets the assigned start time for an interval variable. ```python def SetStartValue(self, var, value): return _pywrapcp.Assignment_SetStartValue(self, var, value) ```