sourcefinder.measure ==================== .. py:module:: sourcefinder.measure .. autoapi-nested-parse:: Source measuring routines. .. !! processed by numpydoc !! Attributes ---------- .. autoapisummary:: sourcefinder.measure.FIT_PARAMS sourcefinder.measure.sigma_to_ax Classes ------- .. autoapisummary:: sourcefinder.measure.MomentParam Functions --------- .. autoapisummary:: sourcefinder.measure.find_true_peak sourcefinder.measure.fitgaussian sourcefinder.measure.goodness_of_fit sourcefinder.measure.moments sourcefinder.measure.moments_enhanced Module Contents --------------- .. py:class:: MomentParam Bases: :py:obj:`str`, :py:obj:`enum.Enum` str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. .. !! processed by numpydoc !! .. py:attribute:: FLUX :value: 'flux' .. py:attribute:: PEAK :value: 'peak' .. py:attribute:: SEMIMAJOR :value: 'semimajor' .. py:attribute:: SEMIMINOR :value: 'semiminor' .. py:attribute:: THETA :value: 'theta' .. py:attribute:: XBAR :value: 'xbar' .. py:attribute:: YBAR :value: 'ybar' .. py:function:: find_true_peak(peak, T, epsilon, msq, maxpix) This function represents equation 2.67 from Spreeuw's thesis. .. !! processed by numpydoc !! .. py:function:: fitgaussian(pixels, params, fixed=None, max_nfev=None, bounds={}) Calculate source positional values by fitting a 2D Gaussian. :Parameters: **pixels** : np.ma.MaskedArray or np.ndarray Pixel values (with bad pixels masked) **params** : dict Initial fit parameters (possibly estimated using the moments() function) **fixed** : dict, default: None Parameters & their values to be kept frozen (ie, not fitted) **max_nfev** : int, default: None Maximum number of calls to the error function **bounds** : dict, default: {} Can be a dict such as the extract.ParamSet().bounds attribute generated by the extract.ParamSet().compute_bounds method, but any dict with keys from FIT_PARAMS and (lower_bound, upper_bound, bool) tuples as values will do. The boolean argument accommodates for loosening a bound when a fit becomes unfeasible because of the bound, see the scipy.optimize.Bounds documentation and source code for background. :Returns: dict peak, total, x barycenter, y barycenter, semimajor, semiminor, theta (radians) :Raises: exceptions.ValueError In case of a bad fit. .. rubric:: Notes Perform a least squares fit to an elliptical Gaussian. If a dict called fixed is passed in, then parameters specified within the dict with the same keys as in FIT_PARAMS will be "locked" in the fitting process. .. !! processed by numpydoc !! .. py:function:: goodness_of_fit(masked_residuals, noise, correlation_lengths) Calculate the goodness-of-fit values. :Parameters: **masked_residuals** : np.ma.MaskedArray The pixel-residuals from the fit. **noise** : float or np.ma.MaskedArray An estimate of the noise level. Can also be a masked numpy array matching the data for per-pixel noise estimates. **correlation_lengths** : tuple of two floats Distance along the semimajor and semiminor axes of the clean beam beyond which noise is assumed uncorrelated. Some background: Aperture synthesis imaging yields noise that is partially correlated over the entire image. This has a considerable effect on error estimates. We approximate this by considering all noise within the correlation length completely correlated and beyond that completely uncorrelated. :Returns: chisq: float .. **reduced_chisq** : float .. .. rubric:: Notes We do not use the standard chi-squared formula for calculating these goodness-of-fit values, see . These values are related to, but not quite the same as reduced chi-squared. The reduced chi-squared is statistically invalid for a Gaussian model from the outset (see ). We attempt to provide a resolution-independent estimate of goodness-of-fit ('reduced chi-squared') by estimating the number of independent pixels in the data, that we have used for fitting the Gaussian model, to normalize the chi-squared value. However, this will sometimes imply that we are fitting a fractional number of datapoints less than 1! As a result, it doesn't really make sense to try and apply the 'degrees-of-freedom' correction, as this would likely result in a negative ``reduced_chisq`` value. .. !! processed by numpydoc !! .. py:function:: moments(data, fudge_max_pix_factor, beam, beamsize, threshold=0) Calculate source positional values using moments. The first moment of the distribution is the barycenter of an ellipse. The second moments are used to estimate the rotation angle and the length of the axes. :Parameters: **data** : np.ma.MaskedArray or np.ndarray A rectangular region of 2D observational image data, typically with the mean background subtracted. Units: spectral brightness, usually Jy/beam. **fudge_max_pix_factor** : float Correct for the underestimation of the peak by taking the maximum pixel value. This factor is slightly larger than 1. **beam** : 3-tuple tuple of 3 floats: (semimajor axis, semiminor axis, theta). The axes are in units of pixels and theta, the position angle of the major axis wrt the positive y-axis, is in radians. **beamsize** : float The FWHM size of the clean beam in square pixels. **threshold** : float, default: 0 Source parameters like the semimajor and semiminor axes derived from moments can be underestimated if one does not take account of the threshold that was used to segment the source islands. This threshold is typically the value of the analysisthresholdmap at the position of the island pixel with the highest spectral brightness. :Returns: dict Dictionary with seven items, i.e. peak spectral brightness, flux density, barycenter position in x and y, i.e. in pixel coordinates, semimajor and semiminor axes in pixel units and the position angle of the semi-major axis measured east from local north in radians. :Raises: exceptions.ValueError If input contains NaN values. .. !! processed by numpydoc !! .. py:function:: moments_enhanced(source_island, noise_island, chunkpos, posx, posy, min_width, no_pixels, threshold, noise, maxpos, maxi, fudge_max_pix_factor, beam, beamsize, force_beam, correlation_lengths, clean_bias_error, frac_flux_cal_error, Gaussian_islands_map, Gaussian_residuals_map, dummy, computed_moments, significance, chisq, reduced_chisq) Calculate source properties using moments. Vectorized using the `guvectorize` decorator. Also calculates the signal-to-noise ratio of detections, chi-squared and reduced chi-squared statistics, and fills in maps with Gaussian islands and Gaussian residuals. Uses the first moments of the distribution to determine the barycenter of an ellipse, while the second moments estimate rotation angle and axis lengths. :Parameters: **source_island** : np.ndarray Selected from the 2D image data by taking pixels above the analysis threshold, with its peak above the detection threshold. Flattened to a 1D ndarray. Units: spectral brightness, typically Jy/beam. **noise_island** : np.ndarray Pixel values selected from the 2D RMS noise map at the positions of the island. Flattened to a 1D ndarray. Units: spectral brightness, typically Jy/beam. **chunkpos** : np.ndarray Index array of length 2 denoting the position of the top-left corner of the rectangular slice encompassing the island, relative to the top-left corner of the image. **posx** : np.ndarray Row indices of the pixels in `source_island` relative to the top-left corner of the rectangular slice encompassing the island. The top-left corner corresponds to `posx = 0`. Derived from the 2D image data. **posy** : np.ndarray Column indices of the pixels in `source_island` relative to the top-left corner of the rectangular slice encompassing the island. The top-left corner corresponds to `posy = 0`. Derived from the 2D image data. **min_width** : int Minimum width (in pixels) of the island, derived as the lesser of its maximum width along the x and y axes. **no_pixels** : int Number of pixels that constitute the island. **threshold** : float Threshold used for segmenting source islands, which can affect parameters like semimajor and semiminor axes. A higher threshold may lead to a larger underestimate of the Gaussian axes. If the analysis threshold is known, this underestimate can be corrected. Units: spectral brightness, typically Jy/beam. **noise** : float Local noise, i.e., the standard deviation of the background pixel values at the position of the island's peak pixel value. Units: spectral brightness, typically Jy/beam. **maxpos** : np.ndarray with int32 as dtype and length 2 The position of the maximum pixel value within the island, relative to the top-left corner of the rectangular slice encompassing the island. Units: pixels. **maxi** : float Peak pixel value within the island. Pixel values represent spectral brightness (typically in Jy/beam). For clarity: source_island[maxpos] == maxi. **fudge_max_pix_factor** : float Correction factor for underestimation of the peak by considering the maximum pixel value. **beam** : np.ndarray Array of three floats: (semimajor axis, semiminor axis, theta). The axes are in units of pixels and theta, the position angle of the major axis wrt the positive y-axis, is in radians. **beamsize** : float FWHM size of the clean beam. Units: pixels. **force_beam** : int If 1, the restoring beam is used to derive the peak spectral brightnesses of the sources, see equation 2.66 of Spreeuw's (2010) thesis. The sources are then assumed to be unresolved and their shapes are set equal to the restoring beam. If 0, the peak spectral brightnesses are derived using equation 2.67 of that thesis and enhanced moments are used to derive the elliptical Gaussian axes. **correlation_lengths** : np.ndarray Array of two floats describing distances along the semi-major and semi-minor axes of the clean beam beyond which noise is assumed uncorrelated. Units: pixels. Some background: Aperture synthesis imaging yields noise that is partially correlated over the entire image. This has a considerable effect on error estimates. All noise within the correlation length is approximated as completely correlated, while noise beyond is considered uncorrelated. **clean_bias_error** : float Extra source of error based on Condon (PASP 109, 166, 1997) formulae. **frac_flux_cal_error** : float Extra source of error based on Condon (PASP 109, 166, 1997) formulae. **Gaussian_islands_map** : np.ndarray Initially a 2D np.float32 array filled with zeros, same shape as the astronomical image being processed. Computed Gaussian islands are added to this array at pixel positions above the analysis threshold. **Gaussian_residuals_map** : np.ndarray Initially a 2D np.float32 array filled with zeros, same shape as `Gaussian_islands_map`. Residuals are computed by subtracting `Gaussian_islands_map` from the input image data. **dummy** : np.ndarray Empty array matching the shape of `computed_moments`, required due to limitations in `guvectorize`. **computed_moments** : np.ndarray Array of shape (10, 2) containing moments such as peak spectral brightness (Jy/beam), flux density (Jy), barycenter (pixels), semi-major and semi-minor axes (pixels), and position angle (radians), along with corresponding errors. **significance** : float The significance of a detection is defined as the maximum signal-to-noise ratio across the island. Often this will be the ratio of the maximum pixel value within the source island divided by the noise at that position. But for extended sources, the noise can perhaps decrease away from the position of the peak spectral brightness more steeply than the source spectral brightness, and the maximum signal-to-noise ratio can be found at a different position. **chisq** : float Chi-squared statistic indicating goodness-of-fit, derived in the same way as in the `measuring.goodness_of_fit` method. **reduced_chisq** : float Reduced chi-squared statistic indicating goodness-of-fit, derived in the same way as in the `measuring.goodness_of_fit` method. :Returns: None Outputs are written to `Gaussian_islands_map`, `Gaussian_residuals_map`, `computed_moments`, `significance`, `chisq`, and `reduced_chisq`. :Raises: ValueError If input contains NaN values. .. !! processed by numpydoc !! .. py:data:: FIT_PARAMS .. py:data:: sigma_to_ax