Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Created October 10, 2016 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasaarholt/0d1973fec96d05ed2bd9e8030c905fb5 to your computer and use it in GitHub Desktop.
Save thomasaarholt/0d1973fec96d05ed2bd9e8030c905fb5 to your computer and use it in GitHub Desktop.
Binning function for hyperspy signals
def mybin(s, xbin=1, ybin=1, sbin=1):
"""Return spectrum s binned by factors xbin, ybin, sbin"""
if (xbin < 1) or (ybin < 1) or (sbin < 1):
raise ValueError("One of your binnings is smaller than 1. For signal axis to remain constant, leave as 1")
if all(n==1 for n in (xbin, ybin, sbin)):
print("Not binning because all binnings == 1")
return s # End Early
# Get signal channels
signal_channels = s.axes_manager.signal_shape[0]
# Make sure signal channel length is a multiple of two
if signal_channels % 2 != 0:
#print("Signal axis length is odd-numbered! Cropping spectrum by 1 signal channel!")
s = s.isig[0:-1]
signal_channels = s.axes_manager.signal_shape[0]
# Check if image is a single spectrum:
try:
s.axes_manager.navigation_shape[0]
except IndexError:
# This is a 0D Single Spectrum, don't bin X or Y
single_spectrum = True
else:
single_spectrum = False
nav_x_channels = s.axes_manager.navigation_shape[0]
if single_spectrum:
print("Binning " + s.metadata.General.title + " by ( | " + str(sbin) + ").")
s = s.rebin((signal_channels/sbin,))
print("New shape: " + str(s.data.shape))
return s
# Make sure nav X pixel length is a multiple of two
if nav_x_channels % 2 != 0:
#print("x-axis length is odd-numbered! Cropping spectrum by 1 signal channel!")
s = s.inav[:-1,:]
nav_x_channels = s.axes_manager.navigation_shape[0]
# Check if image is a Line profile:
try:
s.axes_manager.navigation_shape[1]
except IndexError:
#This is a 1D Line profile, don't bin the Y axis
line_profile = True
else:
# This is a 2D Spectrum Image Map
line_profile = False
nav_y_channels = s.axes_manager.navigation_shape[1]
if not line_profile:
if nav_y_channels % 2 != 0:
#print("x-axis length is odd-numbered! Cropping spectrum by 1 signal channel!")
s = s.inav[:,:-1]
nav_y_channels = s.axes_manager.navigation_shape[1]
if line_profile:
print("Binning " + s.metadata.General.title + " by (" + str(xbin) + " | " + str(sbin) + ").")
s = s.rebin((nav_x_channels/xbin, signal_channels/sbin))
print("New shape: " + str(s.data.shape))
else:
print("Binning " + s.metadata.General.title + " by (" + str(xbin) + ", " + str(ybin) + " | " + str(sbin) + ").")
s = s.rebin((nav_x_channels/xbin, nav_y_channels/ybin, signal_channels/sbin))
print("New shape: " + str(s.data.shape))
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment