Skip to content

Fix Spectrum slicing to preserve freq_axis metadata#146

Open
vishwas-droid wants to merge 2 commits intosunpy:mainfrom
vishwas-droid:fix-spectrum-slicing
Open

Fix Spectrum slicing to preserve freq_axis metadata#146
vishwas-droid wants to merge 2 commits intosunpy:mainfrom
vishwas-droid:fix-spectrum-slicing

Conversation

@vishwas-droid
Copy link

@vishwas-droid vishwas-droid commented Feb 11, 2026

This PR fixes an issue where slicing a Spectrum object could result in incorrect
or inconsistent propagation of its associated freq_axis metadata.

Since Spectrum subclasses numpy.ndarray, slicing operations return new views.
Without explicitly handling NumPy subclass mechanics, custom attributes such as
freq_axis may not always be reliably preserved.

Changes

  • Implements __array_finalize__ to properly propagate metadata when new views are created.
  • Overrides __getitem__ to ensure sliced Spectrum objects retain a correctly sliced freq_axis.
  • Adds safe handling for advanced indexing (boolean masks, fancy indexing).
  • Ensures consistent behavior between the data array and its corresponding frequency axis.

Behavior After This PR

  • Standard slicing (spec[2:5])
  • Boolean masking (spec[spec > 5])
  • Fancy indexing (spec[[1, 3, 5]])
  • Arithmetic operations (spec + 5)

All correctly preserve freq_axis.

Backward Compatibility

No breaking changes. Existing tests pass and behavior remains consistent for all supported use cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant