ortools.math_opt.python.model_parameters

Model specific solver configuration (e.g. starting basis).

  1#!/usr/bin/env python3
  2# Copyright 2010-2025 Google LLC
  3# Licensed under the Apache License, Version 2.0 (the "License");
  4# you may not use this file except in compliance with the License.
  5# You may obtain a copy of the License at
  6#
  7#     http://www.apache.org/licenses/LICENSE-2.0
  8#
  9# Unless required by applicable law or agreed to in writing, software
 10# distributed under the License is distributed on an "AS IS" BASIS,
 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12# See the License for the specific language governing permissions and
 13# limitations under the License.
 14
 15"""Model specific solver configuration (e.g. starting basis)."""
 16import dataclasses
 17import datetime
 18from typing import Dict, List, Optional, Set
 19
 20from ortools.math_opt import model_parameters_pb2
 21from ortools.math_opt.python import linear_constraints
 22from ortools.math_opt.python import model
 23from ortools.math_opt.python import objectives
 24from ortools.math_opt.python import solution
 25from ortools.math_opt.python import sparse_containers
 26from ortools.math_opt.python import variables
 27
 28
 29@dataclasses.dataclass
 30class SolutionHint:
 31    """A suggested starting solution for the solver.
 32
 33    MIP solvers generally only want primal information (`variable_values`),
 34    while LP solvers want both primal and dual information (`dual_values`).
 35
 36    Many MIP solvers can work with: (1) partial solutions that do not specify all
 37    variables or (2) infeasible solutions. In these cases, solvers typically solve
 38    a sub-MIP to complete/correct the hint.
 39
 40    How the hint is used by the solver, if at all, is highly dependent on the
 41    solver, the problem type, and the algorithm used. The most reliable way to
 42    ensure your hint has an effect is to read the underlying solvers logs with
 43    and without the hint.
 44
 45    Simplex-based LP solvers typically prefer an initial basis to a solution
 46    hint (they need to crossover to convert the hint to a basic feasible
 47    solution otherwise).
 48
 49    Floating point values should be finite and not NaN, they are validated by
 50    MathOpt at Solve() time (resulting in an exception).
 51
 52    Attributes:
 53      variable_values: a potentially partial assignment from the model's primal
 54        variables to finite (and not NaN) double values.
 55      dual_values: a potentially partial assignment from the model's linear
 56        constraints to finite (and not NaN) double values.
 57    """
 58
 59    variable_values: Dict[variables.Variable, float] = dataclasses.field(
 60        default_factory=dict
 61    )
 62    dual_values: Dict[linear_constraints.LinearConstraint, float] = dataclasses.field(
 63        default_factory=dict
 64    )
 65
 66    def to_proto(self) -> model_parameters_pb2.SolutionHintProto:
 67        """Returns an equivalent protocol buffer to this."""
 68        return model_parameters_pb2.SolutionHintProto(
 69            variable_values=sparse_containers.to_sparse_double_vector_proto(
 70                self.variable_values
 71            ),
 72            dual_values=sparse_containers.to_sparse_double_vector_proto(
 73                self.dual_values
 74            ),
 75        )
 76
 77
 78def parse_solution_hint(
 79    hint_proto: model_parameters_pb2.SolutionHintProto, mod: model.Model
 80) -> SolutionHint:
 81    """Returns an equivalent SolutionHint to `hint_proto`.
 82
 83    Args:
 84      hint_proto: The solution, as encoded by the ids of the variables and
 85        constraints.
 86      mod: A MathOpt Model that must contain variables and linear constraints with
 87        the ids from hint_proto.
 88
 89    Returns:
 90      A SolutionHint equivalent.
 91
 92    Raises:
 93      ValueError if hint_proto is invalid or refers to variables or constraints
 94      not in mod.
 95    """
 96    return SolutionHint(
 97        variable_values=sparse_containers.parse_variable_map(
 98            hint_proto.variable_values, mod
 99        ),
100        dual_values=sparse_containers.parse_linear_constraint_map(
101            hint_proto.dual_values, mod
102        ),
103    )
104
105
106@dataclasses.dataclass
107class ObjectiveParameters:
108    """Parameters for an individual objective in a multi-objective model.
109
110    This class mirrors (and can generate) the related proto
111    model_parameters_pb2.ObjectiveParametersProto.
112
113    Attributes:
114      objective_degradation_absolute_tolerance: Optional objective degradation
115        absolute tolerance. For a hierarchical multi-objective solver, each
116        objective fⁱ is processed in priority order: the solver determines the
117        optimal objective value Γⁱ, if it exists, subject to all constraints in
118        the model and the additional constraints that fᵏ(x) = Γᵏ (within
119        tolerances) for each k < i. If set, a solution is considered to be "within
120        tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤
121        `objective_degradation_absolute_tolerance`. See also
122        `objective_degradation_relative_tolerance`; if both parameters are set for
123        a given objective, the solver need only satisfy one to be considered
124        "within tolerances".  If not None, must be nonnegative.
125      objective_degradation_relative_tolerance: Optional objective degradation
126        relative tolerance. For a hierarchical multi-objective solver, each
127        objective fⁱ is processed in priority order: the solver determines the
128        optimal objective value Γⁱ, if it exists, subject to all constraints in
129        the model and the additional constraints that fᵏ(x) = Γᵏ (within
130        tolerances) for each k < i. If set, a solution is considered to be "within
131        tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤
132        `objective_degradation_relative_tolerance` * |Γᵏ|. See also
133        `objective_degradation_absolute_tolerance`; if both parameters are set for
134        a given objective, the solver need only satisfy one to be considered
135        "within tolerances". If not None, must be nonnegative.
136      time_limit: The maximum time a solver should spend on optimizing this
137        particular objective (or infinite if not set). Note that this does not
138        supersede the global time limit in SolveParameters.time_limit; both will
139        be enforced when set. This value is not a hard limit, solve time may
140        slightly exceed this value.
141    """
142
143    objective_degradation_absolute_tolerance: Optional[float] = None
144    objective_degradation_relative_tolerance: Optional[float] = None
145    time_limit: Optional[datetime.timedelta] = None
146
147    def to_proto(self) -> model_parameters_pb2.ObjectiveParametersProto:
148        """Returns an equivalent protocol buffer."""
149        result = model_parameters_pb2.ObjectiveParametersProto()
150        if self.objective_degradation_absolute_tolerance is not None:
151            result.objective_degradation_absolute_tolerance = (
152                self.objective_degradation_absolute_tolerance
153            )
154        if self.objective_degradation_relative_tolerance is not None:
155            result.objective_degradation_relative_tolerance = (
156                self.objective_degradation_relative_tolerance
157            )
158        if self.time_limit is not None:
159            result.time_limit.FromTimedelta(self.time_limit)
160        return result
161
162
163def parse_objective_parameters(
164    proto: model_parameters_pb2.ObjectiveParametersProto,
165) -> ObjectiveParameters:
166    """Returns an equivalent ObjectiveParameters to the input proto."""
167    result = ObjectiveParameters()
168    if proto.HasField("objective_degradation_absolute_tolerance"):
169        result.objective_degradation_absolute_tolerance = (
170            proto.objective_degradation_absolute_tolerance
171        )
172    if proto.HasField("objective_degradation_relative_tolerance"):
173        result.objective_degradation_relative_tolerance = (
174            proto.objective_degradation_relative_tolerance
175        )
176    if proto.HasField("time_limit"):
177        result.time_limit = proto.time_limit.ToTimedelta()
178    return result
179
180
181@dataclasses.dataclass
182class ModelSolveParameters:
183    """Model specific solver configuration, for example, an initial basis.
184
185    This class mirrors (and can generate) the related proto
186    model_parameters_pb2.ModelSolveParametersProto.
187
188    Attributes:
189      variable_values_filter: Only return solution and primal ray values for
190        variables accepted by this filter (default accepts all variables).
191      dual_values_filter: Only return dual variable values and dual ray values for
192        linear constraints accepted by this filter (default accepts all linear
193        constraints).
194      quadratic_dual_values_filter: Only return quadratic constraint dual values
195        accepted by this filter (default accepts all quadratic constraints).
196      reduced_costs_filter: Only return reduced cost and dual ray values for
197        variables accepted by this filter (default accepts all variables).
198      initial_basis: If set, provides a warm start for simplex based solvers.
199      solution_hints: Optional solution hints. If the underlying solver only
200        accepts a single hint, the first hint is used.
201      branching_priorities: Optional branching priorities. Variables with higher
202        values will be branched on first. Variables for which priorities are not
203        set get the solver's default priority (usually zero).
204      objective_parameters: Optional per objective parameters used only only for
205        multi-objective models.
206      lazy_linear_constraints: Optional lazy constraint annotations. Included
207        linear constraints will be marked as "lazy" with supporting solvers,
208        meaning that they will only be added to the working model as-needed as the
209        solver runs. Note that this an algorithmic hint that does not affect the
210        model's feasible region; solvers not supporting these annotations will
211        simply ignore it.
212    """
213
214    variable_values_filter: sparse_containers.VariableFilter = (
215        sparse_containers.VariableFilter()
216    )
217    dual_values_filter: sparse_containers.LinearConstraintFilter = (
218        sparse_containers.LinearConstraintFilter()
219    )
220    quadratic_dual_values_filter: sparse_containers.QuadraticConstraintFilter = (
221        sparse_containers.QuadraticConstraintFilter()
222    )
223    reduced_costs_filter: sparse_containers.VariableFilter = (
224        sparse_containers.VariableFilter()
225    )
226    initial_basis: Optional[solution.Basis] = None
227    solution_hints: List[SolutionHint] = dataclasses.field(default_factory=list)
228    branching_priorities: Dict[variables.Variable, int] = dataclasses.field(
229        default_factory=dict
230    )
231    objective_parameters: Dict[objectives.Objective, ObjectiveParameters] = (
232        dataclasses.field(default_factory=dict)
233    )
234    lazy_linear_constraints: Set[linear_constraints.LinearConstraint] = (
235        dataclasses.field(default_factory=set)
236    )
237
238    def to_proto(self) -> model_parameters_pb2.ModelSolveParametersProto:
239        """Returns an equivalent protocol buffer."""
240        # TODO(b/236289022): these methods should check that the variables are from
241        # the correct model.
242        result = model_parameters_pb2.ModelSolveParametersProto(
243            variable_values_filter=self.variable_values_filter.to_proto(),
244            dual_values_filter=self.dual_values_filter.to_proto(),
245            quadratic_dual_values_filter=self.quadratic_dual_values_filter.to_proto(),
246            reduced_costs_filter=self.reduced_costs_filter.to_proto(),
247            branching_priorities=sparse_containers.to_sparse_int32_vector_proto(
248                self.branching_priorities
249            ),
250        )
251        if self.initial_basis:
252            result.initial_basis.CopyFrom(self.initial_basis.to_proto())
253        for hint in self.solution_hints:
254            result.solution_hints.append(hint.to_proto())
255        for obj, params in self.objective_parameters.items():
256            if isinstance(obj, objectives.AuxiliaryObjective):
257                result.auxiliary_objective_parameters[obj.id].CopyFrom(
258                    params.to_proto()
259                )
260            else:
261                result.primary_objective_parameters.CopyFrom(params.to_proto())
262        result.lazy_linear_constraint_ids[:] = sorted(
263            con.id for con in self.lazy_linear_constraints
264        )
265        return result
@dataclasses.dataclass
class SolutionHint:
30@dataclasses.dataclass
31class SolutionHint:
32    """A suggested starting solution for the solver.
33
34    MIP solvers generally only want primal information (`variable_values`),
35    while LP solvers want both primal and dual information (`dual_values`).
36
37    Many MIP solvers can work with: (1) partial solutions that do not specify all
38    variables or (2) infeasible solutions. In these cases, solvers typically solve
39    a sub-MIP to complete/correct the hint.
40
41    How the hint is used by the solver, if at all, is highly dependent on the
42    solver, the problem type, and the algorithm used. The most reliable way to
43    ensure your hint has an effect is to read the underlying solvers logs with
44    and without the hint.
45
46    Simplex-based LP solvers typically prefer an initial basis to a solution
47    hint (they need to crossover to convert the hint to a basic feasible
48    solution otherwise).
49
50    Floating point values should be finite and not NaN, they are validated by
51    MathOpt at Solve() time (resulting in an exception).
52
53    Attributes:
54      variable_values: a potentially partial assignment from the model's primal
55        variables to finite (and not NaN) double values.
56      dual_values: a potentially partial assignment from the model's linear
57        constraints to finite (and not NaN) double values.
58    """
59
60    variable_values: Dict[variables.Variable, float] = dataclasses.field(
61        default_factory=dict
62    )
63    dual_values: Dict[linear_constraints.LinearConstraint, float] = dataclasses.field(
64        default_factory=dict
65    )
66
67    def to_proto(self) -> model_parameters_pb2.SolutionHintProto:
68        """Returns an equivalent protocol buffer to this."""
69        return model_parameters_pb2.SolutionHintProto(
70            variable_values=sparse_containers.to_sparse_double_vector_proto(
71                self.variable_values
72            ),
73            dual_values=sparse_containers.to_sparse_double_vector_proto(
74                self.dual_values
75            ),
76        )

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.
SolutionHint( variable_values: Dict[ortools.math_opt.python.variables.Variable, float] = <factory>, dual_values: Dict[ortools.math_opt.python.linear_constraints.LinearConstraint, float] = <factory>)
variable_values: Dict[ortools.math_opt.python.variables.Variable, float]
def to_proto(self) -> ortools.math_opt.model_parameters_pb2.SolutionHintProto:
67    def to_proto(self) -> model_parameters_pb2.SolutionHintProto:
68        """Returns an equivalent protocol buffer to this."""
69        return model_parameters_pb2.SolutionHintProto(
70            variable_values=sparse_containers.to_sparse_double_vector_proto(
71                self.variable_values
72            ),
73            dual_values=sparse_containers.to_sparse_double_vector_proto(
74                self.dual_values
75            ),
76        )

Returns an equivalent protocol buffer to this.

 79def parse_solution_hint(
 80    hint_proto: model_parameters_pb2.SolutionHintProto, mod: model.Model
 81) -> SolutionHint:
 82    """Returns an equivalent SolutionHint to `hint_proto`.
 83
 84    Args:
 85      hint_proto: The solution, as encoded by the ids of the variables and
 86        constraints.
 87      mod: A MathOpt Model that must contain variables and linear constraints with
 88        the ids from hint_proto.
 89
 90    Returns:
 91      A SolutionHint equivalent.
 92
 93    Raises:
 94      ValueError if hint_proto is invalid or refers to variables or constraints
 95      not in mod.
 96    """
 97    return SolutionHint(
 98        variable_values=sparse_containers.parse_variable_map(
 99            hint_proto.variable_values, mod
100        ),
101        dual_values=sparse_containers.parse_linear_constraint_map(
102            hint_proto.dual_values, mod
103        ),
104    )

Returns an equivalent SolutionHint to hint_proto.

Arguments:
  • hint_proto: The solution, as encoded by the ids of the variables and constraints.
  • mod: A MathOpt Model that must contain variables and linear constraints with the ids from hint_proto.
Returns:

A SolutionHint equivalent.

Raises:
  • ValueError if hint_proto is invalid or refers to variables or constraints
  • not in mod.
@dataclasses.dataclass
class ObjectiveParameters:
107@dataclasses.dataclass
108class ObjectiveParameters:
109    """Parameters for an individual objective in a multi-objective model.
110
111    This class mirrors (and can generate) the related proto
112    model_parameters_pb2.ObjectiveParametersProto.
113
114    Attributes:
115      objective_degradation_absolute_tolerance: Optional objective degradation
116        absolute tolerance. For a hierarchical multi-objective solver, each
117        objective fⁱ is processed in priority order: the solver determines the
118        optimal objective value Γⁱ, if it exists, subject to all constraints in
119        the model and the additional constraints that fᵏ(x) = Γᵏ (within
120        tolerances) for each k < i. If set, a solution is considered to be "within
121        tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤
122        `objective_degradation_absolute_tolerance`. See also
123        `objective_degradation_relative_tolerance`; if both parameters are set for
124        a given objective, the solver need only satisfy one to be considered
125        "within tolerances".  If not None, must be nonnegative.
126      objective_degradation_relative_tolerance: Optional objective degradation
127        relative tolerance. For a hierarchical multi-objective solver, each
128        objective fⁱ is processed in priority order: the solver determines the
129        optimal objective value Γⁱ, if it exists, subject to all constraints in
130        the model and the additional constraints that fᵏ(x) = Γᵏ (within
131        tolerances) for each k < i. If set, a solution is considered to be "within
132        tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤
133        `objective_degradation_relative_tolerance` * |Γᵏ|. See also
134        `objective_degradation_absolute_tolerance`; if both parameters are set for
135        a given objective, the solver need only satisfy one to be considered
136        "within tolerances". If not None, must be nonnegative.
137      time_limit: The maximum time a solver should spend on optimizing this
138        particular objective (or infinite if not set). Note that this does not
139        supersede the global time limit in SolveParameters.time_limit; both will
140        be enforced when set. This value is not a hard limit, solve time may
141        slightly exceed this value.
142    """
143
144    objective_degradation_absolute_tolerance: Optional[float] = None
145    objective_degradation_relative_tolerance: Optional[float] = None
146    time_limit: Optional[datetime.timedelta] = None
147
148    def to_proto(self) -> model_parameters_pb2.ObjectiveParametersProto:
149        """Returns an equivalent protocol buffer."""
150        result = model_parameters_pb2.ObjectiveParametersProto()
151        if self.objective_degradation_absolute_tolerance is not None:
152            result.objective_degradation_absolute_tolerance = (
153                self.objective_degradation_absolute_tolerance
154            )
155        if self.objective_degradation_relative_tolerance is not None:
156            result.objective_degradation_relative_tolerance = (
157                self.objective_degradation_relative_tolerance
158            )
159        if self.time_limit is not None:
160            result.time_limit.FromTimedelta(self.time_limit)
161        return result

Parameters for an individual objective in a multi-objective model.

This class mirrors (and can generate) the related proto model_parameters_pb2.ObjectiveParametersProto.

Attributes:
  • objective_degradation_absolute_tolerance: Optional objective degradation absolute tolerance. For a hierarchical multi-objective solver, each objective fⁱ is processed in priority order: the solver determines the optimal objective value Γⁱ, if it exists, subject to all constraints in the model and the additional constraints that fᵏ(x) = Γᵏ (within tolerances) for each k < i. If set, a solution is considered to be "within tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤ objective_degradation_absolute_tolerance. See also objective_degradation_relative_tolerance; if both parameters are set for a given objective, the solver need only satisfy one to be considered "within tolerances". If not None, must be nonnegative.
  • objective_degradation_relative_tolerance: Optional objective degradation relative tolerance. For a hierarchical multi-objective solver, each objective fⁱ is processed in priority order: the solver determines the optimal objective value Γⁱ, if it exists, subject to all constraints in the model and the additional constraints that fᵏ(x) = Γᵏ (within tolerances) for each k < i. If set, a solution is considered to be "within tolerances" for this objective fᵏ if |fᵏ(x) - Γᵏ| ≤ objective_degradation_relative_tolerance * |Γᵏ|. See also objective_degradation_absolute_tolerance; if both parameters are set for a given objective, the solver need only satisfy one to be considered "within tolerances". If not None, must be nonnegative.
  • time_limit: The maximum time a solver should spend on optimizing this particular objective (or infinite if not set). Note that this does not supersede the global time limit in SolveParameters.time_limit; both will be enforced when set. This value is not a hard limit, solve time may slightly exceed this value.
ObjectiveParameters( objective_degradation_absolute_tolerance: float | None = None, objective_degradation_relative_tolerance: float | None = None, time_limit: datetime.timedelta | None = None)
objective_degradation_absolute_tolerance: float | None = None
objective_degradation_relative_tolerance: float | None = None
time_limit: datetime.timedelta | None = None
148    def to_proto(self) -> model_parameters_pb2.ObjectiveParametersProto:
149        """Returns an equivalent protocol buffer."""
150        result = model_parameters_pb2.ObjectiveParametersProto()
151        if self.objective_degradation_absolute_tolerance is not None:
152            result.objective_degradation_absolute_tolerance = (
153                self.objective_degradation_absolute_tolerance
154            )
155        if self.objective_degradation_relative_tolerance is not None:
156            result.objective_degradation_relative_tolerance = (
157                self.objective_degradation_relative_tolerance
158            )
159        if self.time_limit is not None:
160            result.time_limit.FromTimedelta(self.time_limit)
161        return result

Returns an equivalent protocol buffer.

def parse_objective_parameters( proto: ortools.math_opt.model_parameters_pb2.ObjectiveParametersProto) -> ObjectiveParameters:
164def parse_objective_parameters(
165    proto: model_parameters_pb2.ObjectiveParametersProto,
166) -> ObjectiveParameters:
167    """Returns an equivalent ObjectiveParameters to the input proto."""
168    result = ObjectiveParameters()
169    if proto.HasField("objective_degradation_absolute_tolerance"):
170        result.objective_degradation_absolute_tolerance = (
171            proto.objective_degradation_absolute_tolerance
172        )
173    if proto.HasField("objective_degradation_relative_tolerance"):
174        result.objective_degradation_relative_tolerance = (
175            proto.objective_degradation_relative_tolerance
176        )
177    if proto.HasField("time_limit"):
178        result.time_limit = proto.time_limit.ToTimedelta()
179    return result

Returns an equivalent ObjectiveParameters to the input proto.

@dataclasses.dataclass
class ModelSolveParameters:
182@dataclasses.dataclass
183class ModelSolveParameters:
184    """Model specific solver configuration, for example, an initial basis.
185
186    This class mirrors (and can generate) the related proto
187    model_parameters_pb2.ModelSolveParametersProto.
188
189    Attributes:
190      variable_values_filter: Only return solution and primal ray values for
191        variables accepted by this filter (default accepts all variables).
192      dual_values_filter: Only return dual variable values and dual ray values for
193        linear constraints accepted by this filter (default accepts all linear
194        constraints).
195      quadratic_dual_values_filter: Only return quadratic constraint dual values
196        accepted by this filter (default accepts all quadratic constraints).
197      reduced_costs_filter: Only return reduced cost and dual ray values for
198        variables accepted by this filter (default accepts all variables).
199      initial_basis: If set, provides a warm start for simplex based solvers.
200      solution_hints: Optional solution hints. If the underlying solver only
201        accepts a single hint, the first hint is used.
202      branching_priorities: Optional branching priorities. Variables with higher
203        values will be branched on first. Variables for which priorities are not
204        set get the solver's default priority (usually zero).
205      objective_parameters: Optional per objective parameters used only only for
206        multi-objective models.
207      lazy_linear_constraints: Optional lazy constraint annotations. Included
208        linear constraints will be marked as "lazy" with supporting solvers,
209        meaning that they will only be added to the working model as-needed as the
210        solver runs. Note that this an algorithmic hint that does not affect the
211        model's feasible region; solvers not supporting these annotations will
212        simply ignore it.
213    """
214
215    variable_values_filter: sparse_containers.VariableFilter = (
216        sparse_containers.VariableFilter()
217    )
218    dual_values_filter: sparse_containers.LinearConstraintFilter = (
219        sparse_containers.LinearConstraintFilter()
220    )
221    quadratic_dual_values_filter: sparse_containers.QuadraticConstraintFilter = (
222        sparse_containers.QuadraticConstraintFilter()
223    )
224    reduced_costs_filter: sparse_containers.VariableFilter = (
225        sparse_containers.VariableFilter()
226    )
227    initial_basis: Optional[solution.Basis] = None
228    solution_hints: List[SolutionHint] = dataclasses.field(default_factory=list)
229    branching_priorities: Dict[variables.Variable, int] = dataclasses.field(
230        default_factory=dict
231    )
232    objective_parameters: Dict[objectives.Objective, ObjectiveParameters] = (
233        dataclasses.field(default_factory=dict)
234    )
235    lazy_linear_constraints: Set[linear_constraints.LinearConstraint] = (
236        dataclasses.field(default_factory=set)
237    )
238
239    def to_proto(self) -> model_parameters_pb2.ModelSolveParametersProto:
240        """Returns an equivalent protocol buffer."""
241        # TODO(b/236289022): these methods should check that the variables are from
242        # the correct model.
243        result = model_parameters_pb2.ModelSolveParametersProto(
244            variable_values_filter=self.variable_values_filter.to_proto(),
245            dual_values_filter=self.dual_values_filter.to_proto(),
246            quadratic_dual_values_filter=self.quadratic_dual_values_filter.to_proto(),
247            reduced_costs_filter=self.reduced_costs_filter.to_proto(),
248            branching_priorities=sparse_containers.to_sparse_int32_vector_proto(
249                self.branching_priorities
250            ),
251        )
252        if self.initial_basis:
253            result.initial_basis.CopyFrom(self.initial_basis.to_proto())
254        for hint in self.solution_hints:
255            result.solution_hints.append(hint.to_proto())
256        for obj, params in self.objective_parameters.items():
257            if isinstance(obj, objectives.AuxiliaryObjective):
258                result.auxiliary_objective_parameters[obj.id].CopyFrom(
259                    params.to_proto()
260                )
261            else:
262                result.primary_objective_parameters.CopyFrom(params.to_proto())
263        result.lazy_linear_constraint_ids[:] = sorted(
264            con.id for con in self.lazy_linear_constraints
265        )
266        return result

Model specific solver configuration, for example, an initial basis.

This class mirrors (and can generate) the related proto model_parameters_pb2.ModelSolveParametersProto.

Attributes:
  • variable_values_filter: Only return solution and primal ray values for variables accepted by this filter (default accepts all variables).
  • dual_values_filter: Only return dual variable values and dual ray values for linear constraints accepted by this filter (default accepts all linear constraints).
  • quadratic_dual_values_filter: Only return quadratic constraint dual values accepted by this filter (default accepts all quadratic constraints).
  • reduced_costs_filter: Only return reduced cost and dual ray values for variables accepted by this filter (default accepts all variables).
  • initial_basis: If set, provides a warm start for simplex based solvers.
  • solution_hints: Optional solution hints. If the underlying solver only accepts a single hint, the first hint is used.
  • branching_priorities: Optional branching priorities. Variables with higher values will be branched on first. Variables for which priorities are not set get the solver's default priority (usually zero).
  • objective_parameters: Optional per objective parameters used only only for multi-objective models.
  • lazy_linear_constraints: Optional lazy constraint annotations. Included linear constraints will be marked as "lazy" with supporting solvers, meaning that they will only be added to the working model as-needed as the solver runs. Note that this an algorithmic hint that does not affect the model's feasible region; solvers not supporting these annotations will simply ignore it.
initial_basis: ortools.math_opt.python.solution.Basis | None = None
solution_hints: List[SolutionHint]
branching_priorities: Dict[ortools.math_opt.python.variables.Variable, int]
239    def to_proto(self) -> model_parameters_pb2.ModelSolveParametersProto:
240        """Returns an equivalent protocol buffer."""
241        # TODO(b/236289022): these methods should check that the variables are from
242        # the correct model.
243        result = model_parameters_pb2.ModelSolveParametersProto(
244            variable_values_filter=self.variable_values_filter.to_proto(),
245            dual_values_filter=self.dual_values_filter.to_proto(),
246            quadratic_dual_values_filter=self.quadratic_dual_values_filter.to_proto(),
247            reduced_costs_filter=self.reduced_costs_filter.to_proto(),
248            branching_priorities=sparse_containers.to_sparse_int32_vector_proto(
249                self.branching_priorities
250            ),
251        )
252        if self.initial_basis:
253            result.initial_basis.CopyFrom(self.initial_basis.to_proto())
254        for hint in self.solution_hints:
255            result.solution_hints.append(hint.to_proto())
256        for obj, params in self.objective_parameters.items():
257            if isinstance(obj, objectives.AuxiliaryObjective):
258                result.auxiliary_objective_parameters[obj.id].CopyFrom(
259                    params.to_proto()
260                )
261            else:
262                result.primary_objective_parameters.CopyFrom(params.to_proto())
263        result.lazy_linear_constraint_ids[:] = sorted(
264            con.id for con in self.lazy_linear_constraints
265        )
266        return result

Returns an equivalent protocol buffer.