qilisdk.core.model
Classes
A singleton class to generate a slack counter id that increments continuously within the user's active session. |
|
An Enumeration of the Objective sense options. |
|
Represent a symbolic constraint inside a |
|
Represent the scalar objective function optimized by a |
|
Aggregate an objective and constraints into an optimization problem. |
|
Specialized |
Module Contents
- class SlackCounter[fuente]
A singleton class to generate a slack counter id that increments continuously within the user’s active session.
- next() int[fuente]
Return the next counter value and increment the counter.
- reset_counter() None[fuente]
- class ObjectiveSense[fuente]
Bases:
qilisdk.core.types.QiliEnumAn Enumeration of the Objective sense options.
Initialize self. See help(type(self)) for accurate signature.
- MINIMIZE = 'minimize'[fuente]
- MAXIMIZE = 'maximize'[fuente]
- class Constraint(label: str, term: qilisdk.core.variables.ComparisonTerm)[fuente]
Represent a symbolic constraint inside a
Model.Ejemplo
from qilisdk.core.model import Constraint from qilisdk.core.variables import BinaryVariable, LEQ x = BinaryVariable("x") constraint = Constraint("limit", LEQ(x, 1))Build a constraint defined by a comparison term such as
x + y <= 2.- Parámetros:
label (
str) – The constraint’s label.term (
ComparisonTerm) – The comparison term that defines the constraint.
- Muestra:
ValueError – if the term provided is not a ConstraintTerm.
- property label: str[fuente]
Returns: str: The label of the constraint object.
- property term: qilisdk.core.variables.ComparisonTerm[fuente]
Returns: ComparisonTerm: The comparison term of the constraint object.
- variables() list[qilisdk.core.variables.BaseVariable][fuente]
Returns the list of variables in the constraint term.
- Tipo del valor devuelto:
list[BaseVariable]
- Devuelve:
the list of variables in the constraint term.
- Tipo del valor devuelto:
list[BaseVariable]
- property lhs: qilisdk.core.variables.Term[fuente]
Returns: Term: The left hand side of the constraint term.
- property rhs: qilisdk.core.variables.Term[fuente]
Returns: Term: The right hand side of the constraint term.
- property degree: int[fuente]
Returns: int: The degree of the constraint term.
- class Objective(label: str, term: qilisdk.core.variables.BaseVariable | qilisdk.core.variables.Term, sense: ObjectiveSense = ObjectiveSense.MINIMIZE)[fuente]
Represent the scalar objective function optimized by a
Model.Ejemplo
from qilisdk.core.model import Objective, ObjectiveSense from qilisdk.core.variables import BinaryVariable x = BinaryVariable("x") obj = Objective("profit", 3 * x, sense=ObjectiveSense.MAXIMIZE)Build a new objective function.
- Parámetros:
label (
str) – Objective label.term (
BaseVariable | Term) – Expression to minimize or maximize.sense (
ObjectiveSense, optional) – Optimization sense. Defaults toObjectiveSense.MINIMIZE.
- Muestra:
ValueError – if the term provided is not a Term Object.
ValueError – if the optimization sense provided is not one that is defined by the ObjectiveSense Enum.
- property label: str[fuente]
Returns: str: the label of the objective.
- property term: qilisdk.core.variables.Term[fuente]
Returns: Term: the objective term.
- property sense: ObjectiveSense[fuente]
Returns: ObjectiveSense: the objective optimization sense.
- variables() list[qilisdk.core.variables.BaseVariable][fuente]
Gathers a list of all the variables in the objective term.
- Devuelve:
the list of variables in the objective term.
- Tipo del valor devuelto:
list[BaseVariable]
- class Model(label: str)[fuente]
Aggregate an objective and constraints into an optimization problem.
Ejemplo
from qilisdk.core import BinaryVariable, LEQ, Model num_items = 4 values = [1, 3, 5, 2] weights = [3, 2, 4, 5] max_weight = 6 bin_vars = [BinaryVariable(f"b{i}") for i in range(num_items)] model = Model("Knapsack") objective = sum(values[i] * bin_vars[i] for i in range(num_items)) model.set_objective(objective) constraint = LEQ(sum(weights[i] * bin_vars[i] for i in range(num_items)), max_weight) model.add_constraint("maximum weight", constraint) print(model)- Parámetros:
label (
str) – Model label.
- property lagrange_multipliers: dict[str, float][fuente]
- set_lagrange_multiplier(constraint_label: str, lagrange_multiplier: float) None[fuente]
Sets the lagrange multiplier value for a given constraint.
- Parámetros:
constraint_label (
str) – the constraint to which the lagrange multiplier value corresponds.lagrange_multiplier (
float) – the lagrange multiplier value.
- Muestra:
ValueError – if the constraint provided is not in the model.
- property label: str[fuente]
Returns: str: The model label.
- property constraints: list[Constraint][fuente]
Returns: list[Constraint]: a list of all the constraints in the model.
- property encoding_constraints: list[Constraint][fuente]
Returns: list[Constraint]: a list of all variable encoding constraints in the model.
- variables() list[qilisdk.core.variables.BaseVariable][fuente]
- Devuelve:
a list of variables that are used in the model whether that is in the constraints or the objective.
- Tipo del valor devuelto:
list[BaseVariable]
- add_constraint(label: str, term: qilisdk.core.variables.ComparisonTerm, lagrange_multiplier: float = 100) None[fuente]
Add a constraint to the model.
- Parámetros:
label (
str) – constraint label.term (
ComparisonTerm) – The constraint’s comparison term.
- Muestra:
ValueError – if the constraint label is already used in the model.
- set_objective(term: qilisdk.core.variables.Term, label: str = 'obj', sense: ObjectiveSense = ObjectiveSense.MINIMIZE) None[fuente]
Sets the model’s objective.
- Parámetros:
term (
Term) – the objective term.label (
str, optional) – the objective’s label. Defaults to «obj».sense (
ObjectiveSense, optional) – The optimization sense of the model’s objective. Defaults to ObjectiveSense.MINIMIZE.
- evaluate(sample: Mapping[qilisdk.core.variables.BaseVariable, qilisdk.core.variables.RealNumber | list[int]]) dict[str, qilisdk.core.variables.Number][fuente]
Evaluates the objective and the constraints of the model given a set of values for the variables.
- Parámetros:
sample (
Mapping[BaseVariable,Number | list[int]]) – The dictionary maps the variable to the value to be used during the evaluation. In case the variable is continuous (Not Binary or Spin) then the value could either be a number or a list of binary bits that correspond to the encoding of the variable. Note: All the model’s variables must be provided for the model to be evaluated.- Devuelve:
- a dictionary that maps the name of the objective/constraint to it’s evaluated value.
Note: For constraints, the value is equal to lagrange multiplier of that constraint if the constraint is not satisfied or 0 otherwise.
- Tipo del valor devuelto:
dict[str, float]
- to_qubo(lagrange_multiplier_dict: dict[str, float] | None = None, penalization: Literal['unbalanced', 'slack'] = 'slack', parameters: list[float] | None = None, linearize: bool = True, linearization_lagrange_multiplier: float = 100) QUBO[fuente]
Export the model to a qubo model.
When
linearizeisTrue, any pseudo-Boolean monomial of degree greater than two, coming either from the objective or from the squared/slack penalty of a constraint, is automatically rewritten to quadratic form by introducing auxiliary binary variables and corresponding Rosenberg penalty constraints. SeeQUBO.from_model()for details on the reduction scheme.- Parámetros:
lagrange_multiplier_dict (
dict[str,float] | None, optional) – A dictionary with lagrange multiplier values to scale the model’s constraints. Defaults to None.penalization (
Literal["unbalanced","slack"], optional) – the penalization used to handle inequality constraints. Defaults to «slack».parameters (
list[float] | None, optional) – the parameters used for the unbalanced penalization method. Defaults to None.linearize (
bool, optional) – Automatically reduce high-degree pseudo-Boolean monomials to quadratic form by introducing auxiliary binary variables. WhenFalse, exporting a model whose objective or constraints contain terms of degree three or higher raises aValueError. Defaults toTrue.linearization_lagrange_multiplier (
float, optional) – The Lagrange multiplier applied to each Rosenberg penalty constraint added during linearization. Defaults to 100.
- Devuelve:
A QUBO model that is generated from the model object.
- Tipo del valor devuelto:
- class QUBO(label: str)[fuente]
Bases:
ModelSpecialized
Modelconstrained to Quadratic Unconstrained Binary Optimization form.Ejemplo
from qilisdk.core.model import QUBO from qilisdk.core.variables import BinaryVariable x0, x1 = BinaryVariable("x0"), BinaryVariable("x1") qubo = QUBO("Example") qubo.set_objective((x0 + x1) ** 2)- Parámetros:
label (
str) – QUBO model label.
- continuous_vars: dict[str, qilisdk.core.variables.Variable][fuente]
- property qubo_objective: Objective | None[fuente]
Returns: Objective | None: The QUBO objective (factoring in the constraints and objective of the model). If the objective and constraints are not defined in the model, this property returns None.
- add_constraint(label: str, term: qilisdk.core.variables.ComparisonTerm, lagrange_multiplier: float = 100, penalization: Literal['unbalanced', 'slack'] = 'slack', parameters: list[float] | None = None, transform_to_qubo: bool = True, linearize: bool = True) None[fuente]
Adds a constraint to the QUBO model.
- Parámetros:
label (
str) – the constraint label.term (
ComparisonTerm) – the constraint’s comparison term.lagrange_multiplier (
float, optional) – the lagrange multiplier used to scale this constraint. Defaults to 100.penalization (
Literal["unbalanced","slack"], optional) – the penalization used to handel inequality constraints. Defaults to «slack».parameters (
list[float] | None, optional) – the parameters used for the unbalanced penalization method. Defaults to None.transform_to_qubo (
bool, optional) – Automatically transform a given constraint to QUBO format. Defaults to True.linearize (
bool, optional) – linearize the constraints if they are above degree 2.
- Muestra:
ValueError – if constraint label already exists in the model.
ValueError – if a penalization method is provided that is not ("unbalanced", "slack")
ValueError – if unbalanced penalization method is used and not enough parameters are provided.
ValueError – if the degree of the provided term is larger than 2.
ValueError – if the constraint term contains variables that are not from Positive Integers or Binary domains.
ValueError – if the constraint term contains variable that do not have 0 as their lower bound.
- set_objective(term: qilisdk.core.variables.Term, label: str = 'obj', sense: ObjectiveSense = ObjectiveSense.MINIMIZE) None[fuente]
Set the QUBO objective.
If a
_Linearizerhas been attached to this QUBO instance (viafrom_model()withlinearize=True), the binary-encoded objective is additionally rewritten so that every monomial has degree at most two. Auxiliary variables introduced by the rewrite are registered on the linearizer.- Parámetros:
term (
Term) – The objective’s term.label (
str, optional) – the objective’s label. Defaults to «obj».sense (
ObjectiveSense, optional) – The optimization sense of the model’s objective. Defaults to ObjectiveSense.MINIMIZE.
- Muestra:
ValueError – if the degree of the provided term is larger than 2.
- evaluate(sample: Mapping[qilisdk.core.variables.BaseVariable, qilisdk.core.variables.RealNumber | list[int]]) dict[str, qilisdk.core.variables.Number][fuente]
Evaluates the objective and the constraints of the model given a set of values for the variables.
- Parámetros:
sample (
Mapping[BaseVariable,RealNumber | list[int]]) – The dictionary maps the variable to the value to be used during the evaluation. In case the variable is continuous (Not Binary or Spin) then the value could either be a number or a list of binary bits that correspond to the encoding of the variable. Note: All the model’s variables must be provided for the model to be evaluated.- Devuelve:
- a dictionary that maps the name of the objective/constraint to it’s evaluated value.
Note: For constraints, the value is equal to the value of the evaluated constraint term multiplied by the lagrange multiplier of that constraint.
- Tipo del valor devuelto:
dict[str, float]
- classmethod from_model(model: Model, lagrange_multiplier_dict: dict[str, float] | None = None, penalization: Literal['unbalanced', 'slack'] = 'slack', parameters: list[float] | None = None, linearize: bool = True, linearization_lagrange_multiplier: float = 100) QUBO[fuente]
A class method that constructs a QUBO model from a regular model if possible.
When
linearizeisTrue(default), any pseudo-Boolean monomial of degree greater than two that appears in the objective or in a transformed constraint penalty is rewritten using auxiliary binary variables via the Rosenberg penalty\[P(a, b, w) = a \cdot b - 2 \cdot a \cdot w - 2 \cdot b \cdot w + 3 \cdot w,\]so
wis forced to equal the producta * bat the optimum. One such penalty is added as an equality QUBO constraint for every unique pair substitution. Settinglinearize=Falserestores the previous behaviour, where aValueErroris raised if the model contains terms of degree three or higher.- Parámetros:
model (
Model) – the model to be used to construct the QUBO model.lagrange_multiplier_dict (
dict[str,float] | None, optional) – A dictionary with lagrange multiplier values to scale the model’s constraints. Defaults to None.penalization (
Literal["unbalanced","slack"], optional) – the penalization used to handel inequality constraints. Defaults to «slack».parameters (
list[float] | None, optional) – the parameters used for the unbalanced penalization method. Defaults to None.linearize (
bool, optional) – Automatically reduce high-degree pseudo-Boolean monomials to quadratic form by introducing auxiliary binary variables. Defaults toTrue.linearization_lagrange_multiplier (
float, optional) – The Lagrange multiplier applied to each Rosenberg penalty constraint added as part of the linearization. Must be large enough to dominate any incentive to violate the auxiliary equalitiesw = a * b. Defaults to 100.
- Devuelve:
a QUBO model equivalent to the input model, with any high-degree terms rewritten via auxiliary binary variables when
linearizeis enabled.- Tipo del valor devuelto:
- to_hamiltonian() qilisdk.analog.hamiltonian.Hamiltonian[fuente]
Construct an ising hamiltonian from the current QUBO model.
- Muestra:
ValueError – if the QUBO model is empty (doesn’t have an objective nor constraints.)
ValueError – if the QUBO model uses operations that are not addition or multiplications.
- Devuelve:
An ising hamiltonian that represents the QUBO model.
- Tipo del valor devuelto:
- to_qubo(lagrange_multiplier_dict: dict[str, float] | None = None, penalization: Literal['unbalanced', 'slack'] = 'slack', parameters: list[float] | None = None, linearize: bool = True, linearization_lagrange_multiplier: float = 100) QUBO[fuente]
Return a copy of this QUBO model.
QUBO models are already in quadratic form, so the linearization arguments are accepted for signature compatibility with
Model.to_qubo()but have no effect. A warning is emitted noting that no conversion was performed.