Skip to content

Commit

Permalink
Adding public API to get the number of pieces in a piecewise linear f…
Browse files Browse the repository at this point in the history
…unction
  • Loading branch information
emma58 committed Aug 7, 2024
1 parent b480497 commit a083740
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pyomo/contrib/piecewise/piecewise_linear_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ def __init__(self, component=None):
self._points = []
self._linear_functions = []

@property
def num_pieces(self):
"""
Returns the number of domain-linear function pairs that define this piecewise-
linear function. Note that it is possible for contiguous domains to have the
same function, and in that case they will each be counted by this metric.
"""
return len(self._linear_functions)

def __call__(self, *args):
"""
Returns a PiecewiseLinearExpression which is an instance of this
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ def check_ln_x_approx(self, pw, x):
places=7,
)

self.assertEqual(pw.num_pieces, 3)

def check_x_squared_approx(self, pw, x):
self.assertEqual(len(pw._simplices), 3)
self.assertEqual(len(pw._linear_functions), 3)
Expand All @@ -93,6 +95,8 @@ def check_x_squared_approx(self, pw, x):
self, pw._linear_functions[2](x), 16 * x - 60, places=7
)

self.assertEqual(pw.num_pieces, 3)

def test_pw_linear_approx_of_ln_x_simplices(self):
m = self.make_ln_x_model()
simplices = [(1, 3), (3, 6), (6, 10)]
Expand Down

0 comments on commit a083740

Please sign in to comment.