Skip to content

Commit 6b839d8

Browse files
author
Robbie Muir
committed
add linear expression from constant
1 parent 6d1302e commit 6b839d8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

linopy/expressions.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1647,6 +1647,26 @@ def process_one(
16471647

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

1650+
@classmethod
1651+
def from_constant(cls, model: Model, constant: ConstantLike) -> LinearExpression:
1652+
"""
1653+
Create a linear expression from a constant value or series
1654+
1655+
Parameters
1656+
----------
1657+
model : linopy.Model
1658+
The model to which the constant expression will belong.
1659+
constant : int/float/array_like
1660+
The constant value for the linear expression.
1661+
1662+
Returns
1663+
-------
1664+
linopy.LinearExpression
1665+
A linear expression representing the constant value.
1666+
"""
1667+
const_da = as_dataarray(constant)
1668+
return LinearExpression(const_da, model)
1669+
16501670

16511671
class QuadraticExpression(BaseExpression):
16521672
"""

test/test_linear_expression.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,21 @@ def test_linear_expression_from_tuples_bad_calls(
11231123
LinearExpression.from_tuples(10)
11241124

11251125

1126+
def test_linear_expression_from_constant_scalar(m: Model) -> None:
1127+
expr = LinearExpression.from_constant(model=m, constant=10)
1128+
assert isinstance(expr, LinearExpression)
1129+
assert (expr.const == 10).all()
1130+
1131+
1132+
def test_linear_expression_from_constant_array(m: Model) -> None:
1133+
arr = pd.Series(index=pd.Index([0, 1], name="t"), data=[10, 20])
1134+
expr = LinearExpression.from_constant(model=m, constant=arr)
1135+
assert isinstance(expr, LinearExpression)
1136+
assert list(expr.coords.keys())[0] == "t"
1137+
assert expr.nterm == 0
1138+
assert (expr.const.values == [10, 20]).all()
1139+
1140+
11261141
def test_linear_expression_sanitize(x: Variable, y: Variable, z: Variable) -> None:
11271142
expr = 10 * x + y + z
11281143
assert isinstance(expr.sanitize(), LinearExpression)

0 commit comments

Comments
 (0)