Skip to content

Commit cdfab7a

Browse files
Fix PPF addition with equal slopes
Sort PPF elements by slope with a key function so equal-slope components do not require comparing curve objects. Add regression tests for two and three same-slope PPFs.
1 parent cf5ce62 commit cdfab7a

2 files changed

Lines changed: 28 additions & 3 deletions

File tree

freeride/curves.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ def ppf_sum(*curves, comparative_advantage=True):
5454
aggregate frontier.
5555
"""
5656

57-
slope_and_curves = sorted(
58-
[(s.slope, s) for s in curves],
57+
curves = sorted(
58+
curves,
59+
key=lambda s: s.slope,
5960
reverse=comparative_advantage,
6061
)
61-
curves = [t[1] for t in slope_and_curves]
6262
x_intercepts = [c.q_intercept for c in curves]
6363
y_intercepts = [c.intercept for c in curves]
6464

tests/test_curves.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,31 @@ def test_commutative_add(self):
236236
p2 = PPF(5, -0.5)
237237
self.assertAlmostEqual((p1 + p2)(7), (p2 + p1)(7))
238238

239+
def test_addition_with_equal_slopes(self):
240+
"""Test PPF addition when both curves have the same slope."""
241+
ppf1 = PPF.from_formula('x = 10 - y')
242+
ppf2 = PPF.from_formula('x = 8 - y')
243+
# Both have slope -1, which previously caused a TypeError
244+
joint = ppf1 + ppf2
245+
self.assertIsInstance(joint, PPF)
246+
# The combined PPF should have x-intercept of 18 (10 + 8)
247+
self.assertAlmostEqual(joint(0), 18.0)
248+
# At x=10, we should have y=8 (using the second PPF segment)
249+
self.assertAlmostEqual(joint(10), 8.0)
250+
# At x=18, we should have y=0
251+
self.assertAlmostEqual(joint(18), 0.0)
252+
253+
def test_addition_multiple_equal_slopes(self):
254+
"""Test PPF addition with more than two curves with equal slopes."""
255+
ppf1 = PPF(10, -1)
256+
ppf2 = PPF(8, -1)
257+
ppf3 = PPF(6, -1)
258+
joint = ppf1 + ppf2 + ppf3
259+
self.assertIsInstance(joint, PPF)
260+
# Combined x-intercept should be 10 + 8 + 6 = 24
261+
self.assertAlmostEqual(joint(0), 24.0)
262+
self.assertAlmostEqual(joint(24), 0.0)
263+
239264

240265
class TestBaseQuadraticRegression(unittest.TestCase):
241266

0 commit comments

Comments
 (0)