Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/release_notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Release Notes
=============

.. Upcoming Version

* Add convenience function to create LinearExpression from constant

Version 0.5.8
--------------
Expand Down
20 changes: 20 additions & 0 deletions linopy/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,26 @@ def process_one(

return merge(exprs, cls=cls) if len(exprs) > 1 else exprs[0]

@classmethod
def from_constant(cls, model: Model, constant: ConstantLike) -> LinearExpression:
"""
Create a linear expression from a constant value or series

Parameters
----------
model : linopy.Model
The model to which the constant expression will belong.
constant : int/float/array_like
The constant value for the linear expression.

Returns
-------
linopy.LinearExpression
A linear expression representing the constant value.
"""
const_da = as_dataarray(constant)
return LinearExpression(const_da, model)


class QuadraticExpression(BaseExpression):
"""
Expand Down
15 changes: 15 additions & 0 deletions test/test_linear_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,21 @@ def test_linear_expression_from_tuples_bad_calls(
LinearExpression.from_tuples(10)


def test_linear_expression_from_constant_scalar(m: Model) -> None:
expr = LinearExpression.from_constant(model=m, constant=10)
assert isinstance(expr, LinearExpression)
assert (expr.const == 10).all()


def test_linear_expression_from_constant_array(m: Model) -> None:
arr = pd.Series(index=pd.Index([0, 1], name="t"), data=[10, 20])
expr = LinearExpression.from_constant(model=m, constant=arr)
assert isinstance(expr, LinearExpression)
assert list(expr.coords.keys())[0] == "t"
assert expr.nterm == 0
assert (expr.const.values == [10, 20]).all()


def test_linear_expression_sanitize(x: Variable, y: Variable, z: Variable) -> None:
expr = 10 * x + y + z
assert isinstance(expr.sanitize(), LinearExpression)
Expand Down
Loading