diff --git a/pyomo/contrib/piecewise/piecewise_linear_function.py b/pyomo/contrib/piecewise/piecewise_linear_function.py index e92edacc756..1c2b065d39f 100644 --- a/pyomo/contrib/piecewise/piecewise_linear_function.py +++ b/pyomo/contrib/piecewise/piecewise_linear_function.py @@ -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 diff --git a/pyomo/contrib/piecewise/tests/test_piecewise_linear_function.py b/pyomo/contrib/piecewise/tests/test_piecewise_linear_function.py index 571601fefbc..a30b82efeb4 100644 --- a/pyomo/contrib/piecewise/tests/test_piecewise_linear_function.py +++ b/pyomo/contrib/piecewise/tests/test_piecewise_linear_function.py @@ -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) @@ -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)]