Skip to content

Commit 5000725

Browse files
committed
Enhance find_x_at_value and fwhm_info functions with improved error handling and documentation
1 parent 49463b4 commit 5000725

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

cdl/algorithms/signal.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -549,14 +549,16 @@ def find_x_at_value(x: np.ndarray, y: np.ndarray, value: float) -> np.ndarray:
549549
value: Value to find
550550
551551
Returns:
552-
X value where the Y value is the closest to the given value
552+
An array of x values where the y value is the closest to the given value
553+
(empty array if no zero crossing is found)
553554
"""
554555
leveled_y = y - value
555556
xi_before = find_nearest_zero_point_idx(leveled_y)
556557
xi_after = xi_before + 1
557558

558559
if len(xi_before) == 0:
559-
return np.array([0.0])
560+
# Return an empty array if no zero crossing is found
561+
return np.array([])
560562

561563
# linear interpolation
562564
p = (leveled_y[xi_after] - leveled_y[xi_before]) / (x[xi_after] - x[xi_before])
@@ -565,7 +567,9 @@ def find_x_at_value(x: np.ndarray, y: np.ndarray, value: float) -> np.ndarray:
565567
return x0
566568

567569

568-
def bandwidth(data: np.ndarray, level: float = 3.0) -> float:
570+
def bandwidth(
571+
data: np.ndarray, level: float = 3.0
572+
) -> tuple[float, float, float, float]:
569573
"""Compute the bandwidth of the signal at a given level.
570574
571575
Args:
@@ -867,8 +871,10 @@ def fwhm(
867871
if method == "zero-crossing":
868872
hmax = dy * 0.5 + np.min(y)
869873
fx = find_x_at_value(x, y, hmax)
870-
if fx.size != 2:
874+
if fx.size > 2:
871875
warnings.warn(f"Ambiguous zero-crossing points (found {fx.size} points)")
876+
elif fx.size < 2:
877+
raise ValueError("No zero-crossing points found")
872878
return fx[0], hmax, fx[-1], hmax
873879

874880
try:

cdl/core/gui/docks.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,12 @@
6464

6565
def fwhm_info(x, y):
6666
"""Return FWHM information string"""
67-
with warnings.catch_warnings(record=True) as w:
68-
x0, _y0, x1, _y1 = fwhm((x, y), "zero-crossing")
69-
wstr = " ⚠️" if w else ""
67+
try:
68+
with warnings.catch_warnings(record=True) as w:
69+
x0, _y0, x1, _y1 = fwhm((x, y), "zero-crossing")
70+
wstr = " ⚠️" if w else ""
71+
except ValueError:
72+
return "🛑"
7073
return f"{x1 - x0:g}{wstr}"
7174

7275

0 commit comments

Comments
 (0)