Skip to content

Commit 7cdbbcf

Browse files
Bugfix: Fix Compute Crossing Time (#165)
- Rolled compute_crossing_time() back to linear-search approach since y-values aren't guaranteed to be in sorted order and thus binary search cannot be used to find the first occurence of data above a certain threshold. --------- Co-authored-by: Cen Wang <cenwang@umass.edu>
1 parent f8e69cb commit 7cdbbcf

1 file changed

Lines changed: 9 additions & 18 deletions

File tree

simopt/curve.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ def lookup(self, x_val: float) -> float:
9494
Raises:
9595
TypeError: If x_val is not numeric.
9696
"""
97+
# We can use binary search here since the x-values are sorted.
9798
from bisect import bisect_right
9899

99100
try:
@@ -116,25 +117,15 @@ def compute_crossing_time(self, threshold: float) -> float:
116117
117118
Returns:
118119
float: First time at which the curve drops below the threshold.
119-
120-
Raises:
121-
TypeError: If threshold is not numeric.
122120
"""
123-
from bisect import bisect_right
124-
125-
try:
126-
# Find the first index where y_vals < threshold using binary search
127-
index = bisect_right(self.y_vals, threshold)
128-
129-
# If all y-values are above the threshold, return infinity
130-
if index == self.n_points:
131-
return math.inf
132-
133-
# Return corresponding x-value
134-
return self.x_vals[index]
135-
136-
except TypeError as e:
137-
raise TypeError(f"Threshold must be a numeric value: {e}") from e
121+
# Linear search for the first crossing time
122+
# NOTE: We can't use binary search because the curve's y-values aren't
123+
# guaranteed to be strictly decreasing.
124+
for i in range(self.n_points):
125+
if self.y_vals[i] < threshold:
126+
return self.x_vals[i]
127+
# If threshold is never crossed, return infinity.
128+
return math.inf
138129

139130
def compute_area_under_curve(self) -> float:
140131
"""Compute the area under a curve.

0 commit comments

Comments
 (0)