@@ -330,7 +330,7 @@ def bkg_image(self, image=None):
330330 (image .shape [0 ], 1 )) * image .unit ,
331331 spectral_axis = image .spectral_axis )
332332
333- def bkg_spectrum (self , image = None ):
333+ def bkg_spectrum (self , image = None , bkg_statistic = "sum" ):
334334 """
335335 Expose the 1D spectrum of the background.
336336
@@ -341,6 +341,13 @@ def bkg_spectrum(self, image=None):
341341 (spatial) direction is axis 0 and dispersion (wavelength)
342342 direction is axis 1. If None, will extract the background
343343 from ``image`` used to initialize the class. [default: None]
344+ bkg_statistic : {'average', 'median', 'sum'}, optional
345+ Statistical method used to collapse the background image. [default: ``'sum'``]
346+ Supported values are:
347+
348+ - ``'average'`` : Uses the mean (`numpy.nanmean`).
349+ - ``'median'`` : Uses the median (`numpy.nanmedian`).
350+ - ``'sum'`` : Uses the sum (`numpy.nansum`).
344351
345352 Returns
346353 -------
@@ -351,12 +358,22 @@ def bkg_spectrum(self, image=None):
351358 """
352359 bkg_image = self .bkg_image (image )
353360
361+ if bkg_statistic == 'sum' :
362+ statistic_function = np .nansum
363+ elif bkg_statistic == 'median' :
364+ statistic_function = np .nanmedian
365+ elif bkg_statistic == 'average' :
366+ statistic_function = np .nanmean
367+ else :
368+ raise ValueError (f"Background statistic { bkg_statistic } is not supported. "
369+ "Please choose from: average, median, or sum." )
370+
354371 try :
355- return bkg_image .collapse (np . nansum , axis = self .crossdisp_axis )
372+ return bkg_image .collapse (statistic_function , axis = self .crossdisp_axis )
356373 except u .UnitTypeError :
357374 # can't collapse with a spectral axis in pixels because
358375 # SpectralCoord only allows frequency/wavelength equivalent units...
359- ext1d = np . nansum (bkg_image .flux , axis = self .crossdisp_axis )
376+ ext1d = statistic_function (bkg_image .flux , axis = self .crossdisp_axis )
360377 return Spectrum1D (ext1d , bkg_image .spectral_axis )
361378
362379 def sub_image (self , image = None ):
0 commit comments