Coverage for spectractor/extractor/background.py: 10%

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

169 statements  

1import numpy as np 

2import matplotlib.pyplot as plt 

3import matplotlib.gridspec as gridspec 

4from matplotlib import cm 

5import os 

6import copy 

7 

8from spectractor import parameters 

9from spectractor.tools import fit_poly1d_outlier_removal, fit_poly2d_outlier_removal, plot_image_simple 

10 

11from astropy.stats import SigmaClip 

12from photutils import Background2D, SExtractorBackground 

13from photutils import make_source_mask 

14 

15from scipy.signal import medfilt2d 

16from scipy.interpolate import interp2d 

17 

18 

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 

36 

37 

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. 

42 

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). 

58 

59 Returns 

60 ------- 

61 bgd_model_func: callable 

62 A 2D function to model the extracted background 

63 

64 Examples 

65 -------- 

66 

67 Build a mock spectrogram with random Poisson noise: 

68 

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.build_spectrogram_image(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) 

82 

83 Fit the transverse profile: 

84 

85 >>> bgd_model = extract_spectrogram_background_fit1D(data, data_errors, deg=1, ws=[30,50], sigma=5, pixel_step=1) 

86 

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 

137 

138 

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. 

142 

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) 

153 

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. 

162 

163 Examples 

164 -------- 

165 

166 Build a mock spectrogram with random Poisson noise: 

167 

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.build_spectrogram_image(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) 

181 

182 Fit the transverse profile: 

183 

184 >>> bgd_model, _, _ = extract_spectrogram_background_sextractor(data, data_errors, ws=[30,50]) 

185 

186 """ 

187 Ny, Nx = data.shape 

188 middle = Ny // 2 

189 

190 # mask sources 

191 mask = make_source_mask(data, nsigma=3, npixels=5, dilate_size=11) 

192 

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 

214 

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 return bgd_model_func, bgd_res, bkg.background_rms 

275 

276 

277def extract_spectrogram_background_poly2D(data, deg=1, ws=(20, 30), pixel_step=1, sigma=5): 

278 """ 

279 Fit a 2D polynomial background with outlier removal, on lateral bands defined by the ws parameter. 

280 

281 Parameters 

282 ---------- 

283 data: array 

284 The 2D array image. The transverse profile is fitted on the y direction for all pixels along the x direction. 

285 deg: int 

286 Degree of the polynomial model for the background (default: 1). 

287 ws: list 

288 up/down region extension where the sky background is estimated with format [int, int] (default: [20,30]) 

289 pixel_step: int, optional 

290 The step in pixels between the slices to be fitted (default: 1). 

291 The values for the skipped pixels are interpolated with splines from the fitted parameters. 

292 sigma: int 

293 Sigma for outlier rejection (default: 5). 

294 

295 Returns 

296 ------- 

297 bgd_model_func: callable 

298 A 2D function to model the extracted background 

299 

300 Examples 

301 -------- 

302 

303 Build a mock spectrogram with random Poisson noise: 

304 

305 >>> from spectractor.extractor.psf import MoffatGauss 

306 >>> from spectractor.extractor.chromaticpsf import ChromaticPSF 

307 >>> from spectractor import parameters 

308 >>> parameters.DEBUG = True 

309 >>> psf = MoffatGauss() 

310 >>> s0 = ChromaticPSF(psf, Nx=100, Ny=100, saturation=1000) 

311 >>> params = s0.generate_test_poly_params() 

312 >>> saturation = params[-1] 

313 >>> data = s0.build_spectrogram_image(params, mode="1D") 

314 >>> bgd = 10.*np.ones_like(data) 

315 >>> xx, yy = np.meshgrid(np.arange(s0.Nx), np.arange(s0.Ny)) 

316 >>> bgd += 1000*np.exp(-((xx-20)**2+(yy-10)**2)/(2*2)) 

317 >>> data += bgd 

318 >>> data = np.random.poisson(data) 

319 >>> data_errors = np.sqrt(data+1) 

320 

321 Fit the transverse profile: 

322 

323 >>> bgd_model_func = extract_spectrogram_background_poly2D(data, deg=1, ws=[30,50], sigma=5, pixel_step=1) 

324 

325 """ 

326 Ny, Nx = data.shape 

327 middle = Ny // 2 

328 # Prepare the fit 

329 bgd_index = np.concatenate((np.arange(0, middle - ws[0]), np.arange(middle + ws[0], Ny))).astype(int) 

330 pixel_range = np.arange(0, Nx, pixel_step) 

331 # Concatenate the background lateral bounds 

332 bgd_bands = data[bgd_index, :] 

333 bgd_bands = bgd_bands[:, pixel_range] 

334 bgd_bands = bgd_bands.astype(float) 

335 # Fit a 1 degree 2D polynomial function with outlier removal 

336 xx, yy = np.meshgrid(pixel_range, bgd_index) 

337 bgd_model_func = fit_poly2d_outlier_removal(xx, yy, bgd_bands, order=deg, sigma=sigma, niter=20) 

338 bgd_model_func = interp2d(xx, yy, bgd_model_func(xx, yy), kind='linear', bounds_error=False, 

339 fill_value=None) 

340 

341 if parameters.DEBUG: 

342 fig, ax = plt.subplots(2, 1, figsize=(12, 6), sharex='all') 

343 bgd_bands = np.copy(data).astype(float) 

344 bgd_bands[middle - ws[0]:middle + ws[0], :] = np.nan 

345 im = ax[0].imshow(bgd_bands, origin='lower', aspect="auto", vmin=0) 

346 c = plt.colorbar(im, ax=ax[0]) 

347 c.set_label(f'Data units (lin scale)') 

348 ax[0].set_title(f'Data background: mean={np.nanmean(bgd_bands):.3f}, std={np.nanstd(bgd_bands):.3f}') 

349 ax[0].set_xlabel(parameters.PLOT_XLABEL) 

350 ax[0].set_ylabel(parameters.PLOT_YLABEL) 

351 # noinspection PyTypeChecker 

352 b = bgd_model_func(np.arange(Nx), np.arange(Ny)) 

353 im = ax[1].imshow(b, origin='lower', aspect="auto") 

354 ax[1].set_xlabel(parameters.PLOT_XLABEL) 

355 ax[1].set_ylabel(parameters.PLOT_YLABEL) 

356 c2 = plt.colorbar(im, ax=ax[1]) 

357 c2.set_label(f'Data units (lin scale)') 

358 ax[1].set_title(f'Fitted background: mean={np.mean(b):.3f}, std={np.std(b):.3f}') 

359 fig.tight_layout() 

360 if parameters.DISPLAY: # pragma: no cover 

361 plt.show() 

362 if parameters.PdfPages: 

363 parameters.PdfPages.savefig() 

364 return bgd_model_func 

365 

366 

367if __name__ == "__main__": 367 ↛ 368line 367 didn't jump to line 368, because the condition on line 367 was never true

368 import doctest 

369 

370 doctest.testmod()