Coverage for spectractor/extractor/background.py: 9%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import numpy as np
2import matplotlib.pyplot as plt
3import matplotlib.gridspec as gridspec
4from matplotlib import cm
5import os
6import copy
8from spectractor import parameters
9from spectractor.tools import fit_poly1d_outlier_removal, fit_poly2d_outlier_removal, plot_image_simple
11from astropy.stats import SigmaClip
12from photutils import Background2D, SExtractorBackground
13from photutils import make_source_mask
15from scipy.signal import medfilt2d
16from scipy.interpolate import interp2d
19def remove_image_background_sextractor(data, sigma=3.0, box_size=(50, 50), filter_size=(3, 3), positive=False):
20 sigma_clip = SigmaClip(sigma=sigma)
21 bkg_estimator = SExtractorBackground()
22 bkg = Background2D(data, box_size, filter_size=filter_size,
23 sigma_clip=sigma_clip, bkg_estimator=bkg_estimator)
24 data_wo_bkg = data - bkg.background
25 if positive:
26 data_wo_bkg -= np.min(data_wo_bkg)
27 if parameters.DEBUG:
28 fig, ax = plt.subplots(1, 2, figsize=(11, 5))
29 plot_image_simple(ax[0], bkg.background, scale="lin")
30 plot_image_simple(ax[1], data_wo_bkg, scale="symlog")
31 fig.tight_layout()
32 plt.show()
33 if parameters.PdfPages:
34 parameters.PdfPages.savefig()
35 return data_wo_bkg
38def extract_spectrogram_background_fit1D(data, err, deg=1, ws=(20, 30), pixel_step=1, sigma=5):
39 """
40 Fit a polynomial background slice per slice along the x axis,
41 with outlier removal, on lateral bands defined by the ws parameter.
43 Parameters
44 ----------
45 data: array
46 The 2D array image. The transverse profile is fitted on the y direction for all pixels along the x direction.
47 err: array
48 The uncertainties related to the data array.
49 deg: int
50 Degree of the polynomial model for the background (default: 1).
51 ws: list
52 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30])
53 pixel_step: int, optional
54 The step in pixels between the slices to be fitted (default: 1).
55 The values for the skipped pixels are interpolated with splines from the fitted parameters.
56 sigma: int
57 Sigma for outlier rejection (default: 5).
59 Returns
60 -------
61 bgd_model_func: callable
62 A 2D function to model the extracted background
64 Examples
65 --------
67 Build a mock spectrogram with random Poisson noise:
69 >>> from spectractor.extractor.psf import MoffatGauss
70 >>> from spectractor.extractor.chromaticpsf import ChromaticPSF
71 >>> from spectractor import parameters
72 >>> parameters.DEBUG = True
73 >>> psf = MoffatGauss()
74 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000)
75 >>> params = s0.generate_test_poly_params()
76 >>> saturation = params[-1]
77 >>> data = s0.evaluate(params, mode="1D")
78 >>> bgd = 10*np.ones_like(data)
79 >>> data += bgd
80 >>> data = np.random.poisson(data)
81 >>> data_errors = np.sqrt(data+1)
83 Fit the transverse profile:
85 >>> bgd_model = extract_spectrogram_background_fit1D(data, data_errors, deg=1, ws=[30,50], sigma=5, pixel_step=1)
87 """
88 Ny, Nx = data.shape
89 middle = Ny // 2
90 index = np.arange(Ny)
91 # Prepare the fit
92 bgd_index = np.concatenate((np.arange(0, middle - ws[0]), np.arange(middle + ws[0], Ny))).astype(int)
93 pixel_range = np.arange(0, Nx, pixel_step)
94 bgd_model = np.zeros_like(data).astype(float)
95 # Fit for pixels in pixel_range array
96 for x in pixel_range:
97 # fit the background with a polynomial function
98 bgd = data[bgd_index, x]
99 bgd_fit, outliers = fit_poly1d_outlier_removal(bgd_index, bgd, order=deg, sigma=sigma, niter=2)
100 bgd_model[:, x] = bgd_fit(index)
101 # Filter the background model
102 bgd_model = medfilt2d(bgd_model, kernel_size=[3, 9])
103 bgd_model_func = interp2d(np.arange(Nx), index, bgd_model, kind='linear', bounds_error=False, fill_value=None)
104 if parameters.DEBUG:
105 fig, ax = plt.subplots(3, 1, figsize=(12, 6), sharex='all')
106 bgd_bands = np.copy(data).astype(float)
107 bgd_bands[middle - ws[0]:middle + ws[0], :] = np.nan
108 im = ax[0].imshow(bgd_bands, origin='lower', aspect="auto", vmin=0)
109 c = plt.colorbar(im, ax=ax[0])
110 c.set_label(f'Data units (lin scale)')
111 ax[0].set_title(f'Data background: mean={np.nanmean(bgd_bands):.3f}, std={np.nanstd(bgd_bands):.3f}')
112 ax[0].set_xlabel(parameters.PLOT_XLABEL)
113 ax[0].set_ylabel(parameters.PLOT_YLABEL)
114 x = np.arange(Nx)
115 y = np.arange(Ny)
116 # noinspection PyTypeChecker
117 b = bgd_model_func(x, y)
118 im = ax[1].imshow(b, origin='lower', aspect="auto")
119 ax[1].set_xlabel(parameters.PLOT_XLABEL)
120 ax[1].set_ylabel(parameters.PLOT_YLABEL)
121 c2 = plt.colorbar(im, ax=ax[1])
122 c2.set_label(f'Data units (lin scale)')
123 ax[1].set_title(f'Fitted background: mean={np.mean(b):.3f}, std={np.std(b):.3f}')
124 res = (bgd_bands - b) / err
125 im = ax[2].imshow(res, origin='lower', aspect="auto", vmin=-5, vmax=5)
126 ax[2].set_xlabel(parameters.PLOT_XLABEL)
127 ax[2].set_ylabel(parameters.PLOT_YLABEL)
128 c2 = plt.colorbar(im, ax=ax[2])
129 c2.set_label(f'Data units (lin scale)')
130 ax[2].set_title(f'Pull: mean={np.nanmean(res):.3f}, std={np.nanstd(res):.3f}')
131 fig.tight_layout()
132 if parameters.DISPLAY: # pragma: no cover
133 plt.show()
134 if parameters.PdfPages:
135 parameters.PdfPages.savefig()
136 return bgd_model_func
139def extract_spectrogram_background_sextractor(data, err, ws=(20, 30), mask_signal_region=True):
140 """
141 Use photutils library median filter to estimate background behgin the sources.
143 Parameters
144 ----------
145 data: array
146 The 2D array image. The transverse profile is fitted on the y direction for all pixels along the x direction.
147 err: array
148 The uncertainties related to the data array.
149 ws: list
150 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30])
151 mask_signal_region: bool
152 If True, the signal region is masked with np.nan values (default: True)
154 Returns
155 -------
156 bgd_model_func: callable
157 A 2D function to model the extracted background.
158 bgd_res: array_like
159 The background residuals normalized with their uncertainties.
160 bgd_rms: array_like
161 The background RMS.
163 Examples
164 --------
166 Build a mock spectrogram with random Poisson noise:
168 >>> from spectractor.extractor.psf import MoffatGauss
169 >>> from spectractor.extractor.chromaticpsf import ChromaticPSF
170 >>> from spectractor import parameters
171 >>> parameters.DEBUG = True
172 >>> psf = MoffatGauss()
173 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000)
174 >>> params = s0.generate_test_poly_params()
175 >>> saturation = params[-1]
176 >>> data = s0.evaluate(params, mode="1D")
177 >>> bgd = 10*np.ones_like(data)
178 >>> data += bgd
179 >>> data = np.random.poisson(data)
180 >>> data_errors = np.sqrt(data+1)
182 Fit the transverse profile:
184 >>> bgd_model, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50])
186 """
187 Ny, Nx = data.shape
188 middle = Ny // 2
190 # mask sources
191 mask = make_source_mask(data, nsigma=3, npixels=5, dilate_size=11)
193 # Estimate the background in the two lateral bands together
194 sigma_clip = SigmaClip(sigma=3.)
195 bkg_estimator = SExtractorBackground()
196 if mask_signal_region:
197 bgd_bands = np.copy(data).astype(float)
198 bgd_bands[middle - ws[0]:middle + ws[0], :] = np.nan
199 mask += (np.isnan(bgd_bands))
200 # windows size in x is set to only 6 pixels to be able to estimate rapid variations of the background on real data
201 # filter window size is set to window // 2 so 3
202 # bkg = Background2D(data, ((ws[1] - ws[0]), (ws[1] - ws[0])),
203 # filter_size=((ws[1] - ws[0]) // 2, (ws[1] - ws[0]) // 2),
204 # sigma_clip=sigma_clip, bkg_estimator=bkg_estimator,
205 # mask=mask)
206 bkg = Background2D(data, (parameters.PIXWIDTH_BOXSIZE, parameters.PIXWIDTH_BOXSIZE),
207 filter_size=(parameters.PIXWIDTH_BOXSIZE // 2, parameters.PIXWIDTH_BOXSIZE // 2),
208 sigma_clip=sigma_clip, bkg_estimator=bkg_estimator,
209 mask=mask)
210 bgd_model_func = interp2d(np.arange(Nx), np.arange(Ny), bkg.background, kind='linear', bounds_error=False,
211 fill_value=None)
212 bgd_res = ((data - bkg.background)/err)
213 bgd_res[mask] = np.nan
215 if parameters.DEBUG:
216 gs = gridspec.GridSpec(3, 2, width_ratios=[4, 1], height_ratios=[1, 1, 1], wspace=0.1, hspace=0.04,
217 right=0.98, left=0.1, top=0.98, bottom=0.1)
218 fig = plt.figure(figsize=(7, 5))
219 ax0 = plt.subplot(gs[0, 0])
220 ax1 = plt.subplot(gs[1, 0])
221 ax2 = plt.subplot(gs[2, 0])
222 ax3 = plt.subplot(gs[:, 1])
223 bgd_bands = np.copy(data).astype(float)
224 bgd_bands[middle - ws[0]:middle + ws[0], :] = np.nan
225 bgd_bands[mask] = np.nan
226 mean = np.nanmean(bgd_bands)
227 std = np.nanstd(bgd_bands)
228 cmap = copy.copy(cm.get_cmap())
229 cmap.set_bad(color='lightgrey')
230 im = ax0.imshow(bgd_bands, origin='lower', aspect="auto", vmin=mean - 3 * std, vmax=mean + 3 * std)
231 v1 = np.linspace(mean - 3 * std, mean + 3 * std, 5, endpoint=True)
232 cb = plt.colorbar(im, ticks=v1, ax=ax0, label=f'Data units')
233 cb.ax.set_yticklabels(["{:2.0f}".format(i) for i in v1])
234 ax0.text(0.05, 0.95, f'Data background', color="white",
235 horizontalalignment='left', verticalalignment='top', transform=ax0.transAxes) # : mean={np.mean(b):.3f}, std={np.std(b):.3f}')
236 ax0.set_xlabel(parameters.PLOT_XLABEL)
237 ax0.set_ylabel(parameters.PLOT_YLABEL)
238 ax0.set_xticks([])
239 ax1.set_xticks([])
240 bkg.plot_meshes(outlines=True, color='red', axes=ax1, linewidth=0.5)
241 b = bkg.background
242 im = ax1.imshow(b, origin='lower', aspect="auto")
243 ax1.set_xlabel(parameters.PLOT_XLABEL)
244 ax1.set_ylabel(parameters.PLOT_YLABEL)
245 v1 = np.linspace(np.nanmin(b), np.nanmax(b), 5, endpoint=True)
246 cb1 = plt.colorbar(im, ticks=v1, ax=ax1, label=f'Data units')
247 cb1.ax.set_yticklabels(["{:2.0f}".format(i) for i in v1])
248 ax1.text(0.05, 0.95, f'Fitted background', color="white",
249 horizontalalignment='left', verticalalignment='top', transform=ax1.transAxes) # : mean={np.mean(b):.3f}, std={np.std(b):.3f}')
250 res = (bgd_bands - b) / err
251 im = ax2.imshow(res, origin='lower', aspect="auto", vmin=-5, vmax=5)
252 ax2.set_xlabel(parameters.PLOT_XLABEL)
253 ax2.set_ylabel(parameters.PLOT_YLABEL)
254 ax2.text(0.05, 0.95, f'Pull: mean={np.nanmean(res):.3f}, std={np.nanstd(res):.3f}', color="white",
255 horizontalalignment='left', verticalalignment='top', transform=ax2.transAxes) # : mean={np.mean(b):.3f}, std={np.std(b):.3f}')
256 v1 = np.array([-5, -2, 0, 2, 5])
257 cb2 = plt.colorbar(im, ticks=v1, ax=ax2, label=f'')
258 cb2.ax.set_yticklabels(["{:1.0f}".format(i) for i in v1])
259 # ax3.set_title(f'Pull') # mean={np.nanmean(res):.3f}, std={np.nanstd(res):.3f}')
260 hist_res = res[~np.isnan(res)].flatten()
261 hist_res = hist_res[hist_res < 5]
262 hist_res = hist_res[hist_res > -5]
263 ax3.hist(hist_res, bins=10)
264 ax3.grid()
265 ax3.set_yticks([])
266 # ax3.set_xlim((-5, 5))
267 # ax3.set_xticks(v1)
268 ax3.set_xlabel('Pull distribution')
269 # fig.tight_layout()
270 if parameters.LSST_SAVEFIGPATH: # pragma: no cover
271 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'background_extraction.pdf'))
272 if parameters.DISPLAY: # pragma: no cover
273 plt.show()
274 if parameters.PdfPages:
275 parameters.PdfPages.savefig()
276 return bgd_model_func, bgd_res, bkg.background_rms
279def extract_spectrogram_background_poly2D(data, deg=1, ws=(20, 30), pixel_step=1, sigma=5):
280 """
281 Fit a 2D polynomial background with outlier removal, on lateral bands defined by the ws parameter.
283 Parameters
284 ----------
285 data: array
286 The 2D array image. The transverse profile is fitted on the y direction for all pixels along the x direction.
287 deg: int
288 Degree of the polynomial model for the background (default: 1).
289 ws: list
290 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30])
291 pixel_step: int, optional
292 The step in pixels between the slices to be fitted (default: 1).
293 The values for the skipped pixels are interpolated with splines from the fitted parameters.
294 sigma: int
295 Sigma for outlier rejection (default: 5).
297 Returns
298 -------
299 bgd_model_func: callable
300 A 2D function to model the extracted background
302 Examples
303 --------
305 Build a mock spectrogram with random Poisson noise:
307 >>> from spectractor.extractor.psf import MoffatGauss
308 >>> from spectractor.extractor.chromaticpsf import ChromaticPSF
309 >>> from spectractor import parameters
310 >>> parameters.DEBUG = True
311 >>> psf = MoffatGauss()
312 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000)
313 >>> params = s0.generate_test_poly_params()
314 >>> saturation = params[-1]
315 >>> data = s0.evaluate(params, mode="1D")
316 >>> bgd = 10.*np.ones_like(data)
317 >>> xx, yy = np.meshgrid(np.arange(s0.Nx), np.arange(s0.Ny))
318 >>> bgd += 1000*np.exp(-((xx-20)**2+(yy-10)**2)/(2*2))
319 >>> data += bgd
320 >>> data = np.random.poisson(data)
321 >>> data_errors = np.sqrt(data+1)
323 Fit the transverse profile:
325 >>> bgd_model_func = extract_spectrogram_background_poly2D(data, deg=1, ws=[30,50], sigma=5, pixel_step=1)
327 """
328 Ny, Nx = data.shape
329 middle = Ny // 2
330 # Prepare the fit
331 bgd_index = np.concatenate((np.arange(0, middle - ws[0]), np.arange(middle + ws[0], Ny))).astype(int)
332 pixel_range = np.arange(0, Nx, pixel_step)
333 # Concatenate the background lateral bounds
334 bgd_bands = data[bgd_index, :]
335 bgd_bands = bgd_bands[:, pixel_range]
336 bgd_bands = bgd_bands.astype(float)
337 # Fit a 1 degree 2D polynomial function with outlier removal
338 xx, yy = np.meshgrid(pixel_range, bgd_index)
339 bgd_model_func = fit_poly2d_outlier_removal(xx, yy, bgd_bands, order=deg, sigma=sigma, niter=20)
340 bgd_model_func = interp2d(xx, yy, bgd_model_func(xx, yy), kind='linear', bounds_error=False,
341 fill_value=None)
343 if parameters.DEBUG:
344 fig, ax = plt.subplots(2, 1, figsize=(12, 6), sharex='all')
345 bgd_bands = np.copy(data).astype(float)
346 bgd_bands[middle - ws[0]:middle + ws[0], :] = np.nan
347 im = ax[0].imshow(bgd_bands, origin='lower', aspect="auto", vmin=0)
348 c = plt.colorbar(im, ax=ax[0])
349 c.set_label(f'Data units (lin scale)')
350 ax[0].set_title(f'Data background: mean={np.nanmean(bgd_bands):.3f}, std={np.nanstd(bgd_bands):.3f}')
351 ax[0].set_xlabel(parameters.PLOT_XLABEL)
352 ax[0].set_ylabel(parameters.PLOT_YLABEL)
353 # noinspection PyTypeChecker
354 b = bgd_model_func(np.arange(Nx), np.arange(Ny))
355 im = ax[1].imshow(b, origin='lower', aspect="auto")
356 ax[1].set_xlabel(parameters.PLOT_XLABEL)
357 ax[1].set_ylabel(parameters.PLOT_YLABEL)
358 c2 = plt.colorbar(im, ax=ax[1])
359 c2.set_label(f'Data units (lin scale)')
360 ax[1].set_title(f'Fitted background: mean={np.mean(b):.3f}, std={np.std(b):.3f}')
361 fig.tight_layout()
362 if parameters.DISPLAY: # pragma: no cover
363 plt.show()
364 if parameters.PdfPages:
365 parameters.PdfPages.savefig()
366 return bgd_model_func
369if __name__ == "__main__": 369 ↛ 370line 369 didn't jump to line 370, because the condition on line 369 was never true
370 import doctest
372 doctest.testmod()