Skip to content

Commit

Permalink
Update math for higher orders as well - cancels out for constant bin …
Browse files Browse the repository at this point in the history
…width
  • Loading branch information
rosteen committed May 28, 2024
1 parent 93ea26c commit 9b095f2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
14 changes: 7 additions & 7 deletions specutils/analysis/moment.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,25 +64,25 @@ def _compute_moment(spectrum, regions=None, order=0, axis=-1):
if order is None or order < 0:
return None

dx = np.abs(np.diff(spectral_axis.bin_edges))
m0 = np.sum(flux * dx, axis=axis)
if order == 0:
dx = np.abs(np.diff(spectral_axis.bin_edges))
return np.sum(flux * dx, axis=axis)
return m0

dispersion = spectral_axis
if len(flux.shape) > len(spectral_axis.shape):
_shape = flux.shape[:-1] + (1,)
dispersion = np.tile(spectral_axis, _shape)

if order == 1:
return np.sum(flux * dispersion, axis=axis) / np.sum(flux, axis=axis)
return np.sum(flux * dispersion * dx, axis=axis) / m0

if order > 1:
m0 = np.sum(flux, axis=axis)

# By setting keepdims to True, the axes which are reduced are
# left in the result as dimensions with size one. This means
# that we can broadcast m1 correctly against dispersion.
m1 = (np.sum(flux * spectral_axis, axis=axis, keepdims=True)
/ np.sum(flux, axis=axis, keepdims=True))
m1 = (np.sum(flux * dispersion * dx, axis=axis, keepdims=True)
/ np.sum(flux * dx, axis=axis, keepdims=True))

return np.sum(flux * (dispersion - m1) ** order, axis=axis) / m0
return np.sum(flux * dx * (dispersion - m1) ** order, axis=axis) / m0
4 changes: 2 additions & 2 deletions specutils/tests/test_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,8 +1164,8 @@ def test_moment_cube_order_2():
assert moment_2.shape == (10, 10000)
assert moment_2.unit.is_equivalent(u.GHz**2)
# check assorted values.
assert quantity_allclose(moment_2[0][0], 2.019e-28*u.GHz**2, rtol=0.01)
assert quantity_allclose(moment_2[1][0], 2.019e-28*u.GHz**2, rtol=0.01)
assert quantity_allclose(moment_2[0][0], 8.078e-28*u.GHz**2, rtol=0.01)
assert quantity_allclose(moment_2[1][0], 8.078e-28*u.GHz**2, rtol=0.01)
assert quantity_allclose(moment_2[0][3], 2.019e-28*u.GHz**2, rtol=0.01)


Expand Down

0 comments on commit 9b095f2

Please sign in to comment.