From 6b839d86bb74e90ba6995095e275974fc63a3b68 Mon Sep 17 00:00:00 2001 From: Robbie Muir Date: Sat, 1 Nov 2025 23:52:55 +0100 Subject: [PATCH 1/2] add linear expression from constant --- linopy/expressions.py | 20 ++++++++++++++++++++ test/test_linear_expression.py | 15 +++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/linopy/expressions.py b/linopy/expressions.py index d60c8be5..b480e8a4 100644 --- a/linopy/expressions.py +++ b/linopy/expressions.py @@ -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): """ diff --git a/test/test_linear_expression.py b/test/test_linear_expression.py index 2551c203..01c46252 100644 --- a/test/test_linear_expression.py +++ b/test/test_linear_expression.py @@ -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) From 7626b5975edd2c8e5dc850a8b244ee2e721d784d Mon Sep 17 00:00:00 2001 From: Robbie Muir Date: Sat, 1 Nov 2025 23:54:19 +0100 Subject: [PATCH 2/2] add doc --- doc/release_notes.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/release_notes.rst b/doc/release_notes.rst index 76e5bf24..99847409 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -2,7 +2,7 @@ Release Notes ============= .. Upcoming Version - +* Add convenience function to create LinearExpression from constant Version 0.5.8 --------------