### Generate 1D Gaussian PSF kernels with gaussxkernel/gaussykernel Source: https://context7.com/astropy/astroscrappy/llms.txt Generates 1-D Gaussian kernels for spectroscopic data, Gaussian along one axis and uniform along the other. Useful for `detect_cosmics` when the PSF is elongated along the dispersion direction. ```python from astroscrappy import gaussxkernel, gaussykernel import astroscrappy # Gaussian along the dispersion (x) axis only kx = gaussxkernel(psffwhm=3.0, kernsize=9) # Gaussian along the spatial (y) axis only ky = gaussykernel(psffwhm=3.0, kernsize=9) # Apply to a spectrum with cosmic rays crmask, clean = astroscrappy.detect_cosmics( spectrum_data, gain=2.0, readnoise=6.0, fsmode='convolve', psfk=kx, ) ``` -------------------------------- ### Median filter utilities (medfilt3, medfilt5, medfilt7) Source: https://context7.com/astropy/astroscrappy/llms.txt Provides optimized C implementations of full (square window) median filters for 3x3, 5x5, and 7x7 kernels. ```APIDOC ## Median filter utilities ### Description Full (square window) median filters of sizes 3×3, 5×5, and 7×7, implemented in optimized C. Border pixels (within `floor(size/2)` of the edge) are copied unchanged from the input. All arrays must be C-contiguous `float32`. ### Functions - **medfilt3(image)**: Applies a 3x3 median filter. - **medfilt5(image)**: Applies a 5x5 median filter. - **medfilt7(image)**: Applies a 7x7 median filter. ### Parameters - **image** (numpy.ndarray) - Input image data (must be C-contiguous float32). ### Returns - **smooth_image** (numpy.ndarray) - The median-filtered image. ### Example ```python import numpy as np from astroscrappy.utils import medfilt3, medfilt5, medfilt7 image = np.random.normal(500, 20, (2048, 2048)).astype(np.float32) smooth3 = medfilt3(image) # 3×3 window smooth5 = medfilt5(image) # 5×5 window smooth7 = medfilt7(image) # 7×7 window print(smooth5.shape, smooth5.dtype) # (2048, 2048) float32 ``` ``` -------------------------------- ### Optimized small-array medians with optmed3/5/25 Source: https://context7.com/astropy/astroscrappy/llms.txt Provides fixed-length, branch-network-optimized median routines for arrays of exactly 3, 5, or 25 elements. These are used internally for per-pixel 5x5 neighborhood operations within C cleaning loops. ```python import numpy as np from astroscrappy.utils import optmed3, optmed5, optmed25 a3 = np.array([3.0, 1.0, 2.0], dtype=np.float32) a5 = np.array([5.0, 1.0, 3.0, 2.0, 4.0], dtype=np.float32) a25 = np.random.random(25).astype(np.float32) print(optmed3(a3)) # 2.0 print(optmed5(a5)) # 3.0 print(optmed25(a25)) # same as np.median(a25) within float32 precision ``` -------------------------------- ### Generate 2D Gaussian PSF kernel with gausskernel Source: https://context7.com/astropy/astroscrappy/llms.txt Creates a normalized, circular 2D Gaussian kernel for convolving images. Use this when `fsmode='convolve'` in `detect_cosmics` and you need to supply a custom kernel. ```python from astroscrappy import gausskernel import numpy as np # FWHM = 2.5 pixels, 7×7 kernel kernel = gausskernel(psffwhm=2.5, kernsize=7) print(kernel.shape) # (7, 7) print(kernel.sum()) # ~1.0 (normalized) print(kernel.dtype) # float32 # Use the pre-computed kernel directly in detect_cosmics import astroscrappy crmask, clean = astroscrappy.detect_cosmics( data, gain=1.5, readnoise=5.0, fsmode='convolve', psfk=kernel, # supply kernel explicitly — psfmodel/psffwhm/psfsize ignored ) ``` -------------------------------- ### 2x2 Pixel Resampling: Upsampling and Downsampling Source: https://context7.com/astropy/astroscrappy/llms.txt Subsample expands an array 2x by replicating pixels, while rebin shrinks an array 2x by block-averaging. These are used in the LA Cosmic subsampling step. ```python import numpy as np from astroscrappy.utils import subsample, rebin image = np.random.random((512, 512)).astype(np.float32) big = subsample(image) # shape: (1024, 1024) small = rebin(big) # shape: (512, 512) — values ≈ image print(big.shape, small.shape) # (1024, 1024) (512, 512) ``` -------------------------------- ### Optimized small-array medians (optmed3, optmed5, optmed7, optmed9, optmed25) Source: https://context7.com/astropy/astroscrappy/llms.txt Provides fixed-length, branch-network–optimized median routines for arrays of exactly 3, 5, 7, 9, or 25 elements. ```APIDOC ## Optimized small-array medians ### Description Fixed-length, branch-network–optimized median routines for arrays of exactly 3, 5, 7, 9, or 25 elements. They use sorting networks to achieve the minimum number of comparisons and are called inside the C cleaning loops for per-pixel 5×5 neighbourhood operations. ### Functions - **optmed3(array)**: Median of 3 elements. - **optmed5(array)**: Median of 5 elements. - **optmed7(array)**: Median of 7 elements. - **optmed9(array)**: Median of 9 elements. - **optmed25(array)**: Median of 25 elements. ### Parameters - **array** (numpy.ndarray) - Input array of the exact specified length (float32). ### Returns - **median_value** (float) - The median of the array elements. ### Example ```python import numpy as np from astroscrappy.utils import optmed3, optmed5, optmed25 a3 = np.array([3.0, 1.0, 2.0], dtype=np.float32) a5 = np.array([5.0, 1.0, 3.0, 2.0, 4.0], dtype=np.float32) a25 = np.random.random(25).astype(np.float32) print(optmed3(a3)) # 2.0 print(optmed5(a5)) # 3.0 print(optmed25(a25)) # same as np.median(a25) within float32 precision ``` ``` -------------------------------- ### Apply 3x3, 5x5, 7x7 median filters with medfilt3/5/7 Source: https://context7.com/astropy/astroscrappy/llms.txt Performs full square-window median filtering on images using optimized C implementations. Border pixels are copied from the input; all input arrays must be C-contiguous `float32`. ```python import numpy as np from astroscrappy.utils import medfilt3, medfilt5, medfilt7 image = np.random.normal(500, 20, (2048, 2048)).astype(np.float32) smooth3 = medfilt3(image) # 3×3 window smooth5 = medfilt5(image) # 5×5 window smooth7 = medfilt7(image) # 7×7 window print(smooth5.shape, smooth5.dtype) # (2048, 2048) float32 ``` -------------------------------- ### gaussxkernel / gaussykernel Source: https://context7.com/astropy/astroscrappy/llms.txt Generates 1-D Gaussian PSF kernels that are Gaussian along one axis and uniform along the other, suitable for spectroscopic data. ```APIDOC ## gaussxkernel / gaussykernel ### Description Generate kernels that are Gaussian only along the x- or y-axis respectively, with uniform weight along the perpendicular axis. These are designed for spectroscopic data where the PSF is elongated along the dispersion direction. ### Parameters - **psffwhm** (float) - Full Width at Half Maximum of the Gaussian. - **kernsize** (int) - The size of the kernel (must be odd). ### Returns - **kernel** (numpy.ndarray) - A 1-D numpy array representing the Gaussian kernel. ### Example ```python from astroscrappy import gaussxkernel, gaussykernel # Gaussian along the dispersion (x) axis only kx = gaussxkernel(psffwhm=3.0, kernsize=9) # Gaussian along the spatial (y) axis only ky = gaussykernel(psffwhm=3.0, kernsize=9) ``` ``` -------------------------------- ### subsample and rebin Source: https://context7.com/astropy/astroscrappy/llms.txt Functions for 2x pixel resampling. `subsample` expands an array by replicating pixels, while `rebin` shrinks an array by block-averaging. ```APIDOC ## subsample and rebin — 2×2 pixel resampling ### Description `subsample` expands an array 2× in each dimension by replicating each pixel into a 2×2 block (no interpolation). `rebin` is the inverse: it shrinks an array 2× by block-averaging each 2×2 group of pixels into one. These are used internally in the LA Cosmic subsampling step. ### Parameters - **image** (numpy.ndarray) - The input 2-D `float32` array. ### Returns - **subsample**: (numpy.ndarray) - The expanded 2-D `float32` array. - **rebin**: (numpy.ndarray) - The shrunk 2-D `float32` array. ### Example ```python import numpy as np from astroscrappy.utils import subsample, rebin image = np.random.random((512, 512)).astype(np.float32) big = subsample(image) # shape: (1024, 1024) small = rebin(big) # shape: (512, 512) — values ≈ image print(big.shape, small.shape) # (1024, 1024) (512, 512) ``` ``` -------------------------------- ### gausskernel Source: https://context7.com/astropy/astroscrappy/llms.txt Generates a normalized, circular 2-D Gaussian kernel suitable for cosmic ray detection with `detect_cosmics` when `fsmode='convolve'`. ```APIDOC ## gausskernel ### Description Produces a normalized, circular Gaussian kernel suitable for use with `detect_cosmics(fsmode='convolve', psfk=...)`. The kernel is computed on a grid of size `kernsize × kernsize`, centred at the array midpoint. ### Parameters - **psffwhm** (float) - Full Width at Half Maximum of the Gaussian. - **kernsize** (int) - The size of the kernel grid (must be odd). ### Returns - **kernel** (numpy.ndarray) - A 2-D numpy array representing the Gaussian kernel. ### Example ```python from astroscrappy import gausskernel import numpy as np # FWHM = 2.5 pixels, 7x7 kernel kernel = gausskernel(psffwhm=2.5, kernsize=7) print(kernel.shape) # (7, 7) print(kernel.sum()) # ~1.0 (normalized) print(kernel.dtype) # float32 ``` ``` -------------------------------- ### `detect_cosmics` — Detect and clean cosmic rays in a 2-D image array Source: https://context7.com/astropy/astroscrappy/llms.txt The primary entry point of the library. It runs up to `niter` iterations of the L.A.Cosmic algorithm to detect and clean cosmic rays in a 2-D NumPy array. It can optionally use pre-estimated background and variance maps, bad-pixel masks, and detector parameters. It returns a boolean cosmic-ray mask and a cleaned version of the image. ```APIDOC ## `detect_cosmics` - Detect and clean cosmic rays in a 2-D image array ### Description The primary entry point of the library. It runs up to `niter` iterations of the L.A.Cosmic algorithm: subsampling the image, applying the discrete Laplacian, building a noise model from the data or a supplied variance map, constructing a fine-structure image (via median filtering or matched-filter convolution), and flagging pixels whose Laplacian signal-to-noise ratio exceeds `sigclip` and whose contrast against the fine-structure image exceeds `objlim`. Detected pixels are then cleaned according to `cleantype`. Saturated stars are automatically masked before detection to prevent them being misclassified as cosmic rays. ### Parameters * **data** (numpy.ndarray) - Input 2D image array (in ADU counts). * **inmask** (numpy.ndarray, optional) - Pre-existing bad-pixel mask (boolean, True = bad). Pixels marked as True will be ignored. * **inbkg** (numpy.ndarray, optional) - Background image (ADU). This background is subtracted before detection and added back to the cleaned image. * **invar** (numpy.ndarray, optional) - Variance image (ADU^2). Used instead of an internally generated noise model. * **gain** (float, optional) - Detector gain in electrons/ADU. Default is 1.0. * **readnoise** (float, optional) - Detector read noise in electrons RMS. Default is 0.0. * **satlevel** (float, optional) - Saturation level in ADU. Pixels with values greater than or equal to this level are masked as saturated. Default is infinity. * **sigclip** (float, optional) - Laplacian signal-to-noise ratio threshold for cosmic ray detection. Default is 4.5. * **sigfrac** (float, optional) - Neighbor detection threshold, relative to `sigclip`. Default is 0.3. * **objlim** (float, optional) - Contrast threshold against the fine-structure image for cosmic ray detection. Default is 5.0. * **niter** (int, optional) - Number of iterations for the L.A.Cosmic algorithm. Default is 4. * **sepmed** (bool, optional) - Whether to use a fast separable median filter. Recommended for performance. Default is True. * **cleantype** (str, optional) - Method for cleaning detected cosmic rays. Options: 'median', 'medmask', 'meanmask', 'idw'. Default is 'meanmask'. * **fsmode** (str, optional) - Mode for generating the fine-structure image. Options: 'median', 'convolve'. Default is 'median'. * **psfmodel** (str, optional) - PSF model to use when `fsmode` is 'convolve'. Options: 'gauss', 'gaussx', 'gaussy', 'moffat'. * **psffwhm** (float, optional) - Full Width at Half Maximum (FWHM) of the PSF in pixels, used when `fsmode` is 'convolve'. * **psfsize** (int, optional) - Size of the PSF kernel. Must be an odd integer. * **verbose** (bool, optional) - If True, print progress messages. Default is False. ### Returns * **crmask** (numpy.ndarray) - Boolean mask where True indicates a detected cosmic ray. * **cleanarr** (numpy.ndarray) - The cleaned image array in the same units as the input. ### Request Example ```python import numpy as np import astroscrappy from astropy.io import fits # --- Load a raw CCD frame (sky-included, in ADU) --- with fits.open('raw_frame.fits') as hdul: data = hdul['SCI'].data.astype(np.float32) # (ny, nx) C-contiguous array # Optional: pre-estimated background from sky fitting sky = hdul['SKYFIT'].data.astype(np.float32) # Optional: per-pixel variance from the pipeline var = hdul['VAR'].data.astype(np.float32) # Optional: existing bad-pixel mask (True = bad) bpm = hdul['BPM'].data.astype(bool) # --- Minimal call (imaging data, detector params provided) --- crmask, cleanarr = astroscrappy.detect_cosmics( data, gain=1.5, # e⁻/ADU readnoise=5.0, # e⁻ RMS satlevel=65000.0, # ADU — pixels ≥ this are masked as saturated sigclip=4.5, # Laplacian S/N threshold objlim=5.0, # fine-structure contrast threshold niter=4, verbose=True, ) print(f"Cosmic rays found: {crmask.sum()}") # --- Advanced call: spectroscopic frame with background + variance --- crmask_spec, cleanarr_spec = astroscrappy.detect_cosmics( data, inmask=bpm, # pre-existing bad pixels to ignore inbkg=sky, # background image (ADU); subtracted before detection, # added back in the returned cleanarr invar=var, # variance image (ADU²); used instead of internal noise model gain=1.933, readnoise=4.24, satlevel=65536.0, sigclip=4.5, sigfrac=0.3, # neighbor detection threshold = sigfrac * sigclip objlim=5.0, niter=4, sepmed=True, # fast separable median (recommended) cleantype='meanmask', # 'median' | 'medmask' | 'meanmask' | 'idw' fsmode='median', # 'median' | 'convolve' verbose=False, ) # --- PSF-matched fine-structure mode (imaging, known PSF) --- crmask_psf, cleanarr_psf = astroscrappy.detect_cosmics( data, gain=1.5, readnoise=5.0, fsmode='convolve', # use matched filter for fine-structure image psfmodel='gauss', # 'gauss' | 'gaussx' | 'gaussy' | 'moffat' psffwhm=2.5, # PSF FWHM in pixels psfsize=7, # kernel size (must be odd) ) # --- Reproduce original IRAF L.A.Cosmic behaviour --- crmask_iraf, _ = astroscrappy.detect_cosmics( data, inmask=None, satlevel=np.inf, # no saturation masking sepmed=False, # full (not separable) median filter cleantype='medmask', fsmode='median', ) # --- Write results --- hdu_mask = fits.ImageHDU(crmask.astype(np.uint8), name='CRMASK') hdu_clean = fits.ImageHDU(cleanarr, name='CLEAN') fits.HDUList([fits.PrimaryHDU(), hdu_mask, hdu_clean]).writeto('output.fits', overwrite=True) ``` ``` -------------------------------- ### median Source: https://context7.com/astropy/astroscrappy/llms.txt Computes the median of the first `n` elements of a 1-D `float32` array using an optimized C implementation (partial sort / selection). ```APIDOC ## median ### Description Computes the median of the first `n` elements of a 1-D `float32` array using an optimized C implementation (partial sort / selection). This is the workhorse called inside cleaning loops where GIL-free operation is required. ### Parameters - **array** (numpy.ndarray) - Input 1-D float32 array. - **n** (int) - The number of elements to consider for the median calculation. ### Returns - **median_value** (float) - The median of the first `n` elements. ### Example ```python import numpy as np from astroscrappy.utils import median a = np.random.normal(100, 5, 10001).astype(np.float32) med = median(a, len(a)) print(f"Median: {med:.4f}") # e.g. Median: 99.9823 ``` ``` -------------------------------- ### Separable median filter utilities (sepmedfilt3, sepmedfilt5, sepmedfilt7, sepmedfilt9) Source: https://context7.com/astropy/astroscrappy/llms.txt Offers fast separable median filters (row-wise then column-wise) that approximate square-window median filtering. ```APIDOC ## Separable median filter utilities ### Description Separable median filters that first median-filter each row, then each column. They are not mathematically identical to the full square-window median but produce very similar results and are significantly faster. These are the default filters used inside `detect_cosmics` when `sepmed=True`. ### Functions - **sepmedfilt3(image)**: Applies a 3x3 separable median filter. - **sepmedfilt5(image)**: Applies a 5x5 separable median filter. - **sepmedfilt7(image)**: Applies a 7x7 separable median filter. - **sepmedfilt9(image)**: Applies a 9x9 separable median filter. ### Parameters - **image** (numpy.ndarray) - Input image data (must be C-contiguous float32). ### Returns - **filtered_image** (numpy.ndarray) - The filtered image. ### Example ```python import numpy as np from astroscrappy.utils import sepmedfilt7, sepmedfilt9 image = np.random.normal(500, 20, (4096, 4096)).astype(np.float32) # Used internally for noise estimation (7×7) noise_model = sepmedfilt7(image) # Used internally for fine structure (9×9) fine_structure = sepmedfilt9(image) ``` ``` -------------------------------- ### Compute fast median of array elements with median Source: https://context7.com/astropy/astroscrappy/llms.txt Calculates the median of the first `n` elements of a 1-D `float32` array using an optimized C partial sort. This function is crucial for GIL-free operations within cleaning loops. ```python import numpy as np from astroscrappy.utils import median a = np.random.normal(100, 5, 1001).astype(np.float32) med = median(a, len(a)) print(f"Median: {med:.4f}") # e.g. Median: 99.9823 ``` -------------------------------- ### laplaceconvolve Source: https://context7.com/astropy/astroscrappy/llms.txt Convolves a 2-D float32 array with the discrete Laplacian kernel for edge detection. This is a fast C implementation and a core step in the L.A.Cosmic algorithm. ```APIDOC ## laplaceconvolve — Discrete Laplacian convolution ### Description Convolves a 2-D `float32` array with the discrete Laplacian kernel `[[0,-1,0],[-1,4,-1],[0,-1,0]]` using a fast C implementation. This is the core edge-detection step in the L.A.Cosmic algorithm. ### Parameters - **image** (numpy.ndarray) - A 2-D `float32` NumPy array to be convolved. ### Returns - **lap** (numpy.ndarray) - The convolved 2-D `float32` array. ### Example ```python import numpy as np from astroscrappy.utils import laplaceconvolve image = np.random.normal(500, 20, (2048, 2048)).astype(np.float32) lap = laplaceconvolve(image) # Positive values indicate locally sharp features (potential cosmic rays) print(f"Max Laplacian response: {lap.max():.2f}") ``` ``` -------------------------------- ### Apply separable median filters with sepmedfilt Source: https://context7.com/astropy/astroscrappy/llms.txt Uses separable median filters (row-wise then column-wise) for faster median filtering, producing similar results to square-window filters. These are the default filters used in `detect_cosmics` when `sepmed=True`. ```python import numpy as np from astroscrappy.utils import sepmedfilt7, sepmedfilt9 image = np.random.normal(500, 20, (4096, 4096)).astype(np.float32) # Used internally for noise estimation (7×7) noise_model = sepmedfilt7(image) # Used internally for fine structure (9×9) fine_structure = sepmedfilt9(image) ``` -------------------------------- ### Detect and Clean Cosmic Rays with Astro-SCRAPPY Source: https://context7.com/astropy/astroscrappy/llms.txt This is the primary function to detect and clean cosmic rays. It requires image data and detector parameters. Optional inputs include bad-pixel masks, background, and variance maps. It returns a cosmic-ray mask and the cleaned image. ```python import numpy as np import astroscrappy from astropy.io import fits # --- Load a raw CCD frame (sky-included, in ADU) --- with fits.open('raw_frame.fits') as hdul: data = hdul['SCI'].data.astype(np.float32) # (ny, nx) C-contiguous array # Optional: pre-estimated background from sky fitting sky = hdul['SKYFIT'].data.astype(np.float32) # Optional: per-pixel variance from the pipeline var = hdul['VAR'].data.astype(np.float32) # Optional: existing bad-pixel mask (True = bad) bpm = hdul['BPM'].data.astype(bool) # --- Minimal call (imaging data, detector params provided) --- crmask, cleanarr = astroscrappy.detect_cosmics( data, gain=1.5, # e⁻/ADU readnoise=5.0, # e⁻ RMS satlevel=65000.0, # ADU — pixels ≥ this are masked as saturated sigclip=4.5, # Laplacian S/N threshold objlim=5.0, # fine-structure contrast threshold niter=4, verbose=True, ) # crmask : bool ndarray, True where cosmic rays were found # cleanarr : float32 ndarray, cleaned image in original ADU units print(f"Cosmic rays found: {crmask.sum()}") # Example output: Cosmic rays found: 237 # --- Advanced call: spectroscopic frame with background + variance --- crmask_spec, cleanarr_spec = astroscrappy.detect_cosmics( data, inmask=bpm, # pre-existing bad pixels to ignore inbkg=sky, # background image (ADU); subtracted before detection, # added back in the returned cleanarr invar=var, # variance image (ADU²); used instead of internal noise model gain=1.933, readnoise=4.24, satlevel=65536.0, sigclip=4.5, sigfrac=0.3, # neighbor detection threshold = sigfrac * sigclip objlim=5.0, niter=4, sepmed=True, # fast separable median (recommended) cleantype='meanmask', # 'median' | 'medmask' | 'meanmask' | 'idw' fsmode='median', # 'median' | 'convolve' verbose=False, ) # --- PSF-matched fine-structure mode (imaging, known PSF) --- crmask_psf, cleanarr_psf = astroscrappy.detect_cosmics( data, gain=1.5, readnoise=5.0, fsmode='convolve', # use matched filter for fine-structure image psfmodel='gauss', # 'gauss' | 'gaussx' | 'gaussy' | 'moffat' psffwhm=2.5, # PSF FWHM in pixels psfsize=7, # kernel size (must be odd) ) # --- Reproduce original IRAF L.A.Cosmic behaviour --- crmask_iraf, _ = astroscrappy.detect_cosmics( data, inmask=None, satlevel=np.inf, # no saturation masking sepmed=False, # full (not separable) median filter cleantype='medmask', fsmode='median', ) # --- Write results --- hdu_mask = fits.ImageHDU(crmask.astype(np.uint8), name='CRMASK') hdu_clean = fits.ImageHDU(cleanarr, name='CLEAN') fits.HDUList([fits.PrimaryHDU(), hdu_mask, hdu_clean]).writeto('output.fits', overwrite=True) ``` -------------------------------- ### Laplacian Convolution for Edge Detection Source: https://context7.com/astropy/astroscrappy/llms.txt Convolves a 2D float32 array with the discrete Laplacian kernel. This is the core edge-detection step in the L.A.Cosmic algorithm. Positive values indicate locally sharp features. ```python import numpy as np from astroscrappy.utils import laplaceconvolve image = np.random.normal(500, 20, (2048, 2048)).astype(np.float32) lap = laplaceconvolve(image) # Positive values indicate locally sharp features (potential cosmic rays) print(f"Max Laplacian response: {lap.max():.2f}") ``` -------------------------------- ### General 2D Convolution with Arbitrary Kernel Source: https://context7.com/astropy/astroscrappy/llms.txt Convolves a 2D float32 array with an arbitrary float32 kernel. Used internally to build the matched-filter fine-structure image. Both arrays must be C-contiguous. ```python import numpy as np from astroscrappy.utils import convolve from astroscrappy import gausskernel image = np.random.normal(500, 20, (1024, 1024)).astype(np.float32) kernel = gausskernel(psffwhm=2.5, kernsize=7) smoothed = convolve(image, kernel) print(smoothed.shape, smoothed.dtype) # (1024, 1024) float32 ``` -------------------------------- ### Binary Morphological Dilation Source: https://context7.com/astropy/astroscrappy/llms.txt Dilate3 performs one iteration of binary dilation with a 3x3 structuring element. Dilate5 performs niter iterations with a 5x5 cross-like element. Used to grow masks. ```python import numpy as np from astroscrappy.utils import dilate3, dilate5 # Sparse boolean mask — e.g., initially flagged cosmic ray centres mask = np.zeros((1024, 1024), dtype=bool) mask[300, 400] = True mask[700, 200] = True grown3 = dilate3(mask) # 3×3 dilation: each True pixel grows by 1 pixel grown5 = dilate5(mask, niter=2) # 5×5 dilation, 2 iterations print(grown3.sum()) # 9 (3×3 neighbourhood around each seed pixel) print(grown5.sum()) # ~84 (two passes with the 5×5 kernel) ``` -------------------------------- ### dilate3 and dilate5 Source: https://context7.com/astropy/astroscrappy/llms.txt Functions for binary morphological dilation. `dilate3` uses a 3x3 structuring element, while `dilate5` uses a 5x5 cross-like element for multiple iterations. ```APIDOC ## dilate3 and dilate5 — Binary morphological dilation ### Description `dilate3` performs one iteration of binary dilation with a full 3×3 structuring element (logical OR of all 8 neighbours). `dilate5` performs `niter` iterations with a cross-like 5×5 element (corners excluded). Used to grow cosmic-ray and saturation masks to cover neighbouring affected pixels. ### Parameters - **mask** (numpy.ndarray) - The input boolean mask array. - **niter** (int, optional) - The number of iterations for `dilate5`. Defaults to 1. ### Returns - **grown3** (numpy.ndarray) - The dilated boolean mask after one 3x3 iteration. - **grown5** (numpy.ndarray) - The dilated boolean mask after `niter` 5x5 iterations. ### Example ```python import numpy as np from astroscrappy.utils import dilate3, dilate5 # Sparse boolean mask — e.g., initially flagged cosmic ray centres mask = np.zeros((1024, 1024), dtype=bool) mask[300, 400] = True mask[700, 200] = True grown3 = dilate3(mask) # 3×3 dilation: each True pixel grows by 1 pixel grown5 = dilate5(mask, niter=2) # 5×5 dilation, 2 iterations print(grown3.sum()) # 9 (3×3 neighbourhood around each seed pixel) print(grown5.sum()) # ~84 (two passes with the 5×5 kernel) ``` ``` -------------------------------- ### Detect and mask saturated stars with update_mask Source: https://context7.com/astropy/astroscrappy/llms.txt Identifies and masks saturated pixels that are part of large structures, useful for standalone saturation detection. This function is called internally by `detect_cosmics`. ```python import numpy as np from astroscrappy import update_mask data = np.random.normal(1000, 30, (2048, 2048)).astype(np.float32) # Inject a bright saturated star data[512:560, 512:560] = 70000.0 mask = np.zeros((2048, 2048), dtype=np.uint8) update_mask(data, mask, satlevel=65536.0, sepmed=True) print(f"Masked pixels: {mask.sum()}") # Masked pixels: ~2500 (dilated region around saturated star) ``` -------------------------------- ### update_mask Source: https://context7.com/astropy/astroscrappy/llms.txt Detects and masks saturated stars by identifying pixels above a saturation level that are part of symmetric structures, then dilating the mask. ```APIDOC ## update_mask ### Description Finds saturated pixels (≥ `satlevel`) that are part of large symmetric structures (i.e., stellar cores rather than isolated hot pixels) using a median filter, dilates the resulting mask, and merges it with any supplied bad-pixel mask. This function is called internally by `detect_cosmics` but is also available for standalone use. ### Parameters - **data** (numpy.ndarray) - Input image data. - **mask** (numpy.ndarray) - Input mask array to be updated. - **satlevel** (float) - Saturation level. - **sepmed** (bool, optional) - If True, use a separable median filter. Defaults to True. ### Returns - None. The input `mask` array is modified in-place. ### Example ```python import numpy as np from astroscrappy import update_mask data = np.random.normal(1000, 30, (2048, 2048)).astype(np.float32) # Inject a bright saturated star data[512:560, 512:560] = 70000.0 mask = np.zeros((2048, 2048), dtype=np.uint8) update_mask(data, mask, satlevel=65536.0, sepmed=True) print(f"Masked pixels: {mask.sum()}") # Masked pixels: ~2500 (dilated region around saturated star) ``` ``` -------------------------------- ### convolve Source: https://context7.com/astropy/astroscrappy/llms.txt Convolves a 2-D float32 array with an arbitrary float32 kernel. This function is used internally for building matched-filter images. ```APIDOC ## convolve — General 2-D convolution ### Description Convolves a 2-D `float32` array with an arbitrary `float32` kernel. Used internally in `detect_cosmics` when `fsmode='convolve'` to build the matched-filter fine-structure image. Both arrays must be C-contiguous. ### Parameters - **image** (numpy.ndarray) - The 2-D `float32` input array. - **kernel** (numpy.ndarray) - The 2-D `float32` convolution kernel. ### Returns - **smoothed** (numpy.ndarray) - The convolved 2-D `float32` array. ### Example ```python import numpy as np from astroscrappy.utils import convolve from astroscrappy import gausskernel image = np.random.normal(500, 20, (1024, 1024)).astype(np.float32) kernel = gausskernel(psffwhm=2.5, kernsize=7) smoothed = convolve(image, kernel) print(smoothed.shape, smoothed.dtype) # (1024, 1024) float32 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.