Skip to content

Variable class

Bases: Term, ABC

Represents a base class for variable terms in an optimization model.

The Variable class is a subclass of Term and serves as a foundation for representing variable terms in optimization models. It is designed to be inherited by subclasses that represent specific types of variables. As an abstract base class (ABC), Variable defines the common behavior and interface for all variable terms.

Source code in pyorlib/algebra/terms/variables/variable.py
class Variable(Term, ABC):
    """
    Represents a base class for variable terms in an optimization model.

    The `Variable` class is a subclass of `Term` and serves as a foundation for representing variable terms in
    optimization models. It is designed to be inherited by subclasses that represent specific types of
    variables. As an abstract base class (ABC), `Variable` defines the common behavior and interface
    for all variable terms.
    """

    def __init__(self, name: str, value_type: ValueType, lower_bound: float = 0, upper_bound: float = inf):
        """
        Initializes a new `Variable` object with the specified attributes.
        :param name: The name of the variable.
        :param value_type: An enumeration representing the type of the variable's value.
        :param lower_bound: The lower bound of the variable. Default is 0.
        :param upper_bound: The upper bound of the variable. Default is infinity.
        """
        # Calls the base init with the term type as Variable.
        super().__init__(term_type=TermType.VARIABLE, value_type=value_type)

        # Applies validations
        if not name:
            raise TermException("Variable terms must have a name.")
        if lower_bound is None or upper_bound is None:
            raise TermException("Variable terms must have lower and upper bounds.")
        if lower_bound >= inf:
            raise TermException("Variable terms lower bounds cannot be +infinity.")
        if upper_bound <= -inf:
            raise TermException("Variable terms upper bounds cannot be -infinity.")
        if lower_bound > upper_bound:
            raise TermException("The lower bound of a variable cannot be greater than the upper bound.")
        if value_type == ValueType.BINARY and (lower_bound != 0 or (upper_bound != 1 and upper_bound != inf)):
            raise TermException("Invalid bounds for a binary variable.")
        if value_type == ValueType.INTEGER and not lower_bound == -inf and not float(lower_bound).is_integer():
            raise TermException("Invalid lower bound for an integer variable term.")
        if value_type == ValueType.INTEGER and not upper_bound == inf and not float(upper_bound).is_integer():
            raise TermException("Invalid upper bound for an integer variable term.")

    def get_pretty_string(self, float_precision: int = 6) -> str:  # pragma: no cover
        default, debug = StdOutColors.DEFAULT, StdOutColors.PURPLE
        return "".join(
            [
                f"Name: {debug}{self.name}{default} | ",
                f"Type: {debug}{self.term_type.name.capitalize()}{default} | ",
                f"Value type: {debug}{self.value_type.name.capitalize()}{default} | ",
                f"Lb:{debug} ",
                "{0:.{prec}g} ".format(self.lower_bound, prec=float_precision),
                f"{default}| Ub:{debug} ",
                "{0:.{prec}g} ".format(self.upper_bound, prec=float_precision),
                f"{default}| Val:{debug} ",
                "{0:.{prec}g} ".format(self.value, prec=float_precision),
                f"{'(N/A) ' if self.value == -0.0 else ''}{default}",
            ]
        )

Attributes

raw abstractmethod property

raw: Any

Returns the raw representation of the mathematical element.

The raw method, when implemented by subclasses, returns the mathematical element in its raw format. The raw format can take various forms, such as an expression used by solvers or engines, or a mathematical expression that represents the entity itself.

RETURNS DESCRIPTION
Any

The raw representation of the mathematical element.

term_type property

term_type: TermType

Retrieves the type of the term.

RETURNS DESCRIPTION
TermType

A TermType enumeration.

value_type property

value_type: ValueType

Retrieves the type of the term's value.

RETURNS DESCRIPTION
ValueType

A ValueType enumeration

name abstractmethod property

name: str

Retrieves the name of the term.

RETURNS DESCRIPTION
str

A string with name of the term.

lower_bound abstractmethod property

lower_bound: float

Retrieves the lower bound of the term's value. For variable terms, the lower bound denotes the minimum value that the term can assume. For constant terms, the lower bound is equivalent to its value.

RETURNS DESCRIPTION
float

A float representing the lower bound of the term's value. If the upper bound is negative infinity, the method returns -inf from the math module.

upper_bound abstractmethod property

upper_bound: float

Retrieves the upper bound of the term's value. For variable terms, the upper bound denotes the maximum value that the term can assume. For constant terms, the upper bound is equivalent to its value.

RETURNS DESCRIPTION
float

A float representing the upper bound of the term's value. If the upper bound is infinity, the method returns inf from the math module.

value abstractmethod property

value: float

Retrieves the value of the term. For variable terms, the value corresponds to the current value of the term. If the term has not been solved yet, the value is -0.0. For constant terms, the value remains the constant value.

RETURNS DESCRIPTION
float

A float representing the value of the term.

is_variable property

is_variable: bool

Determines whether the term is a variable or not.

RETURNS DESCRIPTION
bool

True if the term is a variable, False otherwise.

is_constant property

is_constant: bool

Determines whether the term is a constant or not.

RETURNS DESCRIPTION
bool

True if the term is a constant, False otherwise.

Functions

__add__

__add__(other: Any) -> Element

Addition operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be added.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the addition.

Source code in pyorlib/algebra/element.py
def __add__(self, other: Any) -> "Element":
    """
    Addition operation.
    :param other: The `number` or `Element` instance to be added.
    :return: A new `Element` instance representing the addition.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw + other.raw)
    else:
        return self._build_expression(expression=self.raw + other)

__radd__

__radd__(other: Any) -> Element

Right addition operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be added.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the addition.

Source code in pyorlib/algebra/element.py
def __radd__(self, other: Any) -> "Element":
    """
    Right addition operation.
    :param other: The `number` or `Element` instance to be added.
    :return: A new `Element` instance representing the addition.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw + self.raw)
    else:
        return self._build_expression(expression=other + self.raw)

__iadd__

__iadd__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __iadd__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw + other.raw)
    else:
        return self._build_expression(expression=self.raw + other)

__sub__

__sub__(other: Any) -> Element

Subtraction operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be subtracted.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the subtraction.

Source code in pyorlib/algebra/element.py
def __sub__(self, other: Any) -> "Element":
    """
    Subtraction operation.
    :param other: The `number` or `Element` instance to be subtracted.
    :return: A new `Element` instance representing the subtraction.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw - other.raw)
    else:
        return self._build_expression(expression=self.raw - other)

__rsub__

__rsub__(other: Any) -> Element

Right subtraction operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be subtracted.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the subtraction.

Source code in pyorlib/algebra/element.py
def __rsub__(self, other: Any) -> "Element":
    """
    Right subtraction operation.
    :param other: The `number` or `Element` instance to be subtracted.
    :return: A new `Element` instance representing the subtraction.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw - self.raw)
    else:
        return self._build_expression(expression=other - self.raw)

__isub__

__isub__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __isub__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw - other.raw)
    else:
        return self._build_expression(expression=self.raw - other)

__mul__

__mul__(other: Any) -> Element

Multiplication operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be multiplied.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the multiplication.

Source code in pyorlib/algebra/element.py
def __mul__(self, other: Any) -> "Element":
    """
    Multiplication operation.
    :param other: The `number` or `Element` instance to be multiplied.
    :return: A new `Element` instance representing the multiplication.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw * other.raw)
    else:
        return self._build_expression(expression=self.raw * other)

__rmul__

__rmul__(other: Any) -> Element

Right multiplication operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be multiplied.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the multiplication.

Source code in pyorlib/algebra/element.py
def __rmul__(self, other: Any) -> "Element":
    """
    Right multiplication operation.
    :param other: The `number` or `Element` instance to be multiplied.
    :return: A new `Element` instance representing the multiplication.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw * self.raw)
    else:
        return self._build_expression(expression=other * self.raw)

__imul__

__imul__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __imul__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw * other.raw)
    else:
        return self._build_expression(expression=self.raw * other)

__truediv__

__truediv__(other: Any) -> Element

Division operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be divided.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the division.

Source code in pyorlib/algebra/element.py
def __truediv__(self, other: Any) -> "Element":
    """
    Division operation.
    :param other: The `number` or `Element` instance to be divided.
    :return: A new `Element` instance representing the division.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw / other.raw)
    else:
        return self._build_expression(expression=self.raw / other)

__rtruediv__

__rtruediv__(other: Any) -> Element

Right division operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be divided.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the division.

Source code in pyorlib/algebra/element.py
def __rtruediv__(self, other: Any) -> "Element":
    """
    Right division operation.
    :param other: The `number` or `Element` instance to be divided.
    :return: A new `Element` instance representing the division.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw / self.raw)
    else:
        return self._build_expression(expression=other / self.raw)

__itruediv__

__itruediv__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __itruediv__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw / other.raw)
    else:
        return self._build_expression(expression=self.raw / other)

__floordiv__

__floordiv__(other: Any) -> Element

Floor division operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be floor divided.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the floor division.

Source code in pyorlib/algebra/element.py
def __floordiv__(self, other: Any) -> "Element":
    """
    Floor division operation.
    :param other: The `number` or `Element` instance to be floor divided.
    :return: A new `Element` instance representing the floor division.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw // other.raw)
    else:
        return self._build_expression(expression=self.raw // other)

__rfloordiv__

__rfloordiv__(other: Any) -> Element

Right floor division operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be floor divided.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the floor division.

Source code in pyorlib/algebra/element.py
def __rfloordiv__(self, other: Any) -> "Element":
    """
    Right floor division operation.
    :param other: The `number` or `Element` instance to be floor divided.
    :return: A new `Element` instance representing the floor division.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw // self.raw)
    else:
        return self._build_expression(expression=other // self.raw)

__ifloordiv__

__ifloordiv__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __ifloordiv__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw // other.raw)
    else:
        return self._build_expression(expression=self.raw // other)

__mod__

__mod__(other: Any) -> Element

Modulo operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be used for modulo.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the modulo operation.

Source code in pyorlib/algebra/element.py
def __mod__(self, other: Any) -> "Element":
    """
    Modulo operation.
    :param other: The `number` or `Element` instance to be used for modulo.
    :return: A new `Element` instance representing the modulo operation.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw % other.raw)
    else:
        return self._build_expression(expression=self.raw % other)

__rmod__

__rmod__(other: Any) -> Element

Right modulo operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be used for modulo.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the modulo operation.

Source code in pyorlib/algebra/element.py
def __rmod__(self, other: Any) -> "Element":
    """
    Right modulo operation.
    :param other: The `number` or `Element` instance to be used for modulo.
    :return: A new `Element` instance representing the modulo operation.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw % self.raw)
    else:
        return self._build_expression(expression=other % self.raw)

__imod__

__imod__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __imod__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw % other.raw)
    else:
        return self._build_expression(expression=self.raw % other)

__pow__

__pow__(other: Any) -> Element

Exponentiation operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be used as the exponent.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the exponentiation.

Source code in pyorlib/algebra/element.py
def __pow__(self, other: Any) -> "Element":
    """
    Exponentiation operation.
    :param other: The `number` or `Element` instance to be used as the exponent.
    :return: A new `Element` instance representing the exponentiation.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw**other.raw)
    else:
        return self._build_expression(expression=self.raw**other)

__rpow__

__rpow__(other: Any) -> Element

Right exponentiation operation.

PARAMETER DESCRIPTION
other

The number or Element instance to be used as the base.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the exponentiation.

Source code in pyorlib/algebra/element.py
def __rpow__(self, other: Any) -> "Element":
    """
    Right exponentiation operation.
    :param other: The `number` or `Element` instance to be used as the base.
    :return: A new `Element` instance representing the exponentiation.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=other.raw**self.raw)
    else:
        return self._build_expression(expression=other**self.raw)

__ipow__

__ipow__(other: Any) -> Element
Source code in pyorlib/algebra/terms/term.py
def __ipow__(self, other: Any) -> Element:
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw**other.raw)
    else:
        return self._build_expression(expression=self.raw**other)

__neg__

__neg__() -> Element

Negation operation.

RETURNS DESCRIPTION
Element

A new Element instance representing the negation.

Source code in pyorlib/algebra/element.py
def __neg__(self) -> "Element":
    """
    Negation operation.
    :return: A new `Element` instance representing the negation.
    """
    return self._build_expression(expression=-self.raw)

__pos__

__pos__() -> Element

Positive operation.

RETURNS DESCRIPTION
Element

A new Element instance representing the positive value.

Source code in pyorlib/algebra/element.py
def __pos__(self) -> "Element":
    """
    Positive operation.
    :return: A new `Element` instance representing the positive value.
    """
    return self._build_expression(expression=+self.raw)

__abs__

__abs__() -> Element

Absolute value operation.

RETURNS DESCRIPTION
Element

A new Element instance representing the absolute value.

Source code in pyorlib/algebra/element.py
def __abs__(self) -> "Element":
    """
    Absolute value operation.
    :return: A new `Element` instance representing the absolute value.
    """
    return self._build_expression(expression=abs(self.raw))

__eq__

__eq__(other: Any) -> Element

Equal to comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __eq__(self, other: Any) -> "Element":  # type: ignore[override]
    """
    Equal to comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw == other.raw)
    else:
        return self._build_expression(expression=self.raw == other)

__ne__

__ne__(other: Any) -> Element

Not equal to comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __ne__(self, other: Any) -> "Element":  # type: ignore[override]
    """
    Not equal to comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw != other.raw)
    else:
        return self._build_expression(expression=self.raw != other)

__lt__

__lt__(other: Any) -> Element

Less than comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __lt__(self, other: Any) -> "Element":
    """
    Less than comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw < other.raw)
    else:
        return self._build_expression(expression=self.raw < other)

__le__

__le__(other: Any) -> Element

Less than or equal to comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __le__(self, other: Any) -> "Element":
    """
    Less than or equal to comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw <= other.raw)
    else:
        return self._build_expression(expression=self.raw <= other)

__gt__

__gt__(other: Any) -> Element

Greater than comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __gt__(self, other: Any) -> "Element":
    """
    Greater than comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw > other.raw)
    else:
        return self._build_expression(expression=self.raw > other)

__ge__

__ge__(other: Any) -> Element

Greater than or equal to comparison.

PARAMETER DESCRIPTION
other

The number or Element instance to be compared.

TYPE: Any

RETURNS DESCRIPTION
Element

A new Element instance representing the comparison result.

Source code in pyorlib/algebra/element.py
def __ge__(self, other: Any) -> "Element":
    """
    Greater than or equal to comparison.
    :param other: The `number` or `Element` instance to be compared.
    :return: A new `Element` instance representing the comparison result.
    """
    if isinstance(other, Element):
        return self._build_expression(expression=self.raw >= other.raw)
    else:
        return self._build_expression(expression=self.raw >= other)

__init__

__init__(name: str, value_type: ValueType, lower_bound: float = 0, upper_bound: float = inf)

Initializes a new Variable object with the specified attributes.

PARAMETER DESCRIPTION
name

The name of the variable.

TYPE: str

value_type

An enumeration representing the type of the variable's value.

TYPE: ValueType

lower_bound

The lower bound of the variable. Default is 0.

TYPE: float DEFAULT: 0

upper_bound

The upper bound of the variable. Default is infinity.

TYPE: float DEFAULT: inf

Source code in pyorlib/algebra/terms/variables/variable.py
def __init__(self, name: str, value_type: ValueType, lower_bound: float = 0, upper_bound: float = inf):
    """
    Initializes a new `Variable` object with the specified attributes.
    :param name: The name of the variable.
    :param value_type: An enumeration representing the type of the variable's value.
    :param lower_bound: The lower bound of the variable. Default is 0.
    :param upper_bound: The upper bound of the variable. Default is infinity.
    """
    # Calls the base init with the term type as Variable.
    super().__init__(term_type=TermType.VARIABLE, value_type=value_type)

    # Applies validations
    if not name:
        raise TermException("Variable terms must have a name.")
    if lower_bound is None or upper_bound is None:
        raise TermException("Variable terms must have lower and upper bounds.")
    if lower_bound >= inf:
        raise TermException("Variable terms lower bounds cannot be +infinity.")
    if upper_bound <= -inf:
        raise TermException("Variable terms upper bounds cannot be -infinity.")
    if lower_bound > upper_bound:
        raise TermException("The lower bound of a variable cannot be greater than the upper bound.")
    if value_type == ValueType.BINARY and (lower_bound != 0 or (upper_bound != 1 and upper_bound != inf)):
        raise TermException("Invalid bounds for a binary variable.")
    if value_type == ValueType.INTEGER and not lower_bound == -inf and not float(lower_bound).is_integer():
        raise TermException("Invalid lower bound for an integer variable term.")
    if value_type == ValueType.INTEGER and not upper_bound == inf and not float(upper_bound).is_integer():
        raise TermException("Invalid upper bound for an integer variable term.")

get_pretty_string

get_pretty_string(float_precision: int = 6) -> str
Source code in pyorlib/algebra/terms/variables/variable.py
def get_pretty_string(self, float_precision: int = 6) -> str:  # pragma: no cover
    default, debug = StdOutColors.DEFAULT, StdOutColors.PURPLE
    return "".join(
        [
            f"Name: {debug}{self.name}{default} | ",
            f"Type: {debug}{self.term_type.name.capitalize()}{default} | ",
            f"Value type: {debug}{self.value_type.name.capitalize()}{default} | ",
            f"Lb:{debug} ",
            "{0:.{prec}g} ".format(self.lower_bound, prec=float_precision),
            f"{default}| Ub:{debug} ",
            "{0:.{prec}g} ".format(self.upper_bound, prec=float_precision),
            f"{default}| Val:{debug} ",
            "{0:.{prec}g} ".format(self.value, prec=float_precision),
            f"{'(N/A) ' if self.value == -0.0 else ''}{default}",
        ]
    )