Time-to-Empty from a Discharge Curve (Piecewise Linear Interpolation)
Implement a function time_to_empty(checkpoints, current_soc) that returns the number of minutes until the battery's state of charge (SOC) reaches 0. Use piecewise linear interpolation on a discharge curve built from time-stamped SOC measurements.
Inputs
-
checkpoints: a list of (t_min, soc_percent) tuples sorted by time (ascending). All points are from a single session.
-
current_soc: the current SOC percentage in [0, 100].
Rules and Edge Cases
-
Discharge-only assumption: SOC is nonincreasing during discharge.
-
Skip any charging segments (i.e., where SOC increases).
-
Handle duplicate SOC levels (flat segments) by collapsing them into a single point.
-
Interpolation and extrapolation:
-
If there is no exact soc = 0 point in the data, linearly extrapolate using the last valid decreasing segment.
-
If current_soc falls between two SOC levels, interpolate within the bracketing segment.
-
If current_soc falls outside the observed SOC range after cleaning (above the max or below the min), extrapolate using the first/last valid decreasing segment, respectively.
-
Performance: O(n) time and O(1) extra space after sorting.
Output
-
Minutes (float) until SOC reaches 0 from current_soc.
Tests to Satisfy
-
checkpoints = [(0, 100), (60, 50), (120, 0)], current_soc = 25 → expected 30 minutes.
Explain
-
Explain how your function maintains monotonicity of the estimated remaining time with respect to current_soc and why it is numerically stable.