Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid zero division #67

Merged
merged 1 commit into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/ibex_bluesky_core/callbacks/fitting/fitting_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,14 +332,17 @@ def guess(
# Guessing. gradient of linear-slope part of function
dy = np.gradient(y) # Return array of differences in y
max_dy = np.max(dy) # Return max y difference, this will always be on the upwards slope
dx = x[1] - x[0] # Find x step
dx = abs(x[1] - x[0]) # Find x step
gradient = max_dy / dx

d2y = np.diff(dy) # Double differentiate y to find how gradients change
inflection0 = x[np.argmax(d2y)] # Where there is positive gradient change

background = min(y) # The lowest y value is the background
inflections_diff = -(background - y[np.argmax(y)]) / gradient
if gradient != 0.0:
inflections_diff = -(background - y[np.argmax(y)]) / gradient
else:
inflections_diff = dx # Fallback case, guess one x step
# As linear, using y - y1 = m(x - x1) -> x = (y - y1) / gradient - x1

# The highest y value + slightly more to account for further convergence
Expand Down
7 changes: 7 additions & 0 deletions tests/callbacks/fitting/test_fitting_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,13 @@ def test_guess_inflections_diff(self):

assert 3.0 == pytest.approx(outp["inflections_diff"].value, rel=1e-2)

def test_guess_inflections_diff_with_all_zero_data(self):
x = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
outp = SlitScan.guess()(x, y)

assert 1.0 == pytest.approx(outp["inflections_diff"].value, rel=1e-2)

def test_guess_height_above_inflection1(self):
x = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.0, 1.0, 2.0, 3.0, 4.0, 4.0])
Expand Down
Loading