repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
astropy/photutils
photutils/utils/convolution.py
filter_data
def filter_data(data, kernel, mode='constant', fill_value=0.0, check_normalization=False): """ Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like The 2D array of the image. kernel : array-like (2D) or `~astropy.convolution.Kernel2D` The 2D kernel used to filter the input ``data``. Filtering the ``data`` will smooth the noise and maximize detectability of objects with a shape similar to the kernel. mode : {'constant', 'reflect', 'nearest', 'mirror', 'wrap'}, optional The ``mode`` determines how the array borders are handled. For the ``'constant'`` mode, values outside the array borders are set to ``fill_value``. The default is ``'constant'``. fill_value : scalar, optional Value to fill data values beyond the array borders if ``mode`` is ``'constant'``. The default is ``0.0``. check_normalization : bool, optional If `True` then a warning will be issued if the kernel is not normalized to 1. """ from scipy import ndimage if kernel is not None: if isinstance(kernel, Kernel2D): kernel_array = kernel.array else: kernel_array = kernel if check_normalization: if not np.allclose(np.sum(kernel_array), 1.0): warnings.warn('The kernel is not normalized.', AstropyUserWarning) # NOTE: astropy.convolution.convolve fails with zero-sum # kernels (used in findstars) (cf. astropy #1647) # NOTE: if data is int and kernel is float, ndimage.convolve # will return an int image - here we make the data float so # that a float image is always returned return ndimage.convolve(data.astype(float), kernel_array, mode=mode, cval=fill_value) else: return data
python
def filter_data(data, kernel, mode='constant', fill_value=0.0, check_normalization=False): """ Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like The 2D array of the image. kernel : array-like (2D) or `~astropy.convolution.Kernel2D` The 2D kernel used to filter the input ``data``. Filtering the ``data`` will smooth the noise and maximize detectability of objects with a shape similar to the kernel. mode : {'constant', 'reflect', 'nearest', 'mirror', 'wrap'}, optional The ``mode`` determines how the array borders are handled. For the ``'constant'`` mode, values outside the array borders are set to ``fill_value``. The default is ``'constant'``. fill_value : scalar, optional Value to fill data values beyond the array borders if ``mode`` is ``'constant'``. The default is ``0.0``. check_normalization : bool, optional If `True` then a warning will be issued if the kernel is not normalized to 1. """ from scipy import ndimage if kernel is not None: if isinstance(kernel, Kernel2D): kernel_array = kernel.array else: kernel_array = kernel if check_normalization: if not np.allclose(np.sum(kernel_array), 1.0): warnings.warn('The kernel is not normalized.', AstropyUserWarning) # NOTE: astropy.convolution.convolve fails with zero-sum # kernels (used in findstars) (cf. astropy #1647) # NOTE: if data is int and kernel is float, ndimage.convolve # will return an int image - here we make the data float so # that a float image is always returned return ndimage.convolve(data.astype(float), kernel_array, mode=mode, cval=fill_value) else: return data
[ "def", "filter_data", "(", "data", ",", "kernel", ",", "mode", "=", "'constant'", ",", "fill_value", "=", "0.0", ",", "check_normalization", "=", "False", ")", ":", "from", "scipy", "import", "ndimage", "if", "kernel", "is", "not", "None", ":", "if", "isinstance", "(", "kernel", ",", "Kernel2D", ")", ":", "kernel_array", "=", "kernel", ".", "array", "else", ":", "kernel_array", "=", "kernel", "if", "check_normalization", ":", "if", "not", "np", ".", "allclose", "(", "np", ".", "sum", "(", "kernel_array", ")", ",", "1.0", ")", ":", "warnings", ".", "warn", "(", "'The kernel is not normalized.'", ",", "AstropyUserWarning", ")", "# NOTE: astropy.convolution.convolve fails with zero-sum", "# kernels (used in findstars) (cf. astropy #1647)", "# NOTE: if data is int and kernel is float, ndimage.convolve", "# will return an int image - here we make the data float so", "# that a float image is always returned", "return", "ndimage", ".", "convolve", "(", "data", ".", "astype", "(", "float", ")", ",", "kernel_array", ",", "mode", "=", "mode", ",", "cval", "=", "fill_value", ")", "else", ":", "return", "data" ]
Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like The 2D array of the image. kernel : array-like (2D) or `~astropy.convolution.Kernel2D` The 2D kernel used to filter the input ``data``. Filtering the ``data`` will smooth the noise and maximize detectability of objects with a shape similar to the kernel. mode : {'constant', 'reflect', 'nearest', 'mirror', 'wrap'}, optional The ``mode`` determines how the array borders are handled. For the ``'constant'`` mode, values outside the array borders are set to ``fill_value``. The default is ``'constant'``. fill_value : scalar, optional Value to fill data values beyond the array borders if ``mode`` is ``'constant'``. The default is ``0.0``. check_normalization : bool, optional If `True` then a warning will be issued if the kernel is not normalized to 1.
[ "Convolve", "a", "2D", "image", "with", "a", "2D", "kernel", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/convolution.py#L13-L66
train
astropy/photutils
photutils/psf/utils.py
prepare_psf_model
def prepare_psf_model(psfmodel, xname=None, yname=None, fluxname=None, renormalize_psf=True): """ Convert a 2D PSF model to one suitable for use with `BasicPSFPhotometry` or its subclasses. The resulting model may be a composite model, but should have only the x, y, and flux related parameters un-fixed. Parameters ---------- psfmodel : a 2D model The model to assume as representative of the PSF. xname : str or None The name of the ``psfmodel`` parameter that corresponds to the x-axis center of the PSF. If None, the model will be assumed to be centered at x=0, and a new parameter will be added for the offset. yname : str or None The name of the ``psfmodel`` parameter that corresponds to the y-axis center of the PSF. If None, the model will be assumed to be centered at y=0, and a new parameter will be added for the offset. fluxname : str or None The name of the ``psfmodel`` parameter that corresponds to the total flux of the star. If None, a scaling factor will be added to the model. renormalize_psf : bool If True, the model will be integrated from -inf to inf and re-scaled so that the total integrates to 1. Note that this renormalization only occurs *once*, so if the total flux of ``psfmodel`` depends on position, this will *not* be correct. Returns ------- outmod : a model A new model ready to be passed into `BasicPSFPhotometry` or its subclasses. """ if xname is None: xinmod = models.Shift(0, name='x_offset') xname = 'offset_0' else: xinmod = models.Identity(1) xname = xname + '_2' xinmod.fittable = True if yname is None: yinmod = models.Shift(0, name='y_offset') yname = 'offset_1' else: yinmod = models.Identity(1) yname = yname + '_2' yinmod.fittable = True outmod = (xinmod & yinmod) | psfmodel if fluxname is None: outmod = outmod * models.Const2D(1, name='flux_scaling') fluxname = 'amplitude_3' else: fluxname = fluxname + '_2' if renormalize_psf: # we do the import here because other machinery works w/o scipy from scipy import integrate integrand = integrate.dblquad(psfmodel, -np.inf, np.inf, lambda x: -np.inf, lambda x: np.inf)[0] normmod = models.Const2D(1./integrand, name='renormalize_scaling') outmod = outmod * normmod # final setup of the output model - fix all the non-offset/scale # parameters for pnm in outmod.param_names: outmod.fixed[pnm] = pnm not in (xname, yname, fluxname) # and set the names so that BasicPSFPhotometry knows what to do outmod.xname = xname outmod.yname = yname outmod.fluxname = fluxname # now some convenience aliases if reasonable outmod.psfmodel = outmod[2] if 'x_0' not in outmod.param_names and 'y_0' not in outmod.param_names: outmod.x_0 = getattr(outmod, xname) outmod.y_0 = getattr(outmod, yname) if 'flux' not in outmod.param_names: outmod.flux = getattr(outmod, fluxname) return outmod
python
def prepare_psf_model(psfmodel, xname=None, yname=None, fluxname=None, renormalize_psf=True): """ Convert a 2D PSF model to one suitable for use with `BasicPSFPhotometry` or its subclasses. The resulting model may be a composite model, but should have only the x, y, and flux related parameters un-fixed. Parameters ---------- psfmodel : a 2D model The model to assume as representative of the PSF. xname : str or None The name of the ``psfmodel`` parameter that corresponds to the x-axis center of the PSF. If None, the model will be assumed to be centered at x=0, and a new parameter will be added for the offset. yname : str or None The name of the ``psfmodel`` parameter that corresponds to the y-axis center of the PSF. If None, the model will be assumed to be centered at y=0, and a new parameter will be added for the offset. fluxname : str or None The name of the ``psfmodel`` parameter that corresponds to the total flux of the star. If None, a scaling factor will be added to the model. renormalize_psf : bool If True, the model will be integrated from -inf to inf and re-scaled so that the total integrates to 1. Note that this renormalization only occurs *once*, so if the total flux of ``psfmodel`` depends on position, this will *not* be correct. Returns ------- outmod : a model A new model ready to be passed into `BasicPSFPhotometry` or its subclasses. """ if xname is None: xinmod = models.Shift(0, name='x_offset') xname = 'offset_0' else: xinmod = models.Identity(1) xname = xname + '_2' xinmod.fittable = True if yname is None: yinmod = models.Shift(0, name='y_offset') yname = 'offset_1' else: yinmod = models.Identity(1) yname = yname + '_2' yinmod.fittable = True outmod = (xinmod & yinmod) | psfmodel if fluxname is None: outmod = outmod * models.Const2D(1, name='flux_scaling') fluxname = 'amplitude_3' else: fluxname = fluxname + '_2' if renormalize_psf: # we do the import here because other machinery works w/o scipy from scipy import integrate integrand = integrate.dblquad(psfmodel, -np.inf, np.inf, lambda x: -np.inf, lambda x: np.inf)[0] normmod = models.Const2D(1./integrand, name='renormalize_scaling') outmod = outmod * normmod # final setup of the output model - fix all the non-offset/scale # parameters for pnm in outmod.param_names: outmod.fixed[pnm] = pnm not in (xname, yname, fluxname) # and set the names so that BasicPSFPhotometry knows what to do outmod.xname = xname outmod.yname = yname outmod.fluxname = fluxname # now some convenience aliases if reasonable outmod.psfmodel = outmod[2] if 'x_0' not in outmod.param_names and 'y_0' not in outmod.param_names: outmod.x_0 = getattr(outmod, xname) outmod.y_0 = getattr(outmod, yname) if 'flux' not in outmod.param_names: outmod.flux = getattr(outmod, fluxname) return outmod
[ "def", "prepare_psf_model", "(", "psfmodel", ",", "xname", "=", "None", ",", "yname", "=", "None", ",", "fluxname", "=", "None", ",", "renormalize_psf", "=", "True", ")", ":", "if", "xname", "is", "None", ":", "xinmod", "=", "models", ".", "Shift", "(", "0", ",", "name", "=", "'x_offset'", ")", "xname", "=", "'offset_0'", "else", ":", "xinmod", "=", "models", ".", "Identity", "(", "1", ")", "xname", "=", "xname", "+", "'_2'", "xinmod", ".", "fittable", "=", "True", "if", "yname", "is", "None", ":", "yinmod", "=", "models", ".", "Shift", "(", "0", ",", "name", "=", "'y_offset'", ")", "yname", "=", "'offset_1'", "else", ":", "yinmod", "=", "models", ".", "Identity", "(", "1", ")", "yname", "=", "yname", "+", "'_2'", "yinmod", ".", "fittable", "=", "True", "outmod", "=", "(", "xinmod", "&", "yinmod", ")", "|", "psfmodel", "if", "fluxname", "is", "None", ":", "outmod", "=", "outmod", "*", "models", ".", "Const2D", "(", "1", ",", "name", "=", "'flux_scaling'", ")", "fluxname", "=", "'amplitude_3'", "else", ":", "fluxname", "=", "fluxname", "+", "'_2'", "if", "renormalize_psf", ":", "# we do the import here because other machinery works w/o scipy", "from", "scipy", "import", "integrate", "integrand", "=", "integrate", ".", "dblquad", "(", "psfmodel", ",", "-", "np", ".", "inf", ",", "np", ".", "inf", ",", "lambda", "x", ":", "-", "np", ".", "inf", ",", "lambda", "x", ":", "np", ".", "inf", ")", "[", "0", "]", "normmod", "=", "models", ".", "Const2D", "(", "1.", "/", "integrand", ",", "name", "=", "'renormalize_scaling'", ")", "outmod", "=", "outmod", "*", "normmod", "# final setup of the output model - fix all the non-offset/scale", "# parameters", "for", "pnm", "in", "outmod", ".", "param_names", ":", "outmod", ".", "fixed", "[", "pnm", "]", "=", "pnm", "not", "in", "(", "xname", ",", "yname", ",", "fluxname", ")", "# and set the names so that BasicPSFPhotometry knows what to do", "outmod", ".", "xname", "=", "xname", "outmod", ".", "yname", "=", "yname", "outmod", ".", "fluxname", "=", "fluxname", "# now some convenience aliases if reasonable", "outmod", ".", "psfmodel", "=", "outmod", "[", "2", "]", "if", "'x_0'", "not", "in", "outmod", ".", "param_names", "and", "'y_0'", "not", "in", "outmod", ".", "param_names", ":", "outmod", ".", "x_0", "=", "getattr", "(", "outmod", ",", "xname", ")", "outmod", ".", "y_0", "=", "getattr", "(", "outmod", ",", "yname", ")", "if", "'flux'", "not", "in", "outmod", ".", "param_names", ":", "outmod", ".", "flux", "=", "getattr", "(", "outmod", ",", "fluxname", ")", "return", "outmod" ]
Convert a 2D PSF model to one suitable for use with `BasicPSFPhotometry` or its subclasses. The resulting model may be a composite model, but should have only the x, y, and flux related parameters un-fixed. Parameters ---------- psfmodel : a 2D model The model to assume as representative of the PSF. xname : str or None The name of the ``psfmodel`` parameter that corresponds to the x-axis center of the PSF. If None, the model will be assumed to be centered at x=0, and a new parameter will be added for the offset. yname : str or None The name of the ``psfmodel`` parameter that corresponds to the y-axis center of the PSF. If None, the model will be assumed to be centered at y=0, and a new parameter will be added for the offset. fluxname : str or None The name of the ``psfmodel`` parameter that corresponds to the total flux of the star. If None, a scaling factor will be added to the model. renormalize_psf : bool If True, the model will be integrated from -inf to inf and re-scaled so that the total integrates to 1. Note that this renormalization only occurs *once*, so if the total flux of ``psfmodel`` depends on position, this will *not* be correct. Returns ------- outmod : a model A new model ready to be passed into `BasicPSFPhotometry` or its subclasses.
[ "Convert", "a", "2D", "PSF", "model", "to", "one", "suitable", "for", "use", "with", "BasicPSFPhotometry", "or", "its", "subclasses", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/utils.py#L15-L106
train
astropy/photutils
photutils/psf/utils.py
get_grouped_psf_model
def get_grouped_psf_model(template_psf_model, star_group, pars_to_set): """ Construct a joint PSF model which consists of a sum of PSF's templated on a specific model, but whose parameters are given by a table of objects. Parameters ---------- template_psf_model : `astropy.modeling.Fittable2DModel` instance The model to use for *individual* objects. Must have parameters named ``x_0``, ``y_0``, and ``flux``. star_group : `~astropy.table.Table` Table of stars for which the compound PSF will be constructed. It must have columns named ``x_0``, ``y_0``, and ``flux_0``. Returns ------- group_psf An `astropy.modeling` ``CompoundModel`` instance which is a sum of the given PSF models. """ group_psf = None for star in star_group: psf_to_add = template_psf_model.copy() for param_tab_name, param_name in pars_to_set.items(): setattr(psf_to_add, param_name, star[param_tab_name]) if group_psf is None: # this is the first one only group_psf = psf_to_add else: group_psf += psf_to_add return group_psf
python
def get_grouped_psf_model(template_psf_model, star_group, pars_to_set): """ Construct a joint PSF model which consists of a sum of PSF's templated on a specific model, but whose parameters are given by a table of objects. Parameters ---------- template_psf_model : `astropy.modeling.Fittable2DModel` instance The model to use for *individual* objects. Must have parameters named ``x_0``, ``y_0``, and ``flux``. star_group : `~astropy.table.Table` Table of stars for which the compound PSF will be constructed. It must have columns named ``x_0``, ``y_0``, and ``flux_0``. Returns ------- group_psf An `astropy.modeling` ``CompoundModel`` instance which is a sum of the given PSF models. """ group_psf = None for star in star_group: psf_to_add = template_psf_model.copy() for param_tab_name, param_name in pars_to_set.items(): setattr(psf_to_add, param_name, star[param_tab_name]) if group_psf is None: # this is the first one only group_psf = psf_to_add else: group_psf += psf_to_add return group_psf
[ "def", "get_grouped_psf_model", "(", "template_psf_model", ",", "star_group", ",", "pars_to_set", ")", ":", "group_psf", "=", "None", "for", "star", "in", "star_group", ":", "psf_to_add", "=", "template_psf_model", ".", "copy", "(", ")", "for", "param_tab_name", ",", "param_name", "in", "pars_to_set", ".", "items", "(", ")", ":", "setattr", "(", "psf_to_add", ",", "param_name", ",", "star", "[", "param_tab_name", "]", ")", "if", "group_psf", "is", "None", ":", "# this is the first one only", "group_psf", "=", "psf_to_add", "else", ":", "group_psf", "+=", "psf_to_add", "return", "group_psf" ]
Construct a joint PSF model which consists of a sum of PSF's templated on a specific model, but whose parameters are given by a table of objects. Parameters ---------- template_psf_model : `astropy.modeling.Fittable2DModel` instance The model to use for *individual* objects. Must have parameters named ``x_0``, ``y_0``, and ``flux``. star_group : `~astropy.table.Table` Table of stars for which the compound PSF will be constructed. It must have columns named ``x_0``, ``y_0``, and ``flux_0``. Returns ------- group_psf An `astropy.modeling` ``CompoundModel`` instance which is a sum of the given PSF models.
[ "Construct", "a", "joint", "PSF", "model", "which", "consists", "of", "a", "sum", "of", "PSF", "s", "templated", "on", "a", "specific", "model", "but", "whose", "parameters", "are", "given", "by", "a", "table", "of", "objects", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/utils.py#L109-L143
train
astropy/photutils
photutils/psf/utils.py
_call_fitter
def _call_fitter(fitter, psf, x, y, data, weights): """ Not all fitters have to support a weight array. This function includes the weight in the fitter call only if really needed. """ if np.all(weights == 1.): return fitter(psf, x, y, data) else: return fitter(psf, x, y, data, weights=weights)
python
def _call_fitter(fitter, psf, x, y, data, weights): """ Not all fitters have to support a weight array. This function includes the weight in the fitter call only if really needed. """ if np.all(weights == 1.): return fitter(psf, x, y, data) else: return fitter(psf, x, y, data, weights=weights)
[ "def", "_call_fitter", "(", "fitter", ",", "psf", ",", "x", ",", "y", ",", "data", ",", "weights", ")", ":", "if", "np", ".", "all", "(", "weights", "==", "1.", ")", ":", "return", "fitter", "(", "psf", ",", "x", ",", "y", ",", "data", ")", "else", ":", "return", "fitter", "(", "psf", ",", "x", ",", "y", ",", "data", ",", "weights", "=", "weights", ")" ]
Not all fitters have to support a weight array. This function includes the weight in the fitter call only if really needed.
[ "Not", "all", "fitters", "have", "to", "support", "a", "weight", "array", ".", "This", "function", "includes", "the", "weight", "in", "the", "fitter", "call", "only", "if", "really", "needed", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/utils.py#L178-L187
train
astropy/photutils
photutils/detection/core.py
detect_threshold
def detect_threshold(data, snr, background=None, error=None, mask=None, mask_value=None, sigclip_sigma=3.0, sigclip_iters=None): """ Calculate a pixel-wise threshold image that can be used to detect sources. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. background : float or array_like, optional The background value(s) of the input ``data``. ``background`` may either be a scalar value or a 2D image with the same shape as the input ``data``. If the input ``data`` has been background-subtracted, then set ``background`` to ``0.0``. If `None`, then a scalar background value will be estimated using sigma-clipped statistics. error : float or array_like, optional The Gaussian 1-sigma standard deviation of the background noise in ``data``. ``error`` should include all sources of "background" error, but *exclude* the Poisson error of the sources. If ``error`` is a 2D image, then it should represent the 1-sigma background error in each pixel of ``data``. If `None`, then a scalar background rms value will be estimated using sigma-clipped statistics. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. Returns ------- threshold : 2D `~numpy.ndarray` A 2D image with the same shape as ``data`` containing the pixel-wise threshold values. See Also -------- :func:`photutils.segmentation.detect_sources` Notes ----- The ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` inputs are used only if it is necessary to estimate ``background`` or ``error`` using sigma-clipped background statistics. If ``background`` and ``error`` are both input, then ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` are ignored. """ if background is None or error is None: if astropy_version < '3.1': data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, iters=sigclip_iters) else: data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, maxiters=sigclip_iters) bkgrd_image = np.zeros_like(data) + data_mean bkgrdrms_image = np.zeros_like(data) + data_std if background is None: background = bkgrd_image else: if np.isscalar(background): background = np.zeros_like(data) + background else: if background.shape != data.shape: raise ValueError('If input background is 2D, then it ' 'must have the same shape as the input ' 'data.') if error is None: error = bkgrdrms_image else: if np.isscalar(error): error = np.zeros_like(data) + error else: if error.shape != data.shape: raise ValueError('If input error is 2D, then it ' 'must have the same shape as the input ' 'data.') return background + (error * snr)
python
def detect_threshold(data, snr, background=None, error=None, mask=None, mask_value=None, sigclip_sigma=3.0, sigclip_iters=None): """ Calculate a pixel-wise threshold image that can be used to detect sources. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. background : float or array_like, optional The background value(s) of the input ``data``. ``background`` may either be a scalar value or a 2D image with the same shape as the input ``data``. If the input ``data`` has been background-subtracted, then set ``background`` to ``0.0``. If `None`, then a scalar background value will be estimated using sigma-clipped statistics. error : float or array_like, optional The Gaussian 1-sigma standard deviation of the background noise in ``data``. ``error`` should include all sources of "background" error, but *exclude* the Poisson error of the sources. If ``error`` is a 2D image, then it should represent the 1-sigma background error in each pixel of ``data``. If `None`, then a scalar background rms value will be estimated using sigma-clipped statistics. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. Returns ------- threshold : 2D `~numpy.ndarray` A 2D image with the same shape as ``data`` containing the pixel-wise threshold values. See Also -------- :func:`photutils.segmentation.detect_sources` Notes ----- The ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` inputs are used only if it is necessary to estimate ``background`` or ``error`` using sigma-clipped background statistics. If ``background`` and ``error`` are both input, then ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` are ignored. """ if background is None or error is None: if astropy_version < '3.1': data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, iters=sigclip_iters) else: data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, maxiters=sigclip_iters) bkgrd_image = np.zeros_like(data) + data_mean bkgrdrms_image = np.zeros_like(data) + data_std if background is None: background = bkgrd_image else: if np.isscalar(background): background = np.zeros_like(data) + background else: if background.shape != data.shape: raise ValueError('If input background is 2D, then it ' 'must have the same shape as the input ' 'data.') if error is None: error = bkgrdrms_image else: if np.isscalar(error): error = np.zeros_like(data) + error else: if error.shape != data.shape: raise ValueError('If input error is 2D, then it ' 'must have the same shape as the input ' 'data.') return background + (error * snr)
[ "def", "detect_threshold", "(", "data", ",", "snr", ",", "background", "=", "None", ",", "error", "=", "None", ",", "mask", "=", "None", ",", "mask_value", "=", "None", ",", "sigclip_sigma", "=", "3.0", ",", "sigclip_iters", "=", "None", ")", ":", "if", "background", "is", "None", "or", "error", "is", "None", ":", "if", "astropy_version", "<", "'3.1'", ":", "data_mean", ",", "data_median", ",", "data_std", "=", "sigma_clipped_stats", "(", "data", ",", "mask", "=", "mask", ",", "mask_value", "=", "mask_value", ",", "sigma", "=", "sigclip_sigma", ",", "iters", "=", "sigclip_iters", ")", "else", ":", "data_mean", ",", "data_median", ",", "data_std", "=", "sigma_clipped_stats", "(", "data", ",", "mask", "=", "mask", ",", "mask_value", "=", "mask_value", ",", "sigma", "=", "sigclip_sigma", ",", "maxiters", "=", "sigclip_iters", ")", "bkgrd_image", "=", "np", ".", "zeros_like", "(", "data", ")", "+", "data_mean", "bkgrdrms_image", "=", "np", ".", "zeros_like", "(", "data", ")", "+", "data_std", "if", "background", "is", "None", ":", "background", "=", "bkgrd_image", "else", ":", "if", "np", ".", "isscalar", "(", "background", ")", ":", "background", "=", "np", ".", "zeros_like", "(", "data", ")", "+", "background", "else", ":", "if", "background", ".", "shape", "!=", "data", ".", "shape", ":", "raise", "ValueError", "(", "'If input background is 2D, then it '", "'must have the same shape as the input '", "'data.'", ")", "if", "error", "is", "None", ":", "error", "=", "bkgrdrms_image", "else", ":", "if", "np", ".", "isscalar", "(", "error", ")", ":", "error", "=", "np", ".", "zeros_like", "(", "data", ")", "+", "error", "else", ":", "if", "error", ".", "shape", "!=", "data", ".", "shape", ":", "raise", "ValueError", "(", "'If input error is 2D, then it '", "'must have the same shape as the input '", "'data.'", ")", "return", "background", "+", "(", "error", "*", "snr", ")" ]
Calculate a pixel-wise threshold image that can be used to detect sources. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. background : float or array_like, optional The background value(s) of the input ``data``. ``background`` may either be a scalar value or a 2D image with the same shape as the input ``data``. If the input ``data`` has been background-subtracted, then set ``background`` to ``0.0``. If `None`, then a scalar background value will be estimated using sigma-clipped statistics. error : float or array_like, optional The Gaussian 1-sigma standard deviation of the background noise in ``data``. ``error`` should include all sources of "background" error, but *exclude* the Poisson error of the sources. If ``error`` is a 2D image, then it should represent the 1-sigma background error in each pixel of ``data``. If `None`, then a scalar background rms value will be estimated using sigma-clipped statistics. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. Returns ------- threshold : 2D `~numpy.ndarray` A 2D image with the same shape as ``data`` containing the pixel-wise threshold values. See Also -------- :func:`photutils.segmentation.detect_sources` Notes ----- The ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` inputs are used only if it is necessary to estimate ``background`` or ``error`` using sigma-clipped background statistics. If ``background`` and ``error`` are both input, then ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` are ignored.
[ "Calculate", "a", "pixel", "-", "wise", "threshold", "image", "that", "can", "be", "used", "to", "detect", "sources", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/detection/core.py#L18-L126
train
astropy/photutils
ah_bootstrap.py
run_cmd
def run_cmd(cmd): """ Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple. """ try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: msg = 'Command not found: `{0}`'.format(' '.join(cmd)) raise _CommandNotFound(msg, cmd) else: raise _AHBootstrapSystemExit( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}'.format(' '.join(cmd), str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' # Unlikely to fail at this point but even then let's be flexible if not isinstance(stdout, str): stdout = stdout.decode(stdio_encoding, 'replace') if not isinstance(stderr, str): stderr = stderr.decode(stdio_encoding, 'replace') return (p.returncode, stdout, stderr)
python
def run_cmd(cmd): """ Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple. """ try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: msg = 'Command not found: `{0}`'.format(' '.join(cmd)) raise _CommandNotFound(msg, cmd) else: raise _AHBootstrapSystemExit( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}'.format(' '.join(cmd), str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' # Unlikely to fail at this point but even then let's be flexible if not isinstance(stdout, str): stdout = stdout.decode(stdio_encoding, 'replace') if not isinstance(stderr, str): stderr = stderr.decode(stdio_encoding, 'replace') return (p.returncode, stdout, stderr)
[ "def", "run_cmd", "(", "cmd", ")", ":", "try", ":", "p", "=", "sp", ".", "Popen", "(", "cmd", ",", "stdout", "=", "sp", ".", "PIPE", ",", "stderr", "=", "sp", ".", "PIPE", ")", "# XXX: May block if either stdout or stderr fill their buffers;", "# however for the commands this is currently used for that is", "# unlikely (they should have very brief output)", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "except", "OSError", "as", "e", ":", "if", "DEBUG", ":", "raise", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "msg", "=", "'Command not found: `{0}`'", ".", "format", "(", "' '", ".", "join", "(", "cmd", ")", ")", "raise", "_CommandNotFound", "(", "msg", ",", "cmd", ")", "else", ":", "raise", "_AHBootstrapSystemExit", "(", "'An unexpected error occurred when running the '", "'`{0}` command:\\n{1}'", ".", "format", "(", "' '", ".", "join", "(", "cmd", ")", ",", "str", "(", "e", ")", ")", ")", "# Can fail of the default locale is not configured properly. See", "# https://github.com/astropy/astropy/issues/2749. For the purposes under", "# consideration 'latin1' is an acceptable fallback.", "try", ":", "stdio_encoding", "=", "locale", ".", "getdefaultlocale", "(", ")", "[", "1", "]", "or", "'latin1'", "except", "ValueError", ":", "# Due to an OSX oddity locale.getdefaultlocale() can also crash", "# depending on the user's locale/language settings. See:", "# http://bugs.python.org/issue18378", "stdio_encoding", "=", "'latin1'", "# Unlikely to fail at this point but even then let's be flexible", "if", "not", "isinstance", "(", "stdout", ",", "str", ")", ":", "stdout", "=", "stdout", ".", "decode", "(", "stdio_encoding", ",", "'replace'", ")", "if", "not", "isinstance", "(", "stderr", ",", "str", ")", ":", "stderr", "=", "stderr", ".", "decode", "(", "stdio_encoding", ",", "'replace'", ")", "return", "(", "p", ".", "returncode", ",", "stdout", ",", "stderr", ")" ]
Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple.
[ "Run", "a", "command", "in", "a", "subprocess", "given", "as", "a", "list", "of", "command", "-", "line", "arguments", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/ah_bootstrap.py#L768-L812
train
astropy/photutils
photutils/aperture/ellipse.py
EllipticalAperture.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyEllipticalAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAperture` object A `SkyEllipticalAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAperture(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyEllipticalAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAperture` object A `SkyEllipticalAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAperture(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyEllipticalAperture", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyEllipticalAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAperture` object A `SkyEllipticalAperture` object.
[ "Convert", "the", "aperture", "to", "a", "SkyEllipticalAperture", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/ellipse.py#L187-L209
train
astropy/photutils
photutils/aperture/ellipse.py
EllipticalAnnulus.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyEllipticalAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAnnulus` object A `SkyEllipticalAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAnnulus(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyEllipticalAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAnnulus` object A `SkyEllipticalAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAnnulus(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyEllipticalAnnulus", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyEllipticalAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyEllipticalAnnulus` object A `SkyEllipticalAnnulus` object.
[ "Convert", "the", "aperture", "to", "a", "SkyEllipticalAnnulus", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/ellipse.py#L318-L340
train
astropy/photutils
photutils/aperture/ellipse.py
SkyEllipticalAperture.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to an `EllipticalAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAperture` object An `EllipticalAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAperture(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to an `EllipticalAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAperture` object An `EllipticalAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAperture(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "EllipticalAperture", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to an `EllipticalAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAperture` object An `EllipticalAperture` object.
[ "Convert", "the", "aperture", "to", "an", "EllipticalAperture", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/ellipse.py#L385-L407
train
astropy/photutils
photutils/aperture/ellipse.py
SkyEllipticalAnnulus.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to an `EllipticalAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAnnulus` object An `EllipticalAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAnnulus(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to an `EllipticalAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAnnulus` object An `EllipticalAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAnnulus(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "EllipticalAnnulus", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to an `EllipticalAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `EllipticalAnnulus` object An `EllipticalAnnulus` object.
[ "Convert", "the", "aperture", "to", "an", "EllipticalAnnulus", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/ellipse.py#L465-L487
train
astropy/photutils
photutils/isophote/geometry.py
_area
def _area(sma, eps, phi, r): """ Compute elliptical sector area. """ aux = r * math.cos(phi) / sma signal = aux / abs(aux) if abs(aux) >= 1.: aux = signal return abs(sma**2 * (1.-eps) / 2. * math.acos(aux))
python
def _area(sma, eps, phi, r): """ Compute elliptical sector area. """ aux = r * math.cos(phi) / sma signal = aux / abs(aux) if abs(aux) >= 1.: aux = signal return abs(sma**2 * (1.-eps) / 2. * math.acos(aux))
[ "def", "_area", "(", "sma", ",", "eps", ",", "phi", ",", "r", ")", ":", "aux", "=", "r", "*", "math", ".", "cos", "(", "phi", ")", "/", "sma", "signal", "=", "aux", "/", "abs", "(", "aux", ")", "if", "abs", "(", "aux", ")", ">=", "1.", ":", "aux", "=", "signal", "return", "abs", "(", "sma", "**", "2", "*", "(", "1.", "-", "eps", ")", "/", "2.", "*", "math", ".", "acos", "(", "aux", ")", ")" ]
Compute elliptical sector area.
[ "Compute", "elliptical", "sector", "area", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L50-L59
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.find_center
def find_center(self, image, threshold=0.1, verbose=True): """ Find the center of a galaxy. If the algorithm is successful the (x, y) coordinates in this `~photutils.isophote.EllipseGeometry` (i.e. the ``x0`` and ``y0`` attributes) instance will be modified. The isophote fit algorithm requires an initial guess for the galaxy center (x, y) coordinates and these coordinates must be close to the actual galaxy center for the isophote fit to work. This method provides can provide an initial guess for the galaxy center coordinates. See the **Notes** section below for more details. Parameters ---------- image : 2D `~numpy.ndarray` The image array. Masked arrays are not recognized here. This assumes that centering should always be done on valid pixels. threshold : float, optional The centerer threshold. To turn off the centerer, set this to a large value (i.e. >> 1). The default is 0.1. verbose : bool, optional Whether to print object centering information. The default is `True`. Notes ----- The centerer function scans a 10x10 window centered on the (x, y) coordinates in the `~photutils.isophote.EllipseGeometry` instance passed to the constructor of the `~photutils.isophote.Ellipse` class. If any of the `~photutils.isophote.EllipseGeometry` (x, y) coordinates are `None`, the center of the input image frame is used. If the center acquisition is successful, the `~photutils.isophote.EllipseGeometry` instance is modified in place to reflect the solution of the object centerer algorithm. In some cases the object centerer algorithm may fail even though there is enough signal-to-noise to start a fit (e.g. objects with very high ellipticity). In those cases the sensitivity of the algorithm can be decreased by decreasing the value of the object centerer threshold parameter. The centerer works by looking where a quantity akin to a signal-to-noise ratio is maximized within the 10x10 window. The centerer can thus be shut off entirely by setting the threshold to a large value (i.e. >> 1; meaning no location inside the search window will achieve that signal-to-noise ratio). """ self._centerer_mask_half_size = len(IN_MASK) / 2 self.centerer_threshold = threshold # number of pixels in each mask sz = len(IN_MASK) self._centerer_ones_in = np.ma.masked_array(np.ones(shape=(sz, sz)), mask=IN_MASK) self._centerer_ones_out = np.ma.masked_array(np.ones(shape=(sz, sz)), mask=OUT_MASK) self._centerer_in_mask_npix = np.sum(self._centerer_ones_in) self._centerer_out_mask_npix = np.sum(self._centerer_ones_out) # Check if center coordinates point to somewhere inside the frame. # If not, set then to frame center. shape = image.shape _x0 = self.x0 _y0 = self.y0 if (_x0 is None or _x0 < 0 or _x0 >= shape[1] or _y0 is None or _y0 < 0 or _y0 >= shape[0]): _x0 = shape[1] / 2 _y0 = shape[0] / 2 max_fom = 0. max_i = 0 max_j = 0 # scan all positions inside window window_half_size = 5 for i in range(int(_x0 - window_half_size), int(_x0 + window_half_size) + 1): for j in range(int(_y0 - window_half_size), int(_y0 + window_half_size) + 1): # ensure that it stays inside image frame i1 = int(max(0, i - self._centerer_mask_half_size)) j1 = int(max(0, j - self._centerer_mask_half_size)) i2 = int(min(shape[1] - 1, i + self._centerer_mask_half_size)) j2 = int(min(shape[0] - 1, j + self._centerer_mask_half_size)) window = image[j1:j2, i1:i2] # averages in inner and outer regions. inner = np.ma.masked_array(window, mask=IN_MASK) outer = np.ma.masked_array(window, mask=OUT_MASK) inner_avg = np.sum(inner) / self._centerer_in_mask_npix outer_avg = np.sum(outer) / self._centerer_out_mask_npix # standard deviation and figure of merit inner_std = np.std(inner) outer_std = np.std(outer) stddev = np.sqrt(inner_std**2 + outer_std**2) fom = (inner_avg - outer_avg) / stddev if fom > max_fom: max_fom = fom max_i = i max_j = j # figure of merit > threshold: update geometry with new coordinates. if max_fom > threshold: self.x0 = float(max_i) self.y0 = float(max_j) if verbose: log.info("Found center at x0 = {0:5.1f}, y0 = {1:5.1f}" .format(self.x0, self.y0)) else: if verbose: log.info('Result is below the threshold -- keeping the ' 'original coordinates.')
python
def find_center(self, image, threshold=0.1, verbose=True): """ Find the center of a galaxy. If the algorithm is successful the (x, y) coordinates in this `~photutils.isophote.EllipseGeometry` (i.e. the ``x0`` and ``y0`` attributes) instance will be modified. The isophote fit algorithm requires an initial guess for the galaxy center (x, y) coordinates and these coordinates must be close to the actual galaxy center for the isophote fit to work. This method provides can provide an initial guess for the galaxy center coordinates. See the **Notes** section below for more details. Parameters ---------- image : 2D `~numpy.ndarray` The image array. Masked arrays are not recognized here. This assumes that centering should always be done on valid pixels. threshold : float, optional The centerer threshold. To turn off the centerer, set this to a large value (i.e. >> 1). The default is 0.1. verbose : bool, optional Whether to print object centering information. The default is `True`. Notes ----- The centerer function scans a 10x10 window centered on the (x, y) coordinates in the `~photutils.isophote.EllipseGeometry` instance passed to the constructor of the `~photutils.isophote.Ellipse` class. If any of the `~photutils.isophote.EllipseGeometry` (x, y) coordinates are `None`, the center of the input image frame is used. If the center acquisition is successful, the `~photutils.isophote.EllipseGeometry` instance is modified in place to reflect the solution of the object centerer algorithm. In some cases the object centerer algorithm may fail even though there is enough signal-to-noise to start a fit (e.g. objects with very high ellipticity). In those cases the sensitivity of the algorithm can be decreased by decreasing the value of the object centerer threshold parameter. The centerer works by looking where a quantity akin to a signal-to-noise ratio is maximized within the 10x10 window. The centerer can thus be shut off entirely by setting the threshold to a large value (i.e. >> 1; meaning no location inside the search window will achieve that signal-to-noise ratio). """ self._centerer_mask_half_size = len(IN_MASK) / 2 self.centerer_threshold = threshold # number of pixels in each mask sz = len(IN_MASK) self._centerer_ones_in = np.ma.masked_array(np.ones(shape=(sz, sz)), mask=IN_MASK) self._centerer_ones_out = np.ma.masked_array(np.ones(shape=(sz, sz)), mask=OUT_MASK) self._centerer_in_mask_npix = np.sum(self._centerer_ones_in) self._centerer_out_mask_npix = np.sum(self._centerer_ones_out) # Check if center coordinates point to somewhere inside the frame. # If not, set then to frame center. shape = image.shape _x0 = self.x0 _y0 = self.y0 if (_x0 is None or _x0 < 0 or _x0 >= shape[1] or _y0 is None or _y0 < 0 or _y0 >= shape[0]): _x0 = shape[1] / 2 _y0 = shape[0] / 2 max_fom = 0. max_i = 0 max_j = 0 # scan all positions inside window window_half_size = 5 for i in range(int(_x0 - window_half_size), int(_x0 + window_half_size) + 1): for j in range(int(_y0 - window_half_size), int(_y0 + window_half_size) + 1): # ensure that it stays inside image frame i1 = int(max(0, i - self._centerer_mask_half_size)) j1 = int(max(0, j - self._centerer_mask_half_size)) i2 = int(min(shape[1] - 1, i + self._centerer_mask_half_size)) j2 = int(min(shape[0] - 1, j + self._centerer_mask_half_size)) window = image[j1:j2, i1:i2] # averages in inner and outer regions. inner = np.ma.masked_array(window, mask=IN_MASK) outer = np.ma.masked_array(window, mask=OUT_MASK) inner_avg = np.sum(inner) / self._centerer_in_mask_npix outer_avg = np.sum(outer) / self._centerer_out_mask_npix # standard deviation and figure of merit inner_std = np.std(inner) outer_std = np.std(outer) stddev = np.sqrt(inner_std**2 + outer_std**2) fom = (inner_avg - outer_avg) / stddev if fom > max_fom: max_fom = fom max_i = i max_j = j # figure of merit > threshold: update geometry with new coordinates. if max_fom > threshold: self.x0 = float(max_i) self.y0 = float(max_j) if verbose: log.info("Found center at x0 = {0:5.1f}, y0 = {1:5.1f}" .format(self.x0, self.y0)) else: if verbose: log.info('Result is below the threshold -- keeping the ' 'original coordinates.')
[ "def", "find_center", "(", "self", ",", "image", ",", "threshold", "=", "0.1", ",", "verbose", "=", "True", ")", ":", "self", ".", "_centerer_mask_half_size", "=", "len", "(", "IN_MASK", ")", "/", "2", "self", ".", "centerer_threshold", "=", "threshold", "# number of pixels in each mask", "sz", "=", "len", "(", "IN_MASK", ")", "self", ".", "_centerer_ones_in", "=", "np", ".", "ma", ".", "masked_array", "(", "np", ".", "ones", "(", "shape", "=", "(", "sz", ",", "sz", ")", ")", ",", "mask", "=", "IN_MASK", ")", "self", ".", "_centerer_ones_out", "=", "np", ".", "ma", ".", "masked_array", "(", "np", ".", "ones", "(", "shape", "=", "(", "sz", ",", "sz", ")", ")", ",", "mask", "=", "OUT_MASK", ")", "self", ".", "_centerer_in_mask_npix", "=", "np", ".", "sum", "(", "self", ".", "_centerer_ones_in", ")", "self", ".", "_centerer_out_mask_npix", "=", "np", ".", "sum", "(", "self", ".", "_centerer_ones_out", ")", "# Check if center coordinates point to somewhere inside the frame.", "# If not, set then to frame center.", "shape", "=", "image", ".", "shape", "_x0", "=", "self", ".", "x0", "_y0", "=", "self", ".", "y0", "if", "(", "_x0", "is", "None", "or", "_x0", "<", "0", "or", "_x0", ">=", "shape", "[", "1", "]", "or", "_y0", "is", "None", "or", "_y0", "<", "0", "or", "_y0", ">=", "shape", "[", "0", "]", ")", ":", "_x0", "=", "shape", "[", "1", "]", "/", "2", "_y0", "=", "shape", "[", "0", "]", "/", "2", "max_fom", "=", "0.", "max_i", "=", "0", "max_j", "=", "0", "# scan all positions inside window", "window_half_size", "=", "5", "for", "i", "in", "range", "(", "int", "(", "_x0", "-", "window_half_size", ")", ",", "int", "(", "_x0", "+", "window_half_size", ")", "+", "1", ")", ":", "for", "j", "in", "range", "(", "int", "(", "_y0", "-", "window_half_size", ")", ",", "int", "(", "_y0", "+", "window_half_size", ")", "+", "1", ")", ":", "# ensure that it stays inside image frame", "i1", "=", "int", "(", "max", "(", "0", ",", "i", "-", "self", ".", "_centerer_mask_half_size", ")", ")", "j1", "=", "int", "(", "max", "(", "0", ",", "j", "-", "self", ".", "_centerer_mask_half_size", ")", ")", "i2", "=", "int", "(", "min", "(", "shape", "[", "1", "]", "-", "1", ",", "i", "+", "self", ".", "_centerer_mask_half_size", ")", ")", "j2", "=", "int", "(", "min", "(", "shape", "[", "0", "]", "-", "1", ",", "j", "+", "self", ".", "_centerer_mask_half_size", ")", ")", "window", "=", "image", "[", "j1", ":", "j2", ",", "i1", ":", "i2", "]", "# averages in inner and outer regions.", "inner", "=", "np", ".", "ma", ".", "masked_array", "(", "window", ",", "mask", "=", "IN_MASK", ")", "outer", "=", "np", ".", "ma", ".", "masked_array", "(", "window", ",", "mask", "=", "OUT_MASK", ")", "inner_avg", "=", "np", ".", "sum", "(", "inner", ")", "/", "self", ".", "_centerer_in_mask_npix", "outer_avg", "=", "np", ".", "sum", "(", "outer", ")", "/", "self", ".", "_centerer_out_mask_npix", "# standard deviation and figure of merit", "inner_std", "=", "np", ".", "std", "(", "inner", ")", "outer_std", "=", "np", ".", "std", "(", "outer", ")", "stddev", "=", "np", ".", "sqrt", "(", "inner_std", "**", "2", "+", "outer_std", "**", "2", ")", "fom", "=", "(", "inner_avg", "-", "outer_avg", ")", "/", "stddev", "if", "fom", ">", "max_fom", ":", "max_fom", "=", "fom", "max_i", "=", "i", "max_j", "=", "j", "# figure of merit > threshold: update geometry with new coordinates.", "if", "max_fom", ">", "threshold", ":", "self", ".", "x0", "=", "float", "(", "max_i", ")", "self", ".", "y0", "=", "float", "(", "max_j", ")", "if", "verbose", ":", "log", ".", "info", "(", "\"Found center at x0 = {0:5.1f}, y0 = {1:5.1f}\"", ".", "format", "(", "self", ".", "x0", ",", "self", ".", "y0", ")", ")", "else", ":", "if", "verbose", ":", "log", ".", "info", "(", "'Result is below the threshold -- keeping the '", "'original coordinates.'", ")" ]
Find the center of a galaxy. If the algorithm is successful the (x, y) coordinates in this `~photutils.isophote.EllipseGeometry` (i.e. the ``x0`` and ``y0`` attributes) instance will be modified. The isophote fit algorithm requires an initial guess for the galaxy center (x, y) coordinates and these coordinates must be close to the actual galaxy center for the isophote fit to work. This method provides can provide an initial guess for the galaxy center coordinates. See the **Notes** section below for more details. Parameters ---------- image : 2D `~numpy.ndarray` The image array. Masked arrays are not recognized here. This assumes that centering should always be done on valid pixels. threshold : float, optional The centerer threshold. To turn off the centerer, set this to a large value (i.e. >> 1). The default is 0.1. verbose : bool, optional Whether to print object centering information. The default is `True`. Notes ----- The centerer function scans a 10x10 window centered on the (x, y) coordinates in the `~photutils.isophote.EllipseGeometry` instance passed to the constructor of the `~photutils.isophote.Ellipse` class. If any of the `~photutils.isophote.EllipseGeometry` (x, y) coordinates are `None`, the center of the input image frame is used. If the center acquisition is successful, the `~photutils.isophote.EllipseGeometry` instance is modified in place to reflect the solution of the object centerer algorithm. In some cases the object centerer algorithm may fail even though there is enough signal-to-noise to start a fit (e.g. objects with very high ellipticity). In those cases the sensitivity of the algorithm can be decreased by decreasing the value of the object centerer threshold parameter. The centerer works by looking where a quantity akin to a signal-to-noise ratio is maximized within the 10x10 window. The centerer can thus be shut off entirely by setting the threshold to a large value (i.e. >> 1; meaning no location inside the search window will achieve that signal-to-noise ratio).
[ "Find", "the", "center", "of", "a", "galaxy", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L133-L254
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.radius
def radius(self, angle): """ Calculate the polar radius for a given polar angle. Parameters ---------- angle : float The polar angle (radians). Returns ------- radius : float The polar radius (pixels). """ return (self.sma * (1. - self.eps) / np.sqrt(((1. - self.eps) * np.cos(angle))**2 + (np.sin(angle))**2))
python
def radius(self, angle): """ Calculate the polar radius for a given polar angle. Parameters ---------- angle : float The polar angle (radians). Returns ------- radius : float The polar radius (pixels). """ return (self.sma * (1. - self.eps) / np.sqrt(((1. - self.eps) * np.cos(angle))**2 + (np.sin(angle))**2))
[ "def", "radius", "(", "self", ",", "angle", ")", ":", "return", "(", "self", ".", "sma", "*", "(", "1.", "-", "self", ".", "eps", ")", "/", "np", ".", "sqrt", "(", "(", "(", "1.", "-", "self", ".", "eps", ")", "*", "np", ".", "cos", "(", "angle", ")", ")", "**", "2", "+", "(", "np", ".", "sin", "(", "angle", ")", ")", "**", "2", ")", ")" ]
Calculate the polar radius for a given polar angle. Parameters ---------- angle : float The polar angle (radians). Returns ------- radius : float The polar radius (pixels).
[ "Calculate", "the", "polar", "radius", "for", "a", "given", "polar", "angle", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L256-L273
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.initialize_sector_geometry
def initialize_sector_geometry(self, phi): """ Initialize geometry attributes associated with an elliptical sector at the given polar angle ``phi``. This function computes: * the four vertices that define the elliptical sector on the pixel array. * the sector area (saved in the ``sector_area`` attribute) * the sector angular width (saved in ``sector_angular_width`` attribute) Parameters ---------- phi : float The polar angle (radians) where the sector is located. Returns ------- x, y : 1D `~numpy.ndarray` The x and y coordinates of each vertex as 1D arrays. """ # These polar radii bound the region between the inner # and outer ellipses that define the sector. sma1, sma2 = self.bounding_ellipses() eps_ = 1. - self.eps # polar vector at one side of the elliptical sector self._phi1 = phi - self.sector_angular_width / 2. r1 = (sma1 * eps_ / math.sqrt((eps_ * math.cos(self._phi1))**2 + (math.sin(self._phi1))**2)) r2 = (sma2 * eps_ / math.sqrt((eps_ * math.cos(self._phi1))**2 + (math.sin(self._phi1))**2)) # polar vector at the other side of the elliptical sector self._phi2 = phi + self.sector_angular_width / 2. r3 = (sma2 * eps_ / math.sqrt((eps_ * math.cos(self._phi2))**2 + (math.sin(self._phi2))**2)) r4 = (sma1 * eps_ / math.sqrt((eps_ * math.cos(self._phi2))**2 + (math.sin(self._phi2))**2)) # sector area sa1 = _area(sma1, self.eps, self._phi1, r1) sa2 = _area(sma2, self.eps, self._phi1, r2) sa3 = _area(sma2, self.eps, self._phi2, r3) sa4 = _area(sma1, self.eps, self._phi2, r4) self.sector_area = abs((sa3 - sa2) - (sa4 - sa1)) # angular width of sector. It is calculated such that the sectors # come out with roughly constant area along the ellipse. self.sector_angular_width = max(min((self._area_factor / (r3 - r4) / r4), self._phi_max), self._phi_min) # compute the 4 vertices that define the elliptical sector. vertex_x = np.zeros(shape=4, dtype=float) vertex_y = np.zeros(shape=4, dtype=float) # vertices are labelled in counterclockwise sequence vertex_x[0:2] = np.array([r1, r2]) * math.cos(self._phi1 + self.pa) vertex_x[2:4] = np.array([r4, r3]) * math.cos(self._phi2 + self.pa) vertex_y[0:2] = np.array([r1, r2]) * math.sin(self._phi1 + self.pa) vertex_y[2:4] = np.array([r4, r3]) * math.sin(self._phi2 + self.pa) vertex_x += self.x0 vertex_y += self.y0 return vertex_x, vertex_y
python
def initialize_sector_geometry(self, phi): """ Initialize geometry attributes associated with an elliptical sector at the given polar angle ``phi``. This function computes: * the four vertices that define the elliptical sector on the pixel array. * the sector area (saved in the ``sector_area`` attribute) * the sector angular width (saved in ``sector_angular_width`` attribute) Parameters ---------- phi : float The polar angle (radians) where the sector is located. Returns ------- x, y : 1D `~numpy.ndarray` The x and y coordinates of each vertex as 1D arrays. """ # These polar radii bound the region between the inner # and outer ellipses that define the sector. sma1, sma2 = self.bounding_ellipses() eps_ = 1. - self.eps # polar vector at one side of the elliptical sector self._phi1 = phi - self.sector_angular_width / 2. r1 = (sma1 * eps_ / math.sqrt((eps_ * math.cos(self._phi1))**2 + (math.sin(self._phi1))**2)) r2 = (sma2 * eps_ / math.sqrt((eps_ * math.cos(self._phi1))**2 + (math.sin(self._phi1))**2)) # polar vector at the other side of the elliptical sector self._phi2 = phi + self.sector_angular_width / 2. r3 = (sma2 * eps_ / math.sqrt((eps_ * math.cos(self._phi2))**2 + (math.sin(self._phi2))**2)) r4 = (sma1 * eps_ / math.sqrt((eps_ * math.cos(self._phi2))**2 + (math.sin(self._phi2))**2)) # sector area sa1 = _area(sma1, self.eps, self._phi1, r1) sa2 = _area(sma2, self.eps, self._phi1, r2) sa3 = _area(sma2, self.eps, self._phi2, r3) sa4 = _area(sma1, self.eps, self._phi2, r4) self.sector_area = abs((sa3 - sa2) - (sa4 - sa1)) # angular width of sector. It is calculated such that the sectors # come out with roughly constant area along the ellipse. self.sector_angular_width = max(min((self._area_factor / (r3 - r4) / r4), self._phi_max), self._phi_min) # compute the 4 vertices that define the elliptical sector. vertex_x = np.zeros(shape=4, dtype=float) vertex_y = np.zeros(shape=4, dtype=float) # vertices are labelled in counterclockwise sequence vertex_x[0:2] = np.array([r1, r2]) * math.cos(self._phi1 + self.pa) vertex_x[2:4] = np.array([r4, r3]) * math.cos(self._phi2 + self.pa) vertex_y[0:2] = np.array([r1, r2]) * math.sin(self._phi1 + self.pa) vertex_y[2:4] = np.array([r4, r3]) * math.sin(self._phi2 + self.pa) vertex_x += self.x0 vertex_y += self.y0 return vertex_x, vertex_y
[ "def", "initialize_sector_geometry", "(", "self", ",", "phi", ")", ":", "# These polar radii bound the region between the inner", "# and outer ellipses that define the sector.", "sma1", ",", "sma2", "=", "self", ".", "bounding_ellipses", "(", ")", "eps_", "=", "1.", "-", "self", ".", "eps", "# polar vector at one side of the elliptical sector", "self", ".", "_phi1", "=", "phi", "-", "self", ".", "sector_angular_width", "/", "2.", "r1", "=", "(", "sma1", "*", "eps_", "/", "math", ".", "sqrt", "(", "(", "eps_", "*", "math", ".", "cos", "(", "self", ".", "_phi1", ")", ")", "**", "2", "+", "(", "math", ".", "sin", "(", "self", ".", "_phi1", ")", ")", "**", "2", ")", ")", "r2", "=", "(", "sma2", "*", "eps_", "/", "math", ".", "sqrt", "(", "(", "eps_", "*", "math", ".", "cos", "(", "self", ".", "_phi1", ")", ")", "**", "2", "+", "(", "math", ".", "sin", "(", "self", ".", "_phi1", ")", ")", "**", "2", ")", ")", "# polar vector at the other side of the elliptical sector", "self", ".", "_phi2", "=", "phi", "+", "self", ".", "sector_angular_width", "/", "2.", "r3", "=", "(", "sma2", "*", "eps_", "/", "math", ".", "sqrt", "(", "(", "eps_", "*", "math", ".", "cos", "(", "self", ".", "_phi2", ")", ")", "**", "2", "+", "(", "math", ".", "sin", "(", "self", ".", "_phi2", ")", ")", "**", "2", ")", ")", "r4", "=", "(", "sma1", "*", "eps_", "/", "math", ".", "sqrt", "(", "(", "eps_", "*", "math", ".", "cos", "(", "self", ".", "_phi2", ")", ")", "**", "2", "+", "(", "math", ".", "sin", "(", "self", ".", "_phi2", ")", ")", "**", "2", ")", ")", "# sector area", "sa1", "=", "_area", "(", "sma1", ",", "self", ".", "eps", ",", "self", ".", "_phi1", ",", "r1", ")", "sa2", "=", "_area", "(", "sma2", ",", "self", ".", "eps", ",", "self", ".", "_phi1", ",", "r2", ")", "sa3", "=", "_area", "(", "sma2", ",", "self", ".", "eps", ",", "self", ".", "_phi2", ",", "r3", ")", "sa4", "=", "_area", "(", "sma1", ",", "self", ".", "eps", ",", "self", ".", "_phi2", ",", "r4", ")", "self", ".", "sector_area", "=", "abs", "(", "(", "sa3", "-", "sa2", ")", "-", "(", "sa4", "-", "sa1", ")", ")", "# angular width of sector. It is calculated such that the sectors", "# come out with roughly constant area along the ellipse.", "self", ".", "sector_angular_width", "=", "max", "(", "min", "(", "(", "self", ".", "_area_factor", "/", "(", "r3", "-", "r4", ")", "/", "r4", ")", ",", "self", ".", "_phi_max", ")", ",", "self", ".", "_phi_min", ")", "# compute the 4 vertices that define the elliptical sector.", "vertex_x", "=", "np", ".", "zeros", "(", "shape", "=", "4", ",", "dtype", "=", "float", ")", "vertex_y", "=", "np", ".", "zeros", "(", "shape", "=", "4", ",", "dtype", "=", "float", ")", "# vertices are labelled in counterclockwise sequence", "vertex_x", "[", "0", ":", "2", "]", "=", "np", ".", "array", "(", "[", "r1", ",", "r2", "]", ")", "*", "math", ".", "cos", "(", "self", ".", "_phi1", "+", "self", ".", "pa", ")", "vertex_x", "[", "2", ":", "4", "]", "=", "np", ".", "array", "(", "[", "r4", ",", "r3", "]", ")", "*", "math", ".", "cos", "(", "self", ".", "_phi2", "+", "self", ".", "pa", ")", "vertex_y", "[", "0", ":", "2", "]", "=", "np", ".", "array", "(", "[", "r1", ",", "r2", "]", ")", "*", "math", ".", "sin", "(", "self", ".", "_phi1", "+", "self", ".", "pa", ")", "vertex_y", "[", "2", ":", "4", "]", "=", "np", ".", "array", "(", "[", "r4", ",", "r3", "]", ")", "*", "math", ".", "sin", "(", "self", ".", "_phi2", "+", "self", ".", "pa", ")", "vertex_x", "+=", "self", ".", "x0", "vertex_y", "+=", "self", ".", "y0", "return", "vertex_x", ",", "vertex_y" ]
Initialize geometry attributes associated with an elliptical sector at the given polar angle ``phi``. This function computes: * the four vertices that define the elliptical sector on the pixel array. * the sector area (saved in the ``sector_area`` attribute) * the sector angular width (saved in ``sector_angular_width`` attribute) Parameters ---------- phi : float The polar angle (radians) where the sector is located. Returns ------- x, y : 1D `~numpy.ndarray` The x and y coordinates of each vertex as 1D arrays.
[ "Initialize", "geometry", "attributes", "associated", "with", "an", "elliptical", "sector", "at", "the", "given", "polar", "angle", "phi", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L275-L344
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.bounding_ellipses
def bounding_ellipses(self): """ Compute the semimajor axis of the two ellipses that bound the annulus where integrations take place. Returns ------- sma1, sma2 : float The smaller and larger values of semimajor axis length that define the annulus bounding ellipses. """ if (self.linear_growth): a1 = self.sma - self.astep / 2. a2 = self.sma + self.astep / 2. else: a1 = self.sma * (1. - self.astep / 2.) a2 = self.sma * (1. + self.astep / 2.) return a1, a2
python
def bounding_ellipses(self): """ Compute the semimajor axis of the two ellipses that bound the annulus where integrations take place. Returns ------- sma1, sma2 : float The smaller and larger values of semimajor axis length that define the annulus bounding ellipses. """ if (self.linear_growth): a1 = self.sma - self.astep / 2. a2 = self.sma + self.astep / 2. else: a1 = self.sma * (1. - self.astep / 2.) a2 = self.sma * (1. + self.astep / 2.) return a1, a2
[ "def", "bounding_ellipses", "(", "self", ")", ":", "if", "(", "self", ".", "linear_growth", ")", ":", "a1", "=", "self", ".", "sma", "-", "self", ".", "astep", "/", "2.", "a2", "=", "self", ".", "sma", "+", "self", ".", "astep", "/", "2.", "else", ":", "a1", "=", "self", ".", "sma", "*", "(", "1.", "-", "self", ".", "astep", "/", "2.", ")", "a2", "=", "self", ".", "sma", "*", "(", "1.", "+", "self", ".", "astep", "/", "2.", ")", "return", "a1", ",", "a2" ]
Compute the semimajor axis of the two ellipses that bound the annulus where integrations take place. Returns ------- sma1, sma2 : float The smaller and larger values of semimajor axis length that define the annulus bounding ellipses.
[ "Compute", "the", "semimajor", "axis", "of", "the", "two", "ellipses", "that", "bound", "the", "annulus", "where", "integrations", "take", "place", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L346-L365
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.update_sma
def update_sma(self, step): """ Calculate an updated value for the semimajor axis, given the current value and the step value. The step value must be managed by the caller to support both modes: grow outwards and shrink inwards. Parameters ---------- step : float The step value. Returns ------- sma : float The new semimajor axis length. """ if self.linear_growth: sma = self.sma + step else: sma = self.sma * (1. + step) return sma
python
def update_sma(self, step): """ Calculate an updated value for the semimajor axis, given the current value and the step value. The step value must be managed by the caller to support both modes: grow outwards and shrink inwards. Parameters ---------- step : float The step value. Returns ------- sma : float The new semimajor axis length. """ if self.linear_growth: sma = self.sma + step else: sma = self.sma * (1. + step) return sma
[ "def", "update_sma", "(", "self", ",", "step", ")", ":", "if", "self", ".", "linear_growth", ":", "sma", "=", "self", ".", "sma", "+", "step", "else", ":", "sma", "=", "self", ".", "sma", "*", "(", "1.", "+", "step", ")", "return", "sma" ]
Calculate an updated value for the semimajor axis, given the current value and the step value. The step value must be managed by the caller to support both modes: grow outwards and shrink inwards. Parameters ---------- step : float The step value. Returns ------- sma : float The new semimajor axis length.
[ "Calculate", "an", "updated", "value", "for", "the", "semimajor", "axis", "given", "the", "current", "value", "and", "the", "step", "value", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L484-L507
train
astropy/photutils
photutils/isophote/geometry.py
EllipseGeometry.reset_sma
def reset_sma(self, step): """ Change the direction of semimajor axis growth, from outwards to inwards. Parameters ---------- step : float The current step value. Returns ------- sma, new_step : float The new semimajor axis length and the new step value to initiate the shrinking of the semimajor axis length. This is the step value that should be used when calling the :meth:`~photutils.isophote.EllipseGeometry.update_sma` method. """ if self.linear_growth: sma = self.sma - step step = -step else: aux = 1. / (1. + step) sma = self.sma * aux step = aux - 1. return sma, step
python
def reset_sma(self, step): """ Change the direction of semimajor axis growth, from outwards to inwards. Parameters ---------- step : float The current step value. Returns ------- sma, new_step : float The new semimajor axis length and the new step value to initiate the shrinking of the semimajor axis length. This is the step value that should be used when calling the :meth:`~photutils.isophote.EllipseGeometry.update_sma` method. """ if self.linear_growth: sma = self.sma - step step = -step else: aux = 1. / (1. + step) sma = self.sma * aux step = aux - 1. return sma, step
[ "def", "reset_sma", "(", "self", ",", "step", ")", ":", "if", "self", ".", "linear_growth", ":", "sma", "=", "self", ".", "sma", "-", "step", "step", "=", "-", "step", "else", ":", "aux", "=", "1.", "/", "(", "1.", "+", "step", ")", "sma", "=", "self", ".", "sma", "*", "aux", "step", "=", "aux", "-", "1.", "return", "sma", ",", "step" ]
Change the direction of semimajor axis growth, from outwards to inwards. Parameters ---------- step : float The current step value. Returns ------- sma, new_step : float The new semimajor axis length and the new step value to initiate the shrinking of the semimajor axis length. This is the step value that should be used when calling the :meth:`~photutils.isophote.EllipseGeometry.update_sma` method.
[ "Change", "the", "direction", "of", "semimajor", "axis", "growth", "from", "outwards", "to", "inwards", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/geometry.py#L509-L537
train
astropy/photutils
photutils/psf/matching/fourier.py
resize_psf
def resize_psf(psf, input_pixel_scale, output_pixel_scale, order=3): """ Resize a PSF using spline interpolation of the requested order. Parameters ---------- psf : 2D `~numpy.ndarray` The 2D data array of the PSF. input_pixel_scale : float The pixel scale of the input ``psf``. The units must match ``output_pixel_scale``. output_pixel_scale : float The pixel scale of the output ``psf``. The units must match ``input_pixel_scale``. order : float, optional The order of the spline interpolation (0-5). The default is 3. Returns ------- result : 2D `~numpy.ndarray` The resampled/interpolated 2D data array. """ from scipy.ndimage import zoom ratio = input_pixel_scale / output_pixel_scale return zoom(psf, ratio, order=order) / ratio**2
python
def resize_psf(psf, input_pixel_scale, output_pixel_scale, order=3): """ Resize a PSF using spline interpolation of the requested order. Parameters ---------- psf : 2D `~numpy.ndarray` The 2D data array of the PSF. input_pixel_scale : float The pixel scale of the input ``psf``. The units must match ``output_pixel_scale``. output_pixel_scale : float The pixel scale of the output ``psf``. The units must match ``input_pixel_scale``. order : float, optional The order of the spline interpolation (0-5). The default is 3. Returns ------- result : 2D `~numpy.ndarray` The resampled/interpolated 2D data array. """ from scipy.ndimage import zoom ratio = input_pixel_scale / output_pixel_scale return zoom(psf, ratio, order=order) / ratio**2
[ "def", "resize_psf", "(", "psf", ",", "input_pixel_scale", ",", "output_pixel_scale", ",", "order", "=", "3", ")", ":", "from", "scipy", ".", "ndimage", "import", "zoom", "ratio", "=", "input_pixel_scale", "/", "output_pixel_scale", "return", "zoom", "(", "psf", ",", "ratio", ",", "order", "=", "order", ")", "/", "ratio", "**", "2" ]
Resize a PSF using spline interpolation of the requested order. Parameters ---------- psf : 2D `~numpy.ndarray` The 2D data array of the PSF. input_pixel_scale : float The pixel scale of the input ``psf``. The units must match ``output_pixel_scale``. output_pixel_scale : float The pixel scale of the output ``psf``. The units must match ``input_pixel_scale``. order : float, optional The order of the spline interpolation (0-5). The default is 3. Returns ------- result : 2D `~numpy.ndarray` The resampled/interpolated 2D data array.
[ "Resize", "a", "PSF", "using", "spline", "interpolation", "of", "the", "requested", "order", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/matching/fourier.py#L13-L42
train
astropy/photutils
photutils/background/background_2d.py
Background2D._select_meshes
def _select_meshes(self, data): """ Define the x and y indices with respect to the low-resolution mesh image of the meshes to use for the background interpolation. The ``exclude_percentile`` keyword determines which meshes are not used for the background interpolation. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` A 2D array where the y dimension represents each mesh and the x dimension represents the data in each mesh. Returns ------- mesh_idx : 1D `~numpy.ndarray` The 1D mesh indices. """ # the number of masked pixels in each mesh nmasked = np.ma.count_masked(data, axis=1) # meshes that contain more than ``exclude_percentile`` percent # masked pixels are excluded: # - for exclude_percentile=0, good meshes will be only where # nmasked=0 # - meshes where nmasked=self.box_npixels are *always* excluded # (second conditional needed for exclude_percentile=100) threshold_npixels = self.exclude_percentile / 100. * self.box_npixels mesh_idx = np.where((nmasked <= threshold_npixels) & (nmasked != self.box_npixels))[0] # good meshes if len(mesh_idx) == 0: raise ValueError('All meshes contain > {0} ({1} percent per ' 'mesh) masked pixels. Please check your data ' 'or decrease "exclude_percentile".' .format(threshold_npixels, self.exclude_percentile)) return mesh_idx
python
def _select_meshes(self, data): """ Define the x and y indices with respect to the low-resolution mesh image of the meshes to use for the background interpolation. The ``exclude_percentile`` keyword determines which meshes are not used for the background interpolation. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` A 2D array where the y dimension represents each mesh and the x dimension represents the data in each mesh. Returns ------- mesh_idx : 1D `~numpy.ndarray` The 1D mesh indices. """ # the number of masked pixels in each mesh nmasked = np.ma.count_masked(data, axis=1) # meshes that contain more than ``exclude_percentile`` percent # masked pixels are excluded: # - for exclude_percentile=0, good meshes will be only where # nmasked=0 # - meshes where nmasked=self.box_npixels are *always* excluded # (second conditional needed for exclude_percentile=100) threshold_npixels = self.exclude_percentile / 100. * self.box_npixels mesh_idx = np.where((nmasked <= threshold_npixels) & (nmasked != self.box_npixels))[0] # good meshes if len(mesh_idx) == 0: raise ValueError('All meshes contain > {0} ({1} percent per ' 'mesh) masked pixels. Please check your data ' 'or decrease "exclude_percentile".' .format(threshold_npixels, self.exclude_percentile)) return mesh_idx
[ "def", "_select_meshes", "(", "self", ",", "data", ")", ":", "# the number of masked pixels in each mesh", "nmasked", "=", "np", ".", "ma", ".", "count_masked", "(", "data", ",", "axis", "=", "1", ")", "# meshes that contain more than ``exclude_percentile`` percent", "# masked pixels are excluded:", "# - for exclude_percentile=0, good meshes will be only where", "# nmasked=0", "# - meshes where nmasked=self.box_npixels are *always* excluded", "# (second conditional needed for exclude_percentile=100)", "threshold_npixels", "=", "self", ".", "exclude_percentile", "/", "100.", "*", "self", ".", "box_npixels", "mesh_idx", "=", "np", ".", "where", "(", "(", "nmasked", "<=", "threshold_npixels", ")", "&", "(", "nmasked", "!=", "self", ".", "box_npixels", ")", ")", "[", "0", "]", "# good meshes", "if", "len", "(", "mesh_idx", ")", "==", "0", ":", "raise", "ValueError", "(", "'All meshes contain > {0} ({1} percent per '", "'mesh) masked pixels. Please check your data '", "'or decrease \"exclude_percentile\".'", ".", "format", "(", "threshold_npixels", ",", "self", ".", "exclude_percentile", ")", ")", "return", "mesh_idx" ]
Define the x and y indices with respect to the low-resolution mesh image of the meshes to use for the background interpolation. The ``exclude_percentile`` keyword determines which meshes are not used for the background interpolation. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` A 2D array where the y dimension represents each mesh and the x dimension represents the data in each mesh. Returns ------- mesh_idx : 1D `~numpy.ndarray` The 1D mesh indices.
[ "Define", "the", "x", "and", "y", "indices", "with", "respect", "to", "the", "low", "-", "resolution", "mesh", "image", "of", "the", "meshes", "to", "use", "for", "the", "background", "interpolation", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L412-L453
train
astropy/photutils
photutils/background/background_2d.py
Background2D._prepare_data
def _prepare_data(self): """ Prepare the data. First, pad or crop the 2D data array so that there are an integer number of meshes in both dimensions, creating a masked array. Then reshape into a different 2D masked array where each row represents the data in a single mesh. This method also performs a first cut at rejecting certain meshes as specified by the input keywords. """ self.nyboxes = self.data.shape[0] // self.box_size[0] self.nxboxes = self.data.shape[1] // self.box_size[1] yextra = self.data.shape[0] % self.box_size[0] xextra = self.data.shape[1] % self.box_size[1] if (xextra + yextra) == 0: # no resizing of the data is necessary data_ma = np.ma.masked_array(self.data, mask=self.mask) else: # pad or crop the data if self.edge_method == 'pad': data_ma = self._pad_data(yextra, xextra) self.nyboxes = data_ma.shape[0] // self.box_size[0] self.nxboxes = data_ma.shape[1] // self.box_size[1] elif self.edge_method == 'crop': data_ma = self._crop_data() else: raise ValueError('edge_method must be "pad" or "crop"') self.nboxes = self.nxboxes * self.nyboxes # a reshaped 2D masked array with mesh data along the x axis mesh_data = np.ma.swapaxes(data_ma.reshape( self.nyboxes, self.box_size[0], self.nxboxes, self.box_size[1]), 1, 2).reshape(self.nyboxes * self.nxboxes, self.box_npixels) # first cut on rejecting meshes self.mesh_idx = self._select_meshes(mesh_data) self._mesh_data = mesh_data[self.mesh_idx, :] return
python
def _prepare_data(self): """ Prepare the data. First, pad or crop the 2D data array so that there are an integer number of meshes in both dimensions, creating a masked array. Then reshape into a different 2D masked array where each row represents the data in a single mesh. This method also performs a first cut at rejecting certain meshes as specified by the input keywords. """ self.nyboxes = self.data.shape[0] // self.box_size[0] self.nxboxes = self.data.shape[1] // self.box_size[1] yextra = self.data.shape[0] % self.box_size[0] xextra = self.data.shape[1] % self.box_size[1] if (xextra + yextra) == 0: # no resizing of the data is necessary data_ma = np.ma.masked_array(self.data, mask=self.mask) else: # pad or crop the data if self.edge_method == 'pad': data_ma = self._pad_data(yextra, xextra) self.nyboxes = data_ma.shape[0] // self.box_size[0] self.nxboxes = data_ma.shape[1] // self.box_size[1] elif self.edge_method == 'crop': data_ma = self._crop_data() else: raise ValueError('edge_method must be "pad" or "crop"') self.nboxes = self.nxboxes * self.nyboxes # a reshaped 2D masked array with mesh data along the x axis mesh_data = np.ma.swapaxes(data_ma.reshape( self.nyboxes, self.box_size[0], self.nxboxes, self.box_size[1]), 1, 2).reshape(self.nyboxes * self.nxboxes, self.box_npixels) # first cut on rejecting meshes self.mesh_idx = self._select_meshes(mesh_data) self._mesh_data = mesh_data[self.mesh_idx, :] return
[ "def", "_prepare_data", "(", "self", ")", ":", "self", ".", "nyboxes", "=", "self", ".", "data", ".", "shape", "[", "0", "]", "//", "self", ".", "box_size", "[", "0", "]", "self", ".", "nxboxes", "=", "self", ".", "data", ".", "shape", "[", "1", "]", "//", "self", ".", "box_size", "[", "1", "]", "yextra", "=", "self", ".", "data", ".", "shape", "[", "0", "]", "%", "self", ".", "box_size", "[", "0", "]", "xextra", "=", "self", ".", "data", ".", "shape", "[", "1", "]", "%", "self", ".", "box_size", "[", "1", "]", "if", "(", "xextra", "+", "yextra", ")", "==", "0", ":", "# no resizing of the data is necessary", "data_ma", "=", "np", ".", "ma", ".", "masked_array", "(", "self", ".", "data", ",", "mask", "=", "self", ".", "mask", ")", "else", ":", "# pad or crop the data", "if", "self", ".", "edge_method", "==", "'pad'", ":", "data_ma", "=", "self", ".", "_pad_data", "(", "yextra", ",", "xextra", ")", "self", ".", "nyboxes", "=", "data_ma", ".", "shape", "[", "0", "]", "//", "self", ".", "box_size", "[", "0", "]", "self", ".", "nxboxes", "=", "data_ma", ".", "shape", "[", "1", "]", "//", "self", ".", "box_size", "[", "1", "]", "elif", "self", ".", "edge_method", "==", "'crop'", ":", "data_ma", "=", "self", ".", "_crop_data", "(", ")", "else", ":", "raise", "ValueError", "(", "'edge_method must be \"pad\" or \"crop\"'", ")", "self", ".", "nboxes", "=", "self", ".", "nxboxes", "*", "self", ".", "nyboxes", "# a reshaped 2D masked array with mesh data along the x axis", "mesh_data", "=", "np", ".", "ma", ".", "swapaxes", "(", "data_ma", ".", "reshape", "(", "self", ".", "nyboxes", ",", "self", ".", "box_size", "[", "0", "]", ",", "self", ".", "nxboxes", ",", "self", ".", "box_size", "[", "1", "]", ")", ",", "1", ",", "2", ")", ".", "reshape", "(", "self", ".", "nyboxes", "*", "self", ".", "nxboxes", ",", "self", ".", "box_npixels", ")", "# first cut on rejecting meshes", "self", ".", "mesh_idx", "=", "self", ".", "_select_meshes", "(", "mesh_data", ")", "self", ".", "_mesh_data", "=", "mesh_data", "[", "self", ".", "mesh_idx", ",", ":", "]", "return" ]
Prepare the data. First, pad or crop the 2D data array so that there are an integer number of meshes in both dimensions, creating a masked array. Then reshape into a different 2D masked array where each row represents the data in a single mesh. This method also performs a first cut at rejecting certain meshes as specified by the input keywords.
[ "Prepare", "the", "data", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L455-L499
train
astropy/photutils
photutils/background/background_2d.py
Background2D._make_2d_array
def _make_2d_array(self, data): """ Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices ``mesh_idx``. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. Returns ------- result : 2D `~numpy.ma.MaskedArray` A 2D masked array. Pixels not defined in ``mesh_idx`` are masked. """ if data.shape != self.mesh_idx.shape: raise ValueError('data and mesh_idx must have the same shape') if np.ma.is_masked(data): raise ValueError('data must not be a masked array') data2d = np.zeros(self._mesh_shape).astype(data.dtype) data2d[self.mesh_yidx, self.mesh_xidx] = data if len(self.mesh_idx) == self.nboxes: # no meshes were masked return data2d else: # some meshes were masked mask2d = np.ones(data2d.shape).astype(np.bool) mask2d[self.mesh_yidx, self.mesh_xidx] = False return np.ma.masked_array(data2d, mask=mask2d)
python
def _make_2d_array(self, data): """ Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices ``mesh_idx``. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. Returns ------- result : 2D `~numpy.ma.MaskedArray` A 2D masked array. Pixels not defined in ``mesh_idx`` are masked. """ if data.shape != self.mesh_idx.shape: raise ValueError('data and mesh_idx must have the same shape') if np.ma.is_masked(data): raise ValueError('data must not be a masked array') data2d = np.zeros(self._mesh_shape).astype(data.dtype) data2d[self.mesh_yidx, self.mesh_xidx] = data if len(self.mesh_idx) == self.nboxes: # no meshes were masked return data2d else: # some meshes were masked mask2d = np.ones(data2d.shape).astype(np.bool) mask2d[self.mesh_yidx, self.mesh_xidx] = False return np.ma.masked_array(data2d, mask=mask2d)
[ "def", "_make_2d_array", "(", "self", ",", "data", ")", ":", "if", "data", ".", "shape", "!=", "self", ".", "mesh_idx", ".", "shape", ":", "raise", "ValueError", "(", "'data and mesh_idx must have the same shape'", ")", "if", "np", ".", "ma", ".", "is_masked", "(", "data", ")", ":", "raise", "ValueError", "(", "'data must not be a masked array'", ")", "data2d", "=", "np", ".", "zeros", "(", "self", ".", "_mesh_shape", ")", ".", "astype", "(", "data", ".", "dtype", ")", "data2d", "[", "self", ".", "mesh_yidx", ",", "self", ".", "mesh_xidx", "]", "=", "data", "if", "len", "(", "self", ".", "mesh_idx", ")", "==", "self", ".", "nboxes", ":", "# no meshes were masked", "return", "data2d", "else", ":", "# some meshes were masked", "mask2d", "=", "np", ".", "ones", "(", "data2d", ".", "shape", ")", ".", "astype", "(", "np", ".", "bool", ")", "mask2d", "[", "self", ".", "mesh_yidx", ",", "self", ".", "mesh_xidx", "]", "=", "False", "return", "np", ".", "ma", ".", "masked_array", "(", "data2d", ",", "mask", "=", "mask2d", ")" ]
Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices ``mesh_idx``. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. Returns ------- result : 2D `~numpy.ma.MaskedArray` A 2D masked array. Pixels not defined in ``mesh_idx`` are masked.
[ "Convert", "a", "1D", "array", "of", "mesh", "values", "to", "a", "masked", "2D", "mesh", "array", "given", "the", "1D", "mesh", "indices", "mesh_idx", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L501-L535
train
astropy/photutils
photutils/background/background_2d.py
Background2D._interpolate_meshes
def _interpolate_meshes(self, data, n_neighbors=10, eps=0., power=1., reg=0.): """ Use IDW interpolation to fill in any masked pixels in the low-resolution 2D mesh background and background RMS images. This is required to use a regular-grid interpolator to expand the low-resolution image to the full size image. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. n_neighbors : int, optional The maximum number of nearest neighbors to use during the interpolation. eps : float, optional Set to use approximate nearest neighbors; the kth neighbor is guaranteed to be no further than (1 + ``eps``) times the distance to the real *k*-th nearest neighbor. See `scipy.spatial.cKDTree.query` for further information. power : float, optional The power of the inverse distance used for the interpolation weights. See the Notes section for more details. reg : float, optional The regularization parameter. It may be used to control the smoothness of the interpolator. See the Notes section for more details. Returns ------- result : 2D `~numpy.ndarray` A 2D array of the mesh values where masked pixels have been filled by IDW interpolation. """ yx = np.column_stack([self.mesh_yidx, self.mesh_xidx]) coords = np.array(list(product(range(self.nyboxes), range(self.nxboxes)))) f = ShepardIDWInterpolator(yx, data) img1d = f(coords, n_neighbors=n_neighbors, power=power, eps=eps, reg=reg) return img1d.reshape(self._mesh_shape)
python
def _interpolate_meshes(self, data, n_neighbors=10, eps=0., power=1., reg=0.): """ Use IDW interpolation to fill in any masked pixels in the low-resolution 2D mesh background and background RMS images. This is required to use a regular-grid interpolator to expand the low-resolution image to the full size image. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. n_neighbors : int, optional The maximum number of nearest neighbors to use during the interpolation. eps : float, optional Set to use approximate nearest neighbors; the kth neighbor is guaranteed to be no further than (1 + ``eps``) times the distance to the real *k*-th nearest neighbor. See `scipy.spatial.cKDTree.query` for further information. power : float, optional The power of the inverse distance used for the interpolation weights. See the Notes section for more details. reg : float, optional The regularization parameter. It may be used to control the smoothness of the interpolator. See the Notes section for more details. Returns ------- result : 2D `~numpy.ndarray` A 2D array of the mesh values where masked pixels have been filled by IDW interpolation. """ yx = np.column_stack([self.mesh_yidx, self.mesh_xidx]) coords = np.array(list(product(range(self.nyboxes), range(self.nxboxes)))) f = ShepardIDWInterpolator(yx, data) img1d = f(coords, n_neighbors=n_neighbors, power=power, eps=eps, reg=reg) return img1d.reshape(self._mesh_shape)
[ "def", "_interpolate_meshes", "(", "self", ",", "data", ",", "n_neighbors", "=", "10", ",", "eps", "=", "0.", ",", "power", "=", "1.", ",", "reg", "=", "0.", ")", ":", "yx", "=", "np", ".", "column_stack", "(", "[", "self", ".", "mesh_yidx", ",", "self", ".", "mesh_xidx", "]", ")", "coords", "=", "np", ".", "array", "(", "list", "(", "product", "(", "range", "(", "self", ".", "nyboxes", ")", ",", "range", "(", "self", ".", "nxboxes", ")", ")", ")", ")", "f", "=", "ShepardIDWInterpolator", "(", "yx", ",", "data", ")", "img1d", "=", "f", "(", "coords", ",", "n_neighbors", "=", "n_neighbors", ",", "power", "=", "power", ",", "eps", "=", "eps", ",", "reg", "=", "reg", ")", "return", "img1d", ".", "reshape", "(", "self", ".", "_mesh_shape", ")" ]
Use IDW interpolation to fill in any masked pixels in the low-resolution 2D mesh background and background RMS images. This is required to use a regular-grid interpolator to expand the low-resolution image to the full size image. Parameters ---------- data : 1D `~numpy.ndarray` A 1D array of mesh values. n_neighbors : int, optional The maximum number of nearest neighbors to use during the interpolation. eps : float, optional Set to use approximate nearest neighbors; the kth neighbor is guaranteed to be no further than (1 + ``eps``) times the distance to the real *k*-th nearest neighbor. See `scipy.spatial.cKDTree.query` for further information. power : float, optional The power of the inverse distance used for the interpolation weights. See the Notes section for more details. reg : float, optional The regularization parameter. It may be used to control the smoothness of the interpolator. See the Notes section for more details. Returns ------- result : 2D `~numpy.ndarray` A 2D array of the mesh values where masked pixels have been filled by IDW interpolation.
[ "Use", "IDW", "interpolation", "to", "fill", "in", "any", "masked", "pixels", "in", "the", "low", "-", "resolution", "2D", "mesh", "background", "and", "background", "RMS", "images", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L537-L584
train
astropy/photutils
photutils/background/background_2d.py
Background2D._selective_filter
def _selective_filter(self, data, indices): """ Selectively filter only pixels above ``filter_threshold`` in the background mesh. The same pixels are filtered in both the background and background RMS meshes. Parameters ---------- data : 2D `~numpy.ndarray` A 2D array of mesh values. indices : 2 tuple of int A tuple of the ``y`` and ``x`` indices of the pixels to filter. Returns ------- filtered_data : 2D `~numpy.ndarray` The filtered 2D array of mesh values. """ data_out = np.copy(data) for i, j in zip(*indices): yfs, xfs = self.filter_size hyfs, hxfs = yfs // 2, xfs // 2 y0, y1 = max(i - hyfs, 0), min(i - hyfs + yfs, data.shape[0]) x0, x1 = max(j - hxfs, 0), min(j - hxfs + xfs, data.shape[1]) data_out[i, j] = np.median(data[y0:y1, x0:x1]) return data_out
python
def _selective_filter(self, data, indices): """ Selectively filter only pixels above ``filter_threshold`` in the background mesh. The same pixels are filtered in both the background and background RMS meshes. Parameters ---------- data : 2D `~numpy.ndarray` A 2D array of mesh values. indices : 2 tuple of int A tuple of the ``y`` and ``x`` indices of the pixels to filter. Returns ------- filtered_data : 2D `~numpy.ndarray` The filtered 2D array of mesh values. """ data_out = np.copy(data) for i, j in zip(*indices): yfs, xfs = self.filter_size hyfs, hxfs = yfs // 2, xfs // 2 y0, y1 = max(i - hyfs, 0), min(i - hyfs + yfs, data.shape[0]) x0, x1 = max(j - hxfs, 0), min(j - hxfs + xfs, data.shape[1]) data_out[i, j] = np.median(data[y0:y1, x0:x1]) return data_out
[ "def", "_selective_filter", "(", "self", ",", "data", ",", "indices", ")", ":", "data_out", "=", "np", ".", "copy", "(", "data", ")", "for", "i", ",", "j", "in", "zip", "(", "*", "indices", ")", ":", "yfs", ",", "xfs", "=", "self", ".", "filter_size", "hyfs", ",", "hxfs", "=", "yfs", "//", "2", ",", "xfs", "//", "2", "y0", ",", "y1", "=", "max", "(", "i", "-", "hyfs", ",", "0", ")", ",", "min", "(", "i", "-", "hyfs", "+", "yfs", ",", "data", ".", "shape", "[", "0", "]", ")", "x0", ",", "x1", "=", "max", "(", "j", "-", "hxfs", ",", "0", ")", ",", "min", "(", "j", "-", "hxfs", "+", "xfs", ",", "data", ".", "shape", "[", "1", "]", ")", "data_out", "[", "i", ",", "j", "]", "=", "np", ".", "median", "(", "data", "[", "y0", ":", "y1", ",", "x0", ":", "x1", "]", ")", "return", "data_out" ]
Selectively filter only pixels above ``filter_threshold`` in the background mesh. The same pixels are filtered in both the background and background RMS meshes. Parameters ---------- data : 2D `~numpy.ndarray` A 2D array of mesh values. indices : 2 tuple of int A tuple of the ``y`` and ``x`` indices of the pixels to filter. Returns ------- filtered_data : 2D `~numpy.ndarray` The filtered 2D array of mesh values.
[ "Selectively", "filter", "only", "pixels", "above", "filter_threshold", "in", "the", "background", "mesh", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L586-L617
train
astropy/photutils
photutils/background/background_2d.py
Background2D._filter_meshes
def _filter_meshes(self): """ Apply a 2D median filter to the low-resolution 2D mesh, including only pixels inside the image at the borders. """ from scipy.ndimage import generic_filter try: nanmedian_func = np.nanmedian # numpy >= 1.9 except AttributeError: # pragma: no cover from scipy.stats import nanmedian nanmedian_func = nanmedian if self.filter_threshold is None: # filter the entire arrays self.background_mesh = generic_filter( self.background_mesh, nanmedian_func, size=self.filter_size, mode='constant', cval=np.nan) self.background_rms_mesh = generic_filter( self.background_rms_mesh, nanmedian_func, size=self.filter_size, mode='constant', cval=np.nan) else: # selectively filter indices = np.nonzero(self.background_mesh > self.filter_threshold) self.background_mesh = self._selective_filter( self.background_mesh, indices) self.background_rms_mesh = self._selective_filter( self.background_rms_mesh, indices) return
python
def _filter_meshes(self): """ Apply a 2D median filter to the low-resolution 2D mesh, including only pixels inside the image at the borders. """ from scipy.ndimage import generic_filter try: nanmedian_func = np.nanmedian # numpy >= 1.9 except AttributeError: # pragma: no cover from scipy.stats import nanmedian nanmedian_func = nanmedian if self.filter_threshold is None: # filter the entire arrays self.background_mesh = generic_filter( self.background_mesh, nanmedian_func, size=self.filter_size, mode='constant', cval=np.nan) self.background_rms_mesh = generic_filter( self.background_rms_mesh, nanmedian_func, size=self.filter_size, mode='constant', cval=np.nan) else: # selectively filter indices = np.nonzero(self.background_mesh > self.filter_threshold) self.background_mesh = self._selective_filter( self.background_mesh, indices) self.background_rms_mesh = self._selective_filter( self.background_rms_mesh, indices) return
[ "def", "_filter_meshes", "(", "self", ")", ":", "from", "scipy", ".", "ndimage", "import", "generic_filter", "try", ":", "nanmedian_func", "=", "np", ".", "nanmedian", "# numpy >= 1.9", "except", "AttributeError", ":", "# pragma: no cover", "from", "scipy", ".", "stats", "import", "nanmedian", "nanmedian_func", "=", "nanmedian", "if", "self", ".", "filter_threshold", "is", "None", ":", "# filter the entire arrays", "self", ".", "background_mesh", "=", "generic_filter", "(", "self", ".", "background_mesh", ",", "nanmedian_func", ",", "size", "=", "self", ".", "filter_size", ",", "mode", "=", "'constant'", ",", "cval", "=", "np", ".", "nan", ")", "self", ".", "background_rms_mesh", "=", "generic_filter", "(", "self", ".", "background_rms_mesh", ",", "nanmedian_func", ",", "size", "=", "self", ".", "filter_size", ",", "mode", "=", "'constant'", ",", "cval", "=", "np", ".", "nan", ")", "else", ":", "# selectively filter", "indices", "=", "np", ".", "nonzero", "(", "self", ".", "background_mesh", ">", "self", ".", "filter_threshold", ")", "self", ".", "background_mesh", "=", "self", ".", "_selective_filter", "(", "self", ".", "background_mesh", ",", "indices", ")", "self", ".", "background_rms_mesh", "=", "self", ".", "_selective_filter", "(", "self", ".", "background_rms_mesh", ",", "indices", ")", "return" ]
Apply a 2D median filter to the low-resolution 2D mesh, including only pixels inside the image at the borders.
[ "Apply", "a", "2D", "median", "filter", "to", "the", "low", "-", "resolution", "2D", "mesh", "including", "only", "pixels", "inside", "the", "image", "at", "the", "borders", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L619-L648
train
astropy/photutils
photutils/background/background_2d.py
Background2D._calc_bkg_bkgrms
def _calc_bkg_bkgrms(self): """ Calculate the background and background RMS estimate in each of the meshes. Both meshes are computed at the same time here method because the filtering of both depends on the background mesh. The ``background_mesh`` and ``background_rms_mesh`` images are equivalent to the low-resolution "MINIBACKGROUND" and "MINIBACK_RMS" background maps in SExtractor, respectively. """ if self.sigma_clip is not None: data_sigclip = self.sigma_clip(self._mesh_data, axis=1) else: data_sigclip = self._mesh_data del self._mesh_data # preform mesh rejection on sigma-clipped data (i.e. for any # newly-masked pixels) idx = self._select_meshes(data_sigclip) self.mesh_idx = self.mesh_idx[idx] # indices for the output mesh self._data_sigclip = data_sigclip[idx] # always a 2D masked array self._mesh_shape = (self.nyboxes, self.nxboxes) self.mesh_yidx, self.mesh_xidx = np.unravel_index(self.mesh_idx, self._mesh_shape) # These properties are needed later to calculate # background_mesh_ma and background_rms_mesh_ma. Note that _bkg1d # and _bkgrms1d are masked arrays, but the mask should always be # False. self._bkg1d = self.bkg_estimator(self._data_sigclip, axis=1) self._bkgrms1d = self.bkgrms_estimator(self._data_sigclip, axis=1) # make the unfiltered 2D mesh arrays (these are not masked) if len(self._bkg1d) == self.nboxes: bkg = self._make_2d_array(self._bkg1d) bkgrms = self._make_2d_array(self._bkgrms1d) else: bkg = self._interpolate_meshes(self._bkg1d) bkgrms = self._interpolate_meshes(self._bkgrms1d) self._background_mesh_unfiltered = bkg self._background_rms_mesh_unfiltered = bkgrms self.background_mesh = bkg self.background_rms_mesh = bkgrms # filter the 2D mesh arrays if not np.array_equal(self.filter_size, [1, 1]): self._filter_meshes() return
python
def _calc_bkg_bkgrms(self): """ Calculate the background and background RMS estimate in each of the meshes. Both meshes are computed at the same time here method because the filtering of both depends on the background mesh. The ``background_mesh`` and ``background_rms_mesh`` images are equivalent to the low-resolution "MINIBACKGROUND" and "MINIBACK_RMS" background maps in SExtractor, respectively. """ if self.sigma_clip is not None: data_sigclip = self.sigma_clip(self._mesh_data, axis=1) else: data_sigclip = self._mesh_data del self._mesh_data # preform mesh rejection on sigma-clipped data (i.e. for any # newly-masked pixels) idx = self._select_meshes(data_sigclip) self.mesh_idx = self.mesh_idx[idx] # indices for the output mesh self._data_sigclip = data_sigclip[idx] # always a 2D masked array self._mesh_shape = (self.nyboxes, self.nxboxes) self.mesh_yidx, self.mesh_xidx = np.unravel_index(self.mesh_idx, self._mesh_shape) # These properties are needed later to calculate # background_mesh_ma and background_rms_mesh_ma. Note that _bkg1d # and _bkgrms1d are masked arrays, but the mask should always be # False. self._bkg1d = self.bkg_estimator(self._data_sigclip, axis=1) self._bkgrms1d = self.bkgrms_estimator(self._data_sigclip, axis=1) # make the unfiltered 2D mesh arrays (these are not masked) if len(self._bkg1d) == self.nboxes: bkg = self._make_2d_array(self._bkg1d) bkgrms = self._make_2d_array(self._bkgrms1d) else: bkg = self._interpolate_meshes(self._bkg1d) bkgrms = self._interpolate_meshes(self._bkgrms1d) self._background_mesh_unfiltered = bkg self._background_rms_mesh_unfiltered = bkgrms self.background_mesh = bkg self.background_rms_mesh = bkgrms # filter the 2D mesh arrays if not np.array_equal(self.filter_size, [1, 1]): self._filter_meshes() return
[ "def", "_calc_bkg_bkgrms", "(", "self", ")", ":", "if", "self", ".", "sigma_clip", "is", "not", "None", ":", "data_sigclip", "=", "self", ".", "sigma_clip", "(", "self", ".", "_mesh_data", ",", "axis", "=", "1", ")", "else", ":", "data_sigclip", "=", "self", ".", "_mesh_data", "del", "self", ".", "_mesh_data", "# preform mesh rejection on sigma-clipped data (i.e. for any", "# newly-masked pixels)", "idx", "=", "self", ".", "_select_meshes", "(", "data_sigclip", ")", "self", ".", "mesh_idx", "=", "self", ".", "mesh_idx", "[", "idx", "]", "# indices for the output mesh", "self", ".", "_data_sigclip", "=", "data_sigclip", "[", "idx", "]", "# always a 2D masked array", "self", ".", "_mesh_shape", "=", "(", "self", ".", "nyboxes", ",", "self", ".", "nxboxes", ")", "self", ".", "mesh_yidx", ",", "self", ".", "mesh_xidx", "=", "np", ".", "unravel_index", "(", "self", ".", "mesh_idx", ",", "self", ".", "_mesh_shape", ")", "# These properties are needed later to calculate", "# background_mesh_ma and background_rms_mesh_ma. Note that _bkg1d", "# and _bkgrms1d are masked arrays, but the mask should always be", "# False.", "self", ".", "_bkg1d", "=", "self", ".", "bkg_estimator", "(", "self", ".", "_data_sigclip", ",", "axis", "=", "1", ")", "self", ".", "_bkgrms1d", "=", "self", ".", "bkgrms_estimator", "(", "self", ".", "_data_sigclip", ",", "axis", "=", "1", ")", "# make the unfiltered 2D mesh arrays (these are not masked)", "if", "len", "(", "self", ".", "_bkg1d", ")", "==", "self", ".", "nboxes", ":", "bkg", "=", "self", ".", "_make_2d_array", "(", "self", ".", "_bkg1d", ")", "bkgrms", "=", "self", ".", "_make_2d_array", "(", "self", ".", "_bkgrms1d", ")", "else", ":", "bkg", "=", "self", ".", "_interpolate_meshes", "(", "self", ".", "_bkg1d", ")", "bkgrms", "=", "self", ".", "_interpolate_meshes", "(", "self", ".", "_bkgrms1d", ")", "self", ".", "_background_mesh_unfiltered", "=", "bkg", "self", ".", "_background_rms_mesh_unfiltered", "=", "bkgrms", "self", ".", "background_mesh", "=", "bkg", "self", ".", "background_rms_mesh", "=", "bkgrms", "# filter the 2D mesh arrays", "if", "not", "np", ".", "array_equal", "(", "self", ".", "filter_size", ",", "[", "1", ",", "1", "]", ")", ":", "self", ".", "_filter_meshes", "(", ")", "return" ]
Calculate the background and background RMS estimate in each of the meshes. Both meshes are computed at the same time here method because the filtering of both depends on the background mesh. The ``background_mesh`` and ``background_rms_mesh`` images are equivalent to the low-resolution "MINIBACKGROUND" and "MINIBACK_RMS" background maps in SExtractor, respectively.
[ "Calculate", "the", "background", "and", "background", "RMS", "estimate", "in", "each", "of", "the", "meshes", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L650-L703
train
astropy/photutils
photutils/background/background_2d.py
Background2D._calc_coordinates
def _calc_coordinates(self): """ Calculate the coordinates to use when calling an interpolator. These are needed for `Background2D` and `BackgroundIDW2D`. Regular-grid interpolators require a 2D array of values. Some require a 2D meshgrid of x and y. Other require a strictly increasing 1D array of the x and y ranges. """ # the position coordinates used to initialize an interpolation self.y = (self.mesh_yidx * self.box_size[0] + (self.box_size[0] - 1) / 2.) self.x = (self.mesh_xidx * self.box_size[1] + (self.box_size[1] - 1) / 2.) self.yx = np.column_stack([self.y, self.x]) # the position coordinates used when calling an interpolator nx, ny = self.data.shape self.data_coords = np.array(list(product(range(ny), range(nx))))
python
def _calc_coordinates(self): """ Calculate the coordinates to use when calling an interpolator. These are needed for `Background2D` and `BackgroundIDW2D`. Regular-grid interpolators require a 2D array of values. Some require a 2D meshgrid of x and y. Other require a strictly increasing 1D array of the x and y ranges. """ # the position coordinates used to initialize an interpolation self.y = (self.mesh_yidx * self.box_size[0] + (self.box_size[0] - 1) / 2.) self.x = (self.mesh_xidx * self.box_size[1] + (self.box_size[1] - 1) / 2.) self.yx = np.column_stack([self.y, self.x]) # the position coordinates used when calling an interpolator nx, ny = self.data.shape self.data_coords = np.array(list(product(range(ny), range(nx))))
[ "def", "_calc_coordinates", "(", "self", ")", ":", "# the position coordinates used to initialize an interpolation", "self", ".", "y", "=", "(", "self", ".", "mesh_yidx", "*", "self", ".", "box_size", "[", "0", "]", "+", "(", "self", ".", "box_size", "[", "0", "]", "-", "1", ")", "/", "2.", ")", "self", ".", "x", "=", "(", "self", ".", "mesh_xidx", "*", "self", ".", "box_size", "[", "1", "]", "+", "(", "self", ".", "box_size", "[", "1", "]", "-", "1", ")", "/", "2.", ")", "self", ".", "yx", "=", "np", ".", "column_stack", "(", "[", "self", ".", "y", ",", "self", ".", "x", "]", ")", "# the position coordinates used when calling an interpolator", "nx", ",", "ny", "=", "self", ".", "data", ".", "shape", "self", ".", "data_coords", "=", "np", ".", "array", "(", "list", "(", "product", "(", "range", "(", "ny", ")", ",", "range", "(", "nx", ")", ")", ")", ")" ]
Calculate the coordinates to use when calling an interpolator. These are needed for `Background2D` and `BackgroundIDW2D`. Regular-grid interpolators require a 2D array of values. Some require a 2D meshgrid of x and y. Other require a strictly increasing 1D array of the x and y ranges.
[ "Calculate", "the", "coordinates", "to", "use", "when", "calling", "an", "interpolator", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L705-L725
train
astropy/photutils
photutils/background/background_2d.py
Background2D.plot_meshes
def plot_meshes(self, ax=None, marker='+', color='blue', outlines=False, **kwargs): """ Plot the low-resolution mesh boxes on a matplotlib Axes instance. Parameters ---------- ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current ``Axes`` instance is used. marker : str, optional The marker to use to mark the center of the boxes. Default is '+'. color : str, optional The color for the markers and the box outlines. Default is 'blue'. outlines : bool, optional Whether or not to plot the box outlines in addition to the box centers. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Used only if ``outlines`` is True. """ import matplotlib.pyplot as plt kwargs['color'] = color if ax is None: ax = plt.gca() ax.scatter(self.x, self.y, marker=marker, color=color) if outlines: from ..aperture import RectangularAperture xy = np.column_stack([self.x, self.y]) apers = RectangularAperture(xy, self.box_size[1], self.box_size[0], 0.) apers.plot(ax=ax, **kwargs) return
python
def plot_meshes(self, ax=None, marker='+', color='blue', outlines=False, **kwargs): """ Plot the low-resolution mesh boxes on a matplotlib Axes instance. Parameters ---------- ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current ``Axes`` instance is used. marker : str, optional The marker to use to mark the center of the boxes. Default is '+'. color : str, optional The color for the markers and the box outlines. Default is 'blue'. outlines : bool, optional Whether or not to plot the box outlines in addition to the box centers. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Used only if ``outlines`` is True. """ import matplotlib.pyplot as plt kwargs['color'] = color if ax is None: ax = plt.gca() ax.scatter(self.x, self.y, marker=marker, color=color) if outlines: from ..aperture import RectangularAperture xy = np.column_stack([self.x, self.y]) apers = RectangularAperture(xy, self.box_size[1], self.box_size[0], 0.) apers.plot(ax=ax, **kwargs) return
[ "def", "plot_meshes", "(", "self", ",", "ax", "=", "None", ",", "marker", "=", "'+'", ",", "color", "=", "'blue'", ",", "outlines", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "kwargs", "[", "'color'", "]", "=", "color", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "ax", ".", "scatter", "(", "self", ".", "x", ",", "self", ".", "y", ",", "marker", "=", "marker", ",", "color", "=", "color", ")", "if", "outlines", ":", "from", ".", ".", "aperture", "import", "RectangularAperture", "xy", "=", "np", ".", "column_stack", "(", "[", "self", ".", "x", ",", "self", ".", "y", "]", ")", "apers", "=", "RectangularAperture", "(", "xy", ",", "self", ".", "box_size", "[", "1", "]", ",", "self", ".", "box_size", "[", "0", "]", ",", "0.", ")", "apers", ".", "plot", "(", "ax", "=", "ax", ",", "*", "*", "kwargs", ")", "return" ]
Plot the low-resolution mesh boxes on a matplotlib Axes instance. Parameters ---------- ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current ``Axes`` instance is used. marker : str, optional The marker to use to mark the center of the boxes. Default is '+'. color : str, optional The color for the markers and the box outlines. Default is 'blue'. outlines : bool, optional Whether or not to plot the box outlines in addition to the box centers. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Used only if ``outlines`` is True.
[ "Plot", "the", "low", "-", "resolution", "mesh", "boxes", "on", "a", "matplotlib", "Axes", "instance", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/background_2d.py#L798-L839
train
astropy/photutils
photutils/isophote/sample.py
EllipseSample.extract
def extract(self): """ Extract sample data by scanning an elliptical path over the image array. Returns ------- result : 2D `~numpy.ndarray` The rows of the array contain the angles, radii, and extracted intensity values, respectively. """ # the sample values themselves are kept cached to prevent # multiple calls to the integrator code. if self.values is not None: return self.values else: s = self._extract() self.values = s return s
python
def extract(self): """ Extract sample data by scanning an elliptical path over the image array. Returns ------- result : 2D `~numpy.ndarray` The rows of the array contain the angles, radii, and extracted intensity values, respectively. """ # the sample values themselves are kept cached to prevent # multiple calls to the integrator code. if self.values is not None: return self.values else: s = self._extract() self.values = s return s
[ "def", "extract", "(", "self", ")", ":", "# the sample values themselves are kept cached to prevent", "# multiple calls to the integrator code.", "if", "self", ".", "values", "is", "not", "None", ":", "return", "self", ".", "values", "else", ":", "s", "=", "self", ".", "_extract", "(", ")", "self", ".", "values", "=", "s", "return", "s" ]
Extract sample data by scanning an elliptical path over the image array. Returns ------- result : 2D `~numpy.ndarray` The rows of the array contain the angles, radii, and extracted intensity values, respectively.
[ "Extract", "sample", "data", "by", "scanning", "an", "elliptical", "path", "over", "the", "image", "array", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/sample.py#L133-L152
train
astropy/photutils
photutils/isophote/sample.py
EllipseSample.update
def update(self): """ Update this `~photutils.isophote.EllipseSample` instance. This method calls the :meth:`~photutils.isophote.EllipseSample.extract` method to get the values that match the current ``geometry`` attribute, and then computes the the mean intensity, local gradient, and other associated quantities. """ step = self.geometry.astep # Update the mean value first, using extraction from main sample. s = self.extract() self.mean = np.mean(s[2]) # Get sample with same geometry but at a different distance from # center. Estimate gradient from there. gradient, gradient_error = self._get_gradient(step) # Check for meaningful gradient. If no meaningful gradient, try # another sample, this time using larger radius. Meaningful # gradient means something shallower, but still close to within # a factor 3 from previous gradient estimate. If no previous # estimate is available, guess it. previous_gradient = self.gradient if not previous_gradient: previous_gradient = -0.05 # good enough, based on usage if gradient >= (previous_gradient / 3.): # gradient is negative! gradient, gradient_error = self._get_gradient(2 * step) # If still no meaningful gradient can be measured, try with # previous one, slightly shallower. A factor 0.8 is not too far # from what is expected from geometrical sampling steps of 10-20% # and a deVaucouleurs law or an exponential disk (at least at its # inner parts, r <~ 5 req). Gradient error is meaningless in this # case. if gradient >= (previous_gradient / 3.): gradient = previous_gradient * 0.8 gradient_error = None self.gradient = gradient self.gradient_error = gradient_error if gradient_error: self.gradient_relative_error = gradient_error / np.abs(gradient) else: self.gradient_relative_error = None
python
def update(self): """ Update this `~photutils.isophote.EllipseSample` instance. This method calls the :meth:`~photutils.isophote.EllipseSample.extract` method to get the values that match the current ``geometry`` attribute, and then computes the the mean intensity, local gradient, and other associated quantities. """ step = self.geometry.astep # Update the mean value first, using extraction from main sample. s = self.extract() self.mean = np.mean(s[2]) # Get sample with same geometry but at a different distance from # center. Estimate gradient from there. gradient, gradient_error = self._get_gradient(step) # Check for meaningful gradient. If no meaningful gradient, try # another sample, this time using larger radius. Meaningful # gradient means something shallower, but still close to within # a factor 3 from previous gradient estimate. If no previous # estimate is available, guess it. previous_gradient = self.gradient if not previous_gradient: previous_gradient = -0.05 # good enough, based on usage if gradient >= (previous_gradient / 3.): # gradient is negative! gradient, gradient_error = self._get_gradient(2 * step) # If still no meaningful gradient can be measured, try with # previous one, slightly shallower. A factor 0.8 is not too far # from what is expected from geometrical sampling steps of 10-20% # and a deVaucouleurs law or an exponential disk (at least at its # inner parts, r <~ 5 req). Gradient error is meaningless in this # case. if gradient >= (previous_gradient / 3.): gradient = previous_gradient * 0.8 gradient_error = None self.gradient = gradient self.gradient_error = gradient_error if gradient_error: self.gradient_relative_error = gradient_error / np.abs(gradient) else: self.gradient_relative_error = None
[ "def", "update", "(", "self", ")", ":", "step", "=", "self", ".", "geometry", ".", "astep", "# Update the mean value first, using extraction from main sample.", "s", "=", "self", ".", "extract", "(", ")", "self", ".", "mean", "=", "np", ".", "mean", "(", "s", "[", "2", "]", ")", "# Get sample with same geometry but at a different distance from", "# center. Estimate gradient from there.", "gradient", ",", "gradient_error", "=", "self", ".", "_get_gradient", "(", "step", ")", "# Check for meaningful gradient. If no meaningful gradient, try", "# another sample, this time using larger radius. Meaningful", "# gradient means something shallower, but still close to within", "# a factor 3 from previous gradient estimate. If no previous", "# estimate is available, guess it.", "previous_gradient", "=", "self", ".", "gradient", "if", "not", "previous_gradient", ":", "previous_gradient", "=", "-", "0.05", "# good enough, based on usage", "if", "gradient", ">=", "(", "previous_gradient", "/", "3.", ")", ":", "# gradient is negative!", "gradient", ",", "gradient_error", "=", "self", ".", "_get_gradient", "(", "2", "*", "step", ")", "# If still no meaningful gradient can be measured, try with", "# previous one, slightly shallower. A factor 0.8 is not too far", "# from what is expected from geometrical sampling steps of 10-20%", "# and a deVaucouleurs law or an exponential disk (at least at its", "# inner parts, r <~ 5 req). Gradient error is meaningless in this", "# case.", "if", "gradient", ">=", "(", "previous_gradient", "/", "3.", ")", ":", "gradient", "=", "previous_gradient", "*", "0.8", "gradient_error", "=", "None", "self", ".", "gradient", "=", "gradient", "self", ".", "gradient_error", "=", "gradient_error", "if", "gradient_error", ":", "self", ".", "gradient_relative_error", "=", "gradient_error", "/", "np", ".", "abs", "(", "gradient", ")", "else", ":", "self", ".", "gradient_relative_error", "=", "None" ]
Update this `~photutils.isophote.EllipseSample` instance. This method calls the :meth:`~photutils.isophote.EllipseSample.extract` method to get the values that match the current ``geometry`` attribute, and then computes the the mean intensity, local gradient, and other associated quantities.
[ "Update", "this", "~photutils", ".", "isophote", ".", "EllipseSample", "instance", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/sample.py#L279-L327
train
astropy/photutils
photutils/isophote/fitter.py
EllipseFitter.fit
def fit(self, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, going_inwards=False): """ Fit an elliptical isophote. Parameters ---------- conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter in the `~photutils.isophote.EllipseSample` class). The default is `False`. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote, which also contains fit status information. Examples -------- >>> from photutils.isophote import EllipseSample, EllipseFitter >>> sample = EllipseSample(data, sma=10.) >>> fitter = EllipseFitter(sample) >>> isophote = fitter.fit() """ sample = self._sample # this flag signals that limiting gradient error (`maxgerr`) # wasn't exceeded yet. lexceed = False # here we keep track of the sample that caused the minimum harmonic # amplitude(in absolute value). This will eventually be used to # build the resulting Isophote in cases where iterations run to # the maximum allowed (maxit), or the maximum number of flagged # data points (fflag) is reached. minimum_amplitude_value = np.Inf minimum_amplitude_sample = None for iter in range(maxit): # Force the sample to compute its gradient and associated values. sample.update() # The extract() method returns sampled values as a 2-d numpy array # with the following structure: # values[0] = 1-d array with angles # values[1] = 1-d array with radii # values[2] = 1-d array with intensity values = sample.extract() # Fit harmonic coefficients. Failure in fitting is # a fatal error; terminate immediately with sample # marked as invalid. try: coeffs = fit_first_and_second_harmonics(values[0], values[2]) except Exception as e: log.info(e) return Isophote(sample, iter+1, False, 3) coeffs = coeffs[0] # largest harmonic in absolute value drives the correction. largest_harmonic_index = np.argmax(np.abs(coeffs[1:])) largest_harmonic = coeffs[1:][largest_harmonic_index] # see if the amplitude decreased; if yes, keep the # corresponding sample for eventual later use. if abs(largest_harmonic) < minimum_amplitude_value: minimum_amplitude_value = abs(largest_harmonic) minimum_amplitude_sample = sample # check if converged model = first_and_second_harmonic_function(values[0], coeffs) residual = values[2] - model if ((conver * sample.sector_area * np.std(residual)) > np.abs(largest_harmonic)): # Got a valid solution. But before returning, ensure # that a minimum of iterations has run. if iter >= minit-1: sample.update() return Isophote(sample, iter+1, True, 0) # it may not have converged yet, but the sample contains too # many invalid data points: return. if sample.actual_points < (sample.total_points * fflag): # when too many data points were flagged, return the # best fit sample instead of the current one. minimum_amplitude_sample.update() return Isophote(minimum_amplitude_sample, iter+1, True, 1) # pick appropriate corrector code. corrector = _correctors[largest_harmonic_index] # generate *NEW* EllipseSample instance with corrected # parameter. Note that this instance is still devoid of other # information besides its geometry. It needs to be explicitly # updated for computations to proceed. We have to build a new # EllipseSample instance every time because of the lazy # extraction process used by EllipseSample code. To minimize # the number of calls to the area integrators, we pay a # (hopefully smaller) price here, by having multiple calls to # the EllipseSample constructor. sample = corrector.correct(sample, largest_harmonic) sample.update() # see if any abnormal (or unusual) conditions warrant # the change to non-iterative mode, or go-inwards mode. proceed, lexceed = self._check_conditions( sample, maxgerr, going_inwards, lexceed) if not proceed: sample.update() return Isophote(sample, iter+1, True, -1) # Got to the maximum number of iterations. Return with # code 2, and handle it as a valid isophote. Use the # best fit sample instead of the current one. minimum_amplitude_sample.update() return Isophote(minimum_amplitude_sample, maxit, True, 2)
python
def fit(self, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, going_inwards=False): """ Fit an elliptical isophote. Parameters ---------- conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter in the `~photutils.isophote.EllipseSample` class). The default is `False`. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote, which also contains fit status information. Examples -------- >>> from photutils.isophote import EllipseSample, EllipseFitter >>> sample = EllipseSample(data, sma=10.) >>> fitter = EllipseFitter(sample) >>> isophote = fitter.fit() """ sample = self._sample # this flag signals that limiting gradient error (`maxgerr`) # wasn't exceeded yet. lexceed = False # here we keep track of the sample that caused the minimum harmonic # amplitude(in absolute value). This will eventually be used to # build the resulting Isophote in cases where iterations run to # the maximum allowed (maxit), or the maximum number of flagged # data points (fflag) is reached. minimum_amplitude_value = np.Inf minimum_amplitude_sample = None for iter in range(maxit): # Force the sample to compute its gradient and associated values. sample.update() # The extract() method returns sampled values as a 2-d numpy array # with the following structure: # values[0] = 1-d array with angles # values[1] = 1-d array with radii # values[2] = 1-d array with intensity values = sample.extract() # Fit harmonic coefficients. Failure in fitting is # a fatal error; terminate immediately with sample # marked as invalid. try: coeffs = fit_first_and_second_harmonics(values[0], values[2]) except Exception as e: log.info(e) return Isophote(sample, iter+1, False, 3) coeffs = coeffs[0] # largest harmonic in absolute value drives the correction. largest_harmonic_index = np.argmax(np.abs(coeffs[1:])) largest_harmonic = coeffs[1:][largest_harmonic_index] # see if the amplitude decreased; if yes, keep the # corresponding sample for eventual later use. if abs(largest_harmonic) < minimum_amplitude_value: minimum_amplitude_value = abs(largest_harmonic) minimum_amplitude_sample = sample # check if converged model = first_and_second_harmonic_function(values[0], coeffs) residual = values[2] - model if ((conver * sample.sector_area * np.std(residual)) > np.abs(largest_harmonic)): # Got a valid solution. But before returning, ensure # that a minimum of iterations has run. if iter >= minit-1: sample.update() return Isophote(sample, iter+1, True, 0) # it may not have converged yet, but the sample contains too # many invalid data points: return. if sample.actual_points < (sample.total_points * fflag): # when too many data points were flagged, return the # best fit sample instead of the current one. minimum_amplitude_sample.update() return Isophote(minimum_amplitude_sample, iter+1, True, 1) # pick appropriate corrector code. corrector = _correctors[largest_harmonic_index] # generate *NEW* EllipseSample instance with corrected # parameter. Note that this instance is still devoid of other # information besides its geometry. It needs to be explicitly # updated for computations to proceed. We have to build a new # EllipseSample instance every time because of the lazy # extraction process used by EllipseSample code. To minimize # the number of calls to the area integrators, we pay a # (hopefully smaller) price here, by having multiple calls to # the EllipseSample constructor. sample = corrector.correct(sample, largest_harmonic) sample.update() # see if any abnormal (or unusual) conditions warrant # the change to non-iterative mode, or go-inwards mode. proceed, lexceed = self._check_conditions( sample, maxgerr, going_inwards, lexceed) if not proceed: sample.update() return Isophote(sample, iter+1, True, -1) # Got to the maximum number of iterations. Return with # code 2, and handle it as a valid isophote. Use the # best fit sample instead of the current one. minimum_amplitude_sample.update() return Isophote(minimum_amplitude_sample, maxit, True, 2)
[ "def", "fit", "(", "self", ",", "conver", "=", "DEFAULT_CONVERGENCE", ",", "minit", "=", "DEFAULT_MINIT", ",", "maxit", "=", "DEFAULT_MAXIT", ",", "fflag", "=", "DEFAULT_FFLAG", ",", "maxgerr", "=", "DEFAULT_MAXGERR", ",", "going_inwards", "=", "False", ")", ":", "sample", "=", "self", ".", "_sample", "# this flag signals that limiting gradient error (`maxgerr`)", "# wasn't exceeded yet.", "lexceed", "=", "False", "# here we keep track of the sample that caused the minimum harmonic", "# amplitude(in absolute value). This will eventually be used to", "# build the resulting Isophote in cases where iterations run to", "# the maximum allowed (maxit), or the maximum number of flagged", "# data points (fflag) is reached.", "minimum_amplitude_value", "=", "np", ".", "Inf", "minimum_amplitude_sample", "=", "None", "for", "iter", "in", "range", "(", "maxit", ")", ":", "# Force the sample to compute its gradient and associated values.", "sample", ".", "update", "(", ")", "# The extract() method returns sampled values as a 2-d numpy array", "# with the following structure:", "# values[0] = 1-d array with angles", "# values[1] = 1-d array with radii", "# values[2] = 1-d array with intensity", "values", "=", "sample", ".", "extract", "(", ")", "# Fit harmonic coefficients. Failure in fitting is", "# a fatal error; terminate immediately with sample", "# marked as invalid.", "try", ":", "coeffs", "=", "fit_first_and_second_harmonics", "(", "values", "[", "0", "]", ",", "values", "[", "2", "]", ")", "except", "Exception", "as", "e", ":", "log", ".", "info", "(", "e", ")", "return", "Isophote", "(", "sample", ",", "iter", "+", "1", ",", "False", ",", "3", ")", "coeffs", "=", "coeffs", "[", "0", "]", "# largest harmonic in absolute value drives the correction.", "largest_harmonic_index", "=", "np", ".", "argmax", "(", "np", ".", "abs", "(", "coeffs", "[", "1", ":", "]", ")", ")", "largest_harmonic", "=", "coeffs", "[", "1", ":", "]", "[", "largest_harmonic_index", "]", "# see if the amplitude decreased; if yes, keep the", "# corresponding sample for eventual later use.", "if", "abs", "(", "largest_harmonic", ")", "<", "minimum_amplitude_value", ":", "minimum_amplitude_value", "=", "abs", "(", "largest_harmonic", ")", "minimum_amplitude_sample", "=", "sample", "# check if converged", "model", "=", "first_and_second_harmonic_function", "(", "values", "[", "0", "]", ",", "coeffs", ")", "residual", "=", "values", "[", "2", "]", "-", "model", "if", "(", "(", "conver", "*", "sample", ".", "sector_area", "*", "np", ".", "std", "(", "residual", ")", ")", ">", "np", ".", "abs", "(", "largest_harmonic", ")", ")", ":", "# Got a valid solution. But before returning, ensure", "# that a minimum of iterations has run.", "if", "iter", ">=", "minit", "-", "1", ":", "sample", ".", "update", "(", ")", "return", "Isophote", "(", "sample", ",", "iter", "+", "1", ",", "True", ",", "0", ")", "# it may not have converged yet, but the sample contains too", "# many invalid data points: return.", "if", "sample", ".", "actual_points", "<", "(", "sample", ".", "total_points", "*", "fflag", ")", ":", "# when too many data points were flagged, return the", "# best fit sample instead of the current one.", "minimum_amplitude_sample", ".", "update", "(", ")", "return", "Isophote", "(", "minimum_amplitude_sample", ",", "iter", "+", "1", ",", "True", ",", "1", ")", "# pick appropriate corrector code.", "corrector", "=", "_correctors", "[", "largest_harmonic_index", "]", "# generate *NEW* EllipseSample instance with corrected", "# parameter. Note that this instance is still devoid of other", "# information besides its geometry. It needs to be explicitly", "# updated for computations to proceed. We have to build a new", "# EllipseSample instance every time because of the lazy", "# extraction process used by EllipseSample code. To minimize", "# the number of calls to the area integrators, we pay a", "# (hopefully smaller) price here, by having multiple calls to", "# the EllipseSample constructor.", "sample", "=", "corrector", ".", "correct", "(", "sample", ",", "largest_harmonic", ")", "sample", ".", "update", "(", ")", "# see if any abnormal (or unusual) conditions warrant", "# the change to non-iterative mode, or go-inwards mode.", "proceed", ",", "lexceed", "=", "self", ".", "_check_conditions", "(", "sample", ",", "maxgerr", ",", "going_inwards", ",", "lexceed", ")", "if", "not", "proceed", ":", "sample", ".", "update", "(", ")", "return", "Isophote", "(", "sample", ",", "iter", "+", "1", ",", "True", ",", "-", "1", ")", "# Got to the maximum number of iterations. Return with", "# code 2, and handle it as a valid isophote. Use the", "# best fit sample instead of the current one.", "minimum_amplitude_sample", ".", "update", "(", ")", "return", "Isophote", "(", "minimum_amplitude_sample", ",", "maxit", ",", "True", ",", "2", ")" ]
Fit an elliptical isophote. Parameters ---------- conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter in the `~photutils.isophote.EllipseSample` class). The default is `False`. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote, which also contains fit status information. Examples -------- >>> from photutils.isophote import EllipseSample, EllipseFitter >>> sample = EllipseSample(data, sma=10.) >>> fitter = EllipseFitter(sample) >>> isophote = fitter.fit()
[ "Fit", "an", "elliptical", "isophote", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/fitter.py#L41-L217
train
astropy/photutils
photutils/psf/epsf_stars.py
_extract_stars
def _extract_stars(data, catalog, size=(11, 11), use_xy=True): """ Extract cutout images from a single image centered on stars defined in the single input catalog. Parameters ---------- data : `~astropy.nddata.NDData` A `~astropy.nddata.NDData` object containing the 2D image from which to extract the stars. If the input ``catalog`` contains only the sky coordinates (i.e. not the pixel coordinates) of the stars then the `~astropy.nddata.NDData` object must have a valid ``wcs`` attribute. catalogs : `~astropy.table.Table` A single catalog of sources to be extracted from the input ``data``. The center of each source can be defined either in pixel coordinates (in ``x`` and ``y`` columns) or sky coordinates (in a ``skycoord`` column containing a `~astropy.coordinates.SkyCoord` object). If both are specified, then the value of the ``use_xy`` keyword determines which coordinates will be used. size : int or array_like (int), optional The extraction box size along each axis. If ``size`` is a scalar then a square box of size ``size`` will be used. If ``size`` has two elements, they should be in ``(ny, nx)`` order. The size must be greater than or equal to 3 pixel for both axes. use_xy : bool, optional Whether to use the ``x`` and ``y`` pixel positions when both pixel and sky coordinates are present in the input catalog table. If `False` then sky coordinates are used instead of pixel coordinates (e.g. for linked stars). The default is `True`. Returns ------- stars : list of `EPSFStar` objects A list of `EPSFStar` instances containing the extracted stars. """ colnames = catalog.colnames if ('x' not in colnames or 'y' not in colnames) or not use_xy: xcenters, ycenters = skycoord_to_pixel(catalog['skycoord'], data.wcs, origin=0, mode='all') else: xcenters = catalog['x'].data.astype(np.float) ycenters = catalog['y'].data.astype(np.float) if 'id' in colnames: ids = catalog['id'] else: ids = np.arange(len(catalog), dtype=np.int) + 1 if data.uncertainty is None: weights = np.ones_like(data.data) else: if data.uncertainty.uncertainty_type == 'weights': weights = np.asanyarray(data.uncertainty.array, dtype=np.float) else: warnings.warn('The data uncertainty attribute has an unsupported ' 'type. Only uncertainty_type="weights" can be ' 'used to set weights. Weights will be set to 1.', AstropyUserWarning) weights = np.ones_like(data.data) if data.mask is not None: weights[data.mask] = 0. stars = [] for xcenter, ycenter, obj_id in zip(xcenters, ycenters, ids): try: large_slc, small_slc = overlap_slices(data.data.shape, size, (ycenter, xcenter), mode='strict') data_cutout = data.data[large_slc] weights_cutout = weights[large_slc] except (PartialOverlapError, NoOverlapError): stars.append(None) continue origin = (large_slc[1].start, large_slc[0].start) cutout_center = (xcenter - origin[0], ycenter - origin[1]) star = EPSFStar(data_cutout, weights_cutout, cutout_center=cutout_center, origin=origin, wcs_large=data.wcs, id_label=obj_id) stars.append(star) return stars
python
def _extract_stars(data, catalog, size=(11, 11), use_xy=True): """ Extract cutout images from a single image centered on stars defined in the single input catalog. Parameters ---------- data : `~astropy.nddata.NDData` A `~astropy.nddata.NDData` object containing the 2D image from which to extract the stars. If the input ``catalog`` contains only the sky coordinates (i.e. not the pixel coordinates) of the stars then the `~astropy.nddata.NDData` object must have a valid ``wcs`` attribute. catalogs : `~astropy.table.Table` A single catalog of sources to be extracted from the input ``data``. The center of each source can be defined either in pixel coordinates (in ``x`` and ``y`` columns) or sky coordinates (in a ``skycoord`` column containing a `~astropy.coordinates.SkyCoord` object). If both are specified, then the value of the ``use_xy`` keyword determines which coordinates will be used. size : int or array_like (int), optional The extraction box size along each axis. If ``size`` is a scalar then a square box of size ``size`` will be used. If ``size`` has two elements, they should be in ``(ny, nx)`` order. The size must be greater than or equal to 3 pixel for both axes. use_xy : bool, optional Whether to use the ``x`` and ``y`` pixel positions when both pixel and sky coordinates are present in the input catalog table. If `False` then sky coordinates are used instead of pixel coordinates (e.g. for linked stars). The default is `True`. Returns ------- stars : list of `EPSFStar` objects A list of `EPSFStar` instances containing the extracted stars. """ colnames = catalog.colnames if ('x' not in colnames or 'y' not in colnames) or not use_xy: xcenters, ycenters = skycoord_to_pixel(catalog['skycoord'], data.wcs, origin=0, mode='all') else: xcenters = catalog['x'].data.astype(np.float) ycenters = catalog['y'].data.astype(np.float) if 'id' in colnames: ids = catalog['id'] else: ids = np.arange(len(catalog), dtype=np.int) + 1 if data.uncertainty is None: weights = np.ones_like(data.data) else: if data.uncertainty.uncertainty_type == 'weights': weights = np.asanyarray(data.uncertainty.array, dtype=np.float) else: warnings.warn('The data uncertainty attribute has an unsupported ' 'type. Only uncertainty_type="weights" can be ' 'used to set weights. Weights will be set to 1.', AstropyUserWarning) weights = np.ones_like(data.data) if data.mask is not None: weights[data.mask] = 0. stars = [] for xcenter, ycenter, obj_id in zip(xcenters, ycenters, ids): try: large_slc, small_slc = overlap_slices(data.data.shape, size, (ycenter, xcenter), mode='strict') data_cutout = data.data[large_slc] weights_cutout = weights[large_slc] except (PartialOverlapError, NoOverlapError): stars.append(None) continue origin = (large_slc[1].start, large_slc[0].start) cutout_center = (xcenter - origin[0], ycenter - origin[1]) star = EPSFStar(data_cutout, weights_cutout, cutout_center=cutout_center, origin=origin, wcs_large=data.wcs, id_label=obj_id) stars.append(star) return stars
[ "def", "_extract_stars", "(", "data", ",", "catalog", ",", "size", "=", "(", "11", ",", "11", ")", ",", "use_xy", "=", "True", ")", ":", "colnames", "=", "catalog", ".", "colnames", "if", "(", "'x'", "not", "in", "colnames", "or", "'y'", "not", "in", "colnames", ")", "or", "not", "use_xy", ":", "xcenters", ",", "ycenters", "=", "skycoord_to_pixel", "(", "catalog", "[", "'skycoord'", "]", ",", "data", ".", "wcs", ",", "origin", "=", "0", ",", "mode", "=", "'all'", ")", "else", ":", "xcenters", "=", "catalog", "[", "'x'", "]", ".", "data", ".", "astype", "(", "np", ".", "float", ")", "ycenters", "=", "catalog", "[", "'y'", "]", ".", "data", ".", "astype", "(", "np", ".", "float", ")", "if", "'id'", "in", "colnames", ":", "ids", "=", "catalog", "[", "'id'", "]", "else", ":", "ids", "=", "np", ".", "arange", "(", "len", "(", "catalog", ")", ",", "dtype", "=", "np", ".", "int", ")", "+", "1", "if", "data", ".", "uncertainty", "is", "None", ":", "weights", "=", "np", ".", "ones_like", "(", "data", ".", "data", ")", "else", ":", "if", "data", ".", "uncertainty", ".", "uncertainty_type", "==", "'weights'", ":", "weights", "=", "np", ".", "asanyarray", "(", "data", ".", "uncertainty", ".", "array", ",", "dtype", "=", "np", ".", "float", ")", "else", ":", "warnings", ".", "warn", "(", "'The data uncertainty attribute has an unsupported '", "'type. Only uncertainty_type=\"weights\" can be '", "'used to set weights. Weights will be set to 1.'", ",", "AstropyUserWarning", ")", "weights", "=", "np", ".", "ones_like", "(", "data", ".", "data", ")", "if", "data", ".", "mask", "is", "not", "None", ":", "weights", "[", "data", ".", "mask", "]", "=", "0.", "stars", "=", "[", "]", "for", "xcenter", ",", "ycenter", ",", "obj_id", "in", "zip", "(", "xcenters", ",", "ycenters", ",", "ids", ")", ":", "try", ":", "large_slc", ",", "small_slc", "=", "overlap_slices", "(", "data", ".", "data", ".", "shape", ",", "size", ",", "(", "ycenter", ",", "xcenter", ")", ",", "mode", "=", "'strict'", ")", "data_cutout", "=", "data", ".", "data", "[", "large_slc", "]", "weights_cutout", "=", "weights", "[", "large_slc", "]", "except", "(", "PartialOverlapError", ",", "NoOverlapError", ")", ":", "stars", ".", "append", "(", "None", ")", "continue", "origin", "=", "(", "large_slc", "[", "1", "]", ".", "start", ",", "large_slc", "[", "0", "]", ".", "start", ")", "cutout_center", "=", "(", "xcenter", "-", "origin", "[", "0", "]", ",", "ycenter", "-", "origin", "[", "1", "]", ")", "star", "=", "EPSFStar", "(", "data_cutout", ",", "weights_cutout", ",", "cutout_center", "=", "cutout_center", ",", "origin", "=", "origin", ",", "wcs_large", "=", "data", ".", "wcs", ",", "id_label", "=", "obj_id", ")", "stars", ".", "append", "(", "star", ")", "return", "stars" ]
Extract cutout images from a single image centered on stars defined in the single input catalog. Parameters ---------- data : `~astropy.nddata.NDData` A `~astropy.nddata.NDData` object containing the 2D image from which to extract the stars. If the input ``catalog`` contains only the sky coordinates (i.e. not the pixel coordinates) of the stars then the `~astropy.nddata.NDData` object must have a valid ``wcs`` attribute. catalogs : `~astropy.table.Table` A single catalog of sources to be extracted from the input ``data``. The center of each source can be defined either in pixel coordinates (in ``x`` and ``y`` columns) or sky coordinates (in a ``skycoord`` column containing a `~astropy.coordinates.SkyCoord` object). If both are specified, then the value of the ``use_xy`` keyword determines which coordinates will be used. size : int or array_like (int), optional The extraction box size along each axis. If ``size`` is a scalar then a square box of size ``size`` will be used. If ``size`` has two elements, they should be in ``(ny, nx)`` order. The size must be greater than or equal to 3 pixel for both axes. use_xy : bool, optional Whether to use the ``x`` and ``y`` pixel positions when both pixel and sky coordinates are present in the input catalog table. If `False` then sky coordinates are used instead of pixel coordinates (e.g. for linked stars). The default is `True`. Returns ------- stars : list of `EPSFStar` objects A list of `EPSFStar` instances containing the extracted stars.
[ "Extract", "cutout", "images", "from", "a", "single", "image", "centered", "on", "stars", "defined", "in", "the", "single", "input", "catalog", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf_stars.py#L687-L777
train
astropy/photutils
photutils/psf/epsf_stars.py
EPSFStar.estimate_flux
def estimate_flux(self): """ Estimate the star's flux by summing values in the input cutout array. Missing data is filled in by interpolation to better estimate the total flux. """ from .epsf import _interpolate_missing_data if np.any(self.mask): data_interp = _interpolate_missing_data(self.data, method='cubic', mask=self.mask) data_interp = _interpolate_missing_data(data_interp, method='nearest', mask=self.mask) flux = np.sum(data_interp, dtype=np.float64) else: flux = np.sum(self.data, dtype=np.float64) return flux
python
def estimate_flux(self): """ Estimate the star's flux by summing values in the input cutout array. Missing data is filled in by interpolation to better estimate the total flux. """ from .epsf import _interpolate_missing_data if np.any(self.mask): data_interp = _interpolate_missing_data(self.data, method='cubic', mask=self.mask) data_interp = _interpolate_missing_data(data_interp, method='nearest', mask=self.mask) flux = np.sum(data_interp, dtype=np.float64) else: flux = np.sum(self.data, dtype=np.float64) return flux
[ "def", "estimate_flux", "(", "self", ")", ":", "from", ".", "epsf", "import", "_interpolate_missing_data", "if", "np", ".", "any", "(", "self", ".", "mask", ")", ":", "data_interp", "=", "_interpolate_missing_data", "(", "self", ".", "data", ",", "method", "=", "'cubic'", ",", "mask", "=", "self", ".", "mask", ")", "data_interp", "=", "_interpolate_missing_data", "(", "data_interp", ",", "method", "=", "'nearest'", ",", "mask", "=", "self", ".", "mask", ")", "flux", "=", "np", ".", "sum", "(", "data_interp", ",", "dtype", "=", "np", ".", "float64", ")", "else", ":", "flux", "=", "np", ".", "sum", "(", "self", ".", "data", ",", "dtype", "=", "np", ".", "float64", ")", "return", "flux" ]
Estimate the star's flux by summing values in the input cutout array. Missing data is filled in by interpolation to better estimate the total flux.
[ "Estimate", "the", "star", "s", "flux", "by", "summing", "values", "in", "the", "input", "cutout", "array", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf_stars.py#L158-L180
train
astropy/photutils
photutils/psf/epsf_stars.py
EPSFStar._xy_idx
def _xy_idx(self): """ 1D arrays of x and y indices of unmasked pixels in the cutout reference frame. """ yidx, xidx = np.indices(self._data.shape) return xidx[~self.mask].ravel(), yidx[~self.mask].ravel()
python
def _xy_idx(self): """ 1D arrays of x and y indices of unmasked pixels in the cutout reference frame. """ yidx, xidx = np.indices(self._data.shape) return xidx[~self.mask].ravel(), yidx[~self.mask].ravel()
[ "def", "_xy_idx", "(", "self", ")", ":", "yidx", ",", "xidx", "=", "np", ".", "indices", "(", "self", ".", "_data", ".", "shape", ")", "return", "xidx", "[", "~", "self", ".", "mask", "]", ".", "ravel", "(", ")", ",", "yidx", "[", "~", "self", ".", "mask", "]", ".", "ravel", "(", ")" ]
1D arrays of x and y indices of unmasked pixels in the cutout reference frame.
[ "1D", "arrays", "of", "x", "and", "y", "indices", "of", "unmasked", "pixels", "in", "the", "cutout", "reference", "frame", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf_stars.py#L223-L230
train
astropy/photutils
photutils/psf/groupstars.py
DAOGroup.find_group
def find_group(self, star, starlist): """ Find the ids of those stars in ``starlist`` which are at a distance less than ``crit_separation`` from ``star``. Parameters ---------- star : `~astropy.table.Row` Star which will be either the head of a cluster or an isolated one. starlist : `~astropy.table.Table` List of star positions. Columns named as ``x_0`` and ``y_0``, which corresponds to the centroid coordinates of the sources, must be provided. Returns ------- Array containing the ids of those stars which are at a distance less than ``crit_separation`` from ``star``. """ star_distance = np.hypot(star['x_0'] - starlist['x_0'], star['y_0'] - starlist['y_0']) distance_criteria = star_distance < self.crit_separation return np.asarray(starlist[distance_criteria]['id'])
python
def find_group(self, star, starlist): """ Find the ids of those stars in ``starlist`` which are at a distance less than ``crit_separation`` from ``star``. Parameters ---------- star : `~astropy.table.Row` Star which will be either the head of a cluster or an isolated one. starlist : `~astropy.table.Table` List of star positions. Columns named as ``x_0`` and ``y_0``, which corresponds to the centroid coordinates of the sources, must be provided. Returns ------- Array containing the ids of those stars which are at a distance less than ``crit_separation`` from ``star``. """ star_distance = np.hypot(star['x_0'] - starlist['x_0'], star['y_0'] - starlist['y_0']) distance_criteria = star_distance < self.crit_separation return np.asarray(starlist[distance_criteria]['id'])
[ "def", "find_group", "(", "self", ",", "star", ",", "starlist", ")", ":", "star_distance", "=", "np", ".", "hypot", "(", "star", "[", "'x_0'", "]", "-", "starlist", "[", "'x_0'", "]", ",", "star", "[", "'y_0'", "]", "-", "starlist", "[", "'y_0'", "]", ")", "distance_criteria", "=", "star_distance", "<", "self", ".", "crit_separation", "return", "np", ".", "asarray", "(", "starlist", "[", "distance_criteria", "]", "[", "'id'", "]", ")" ]
Find the ids of those stars in ``starlist`` which are at a distance less than ``crit_separation`` from ``star``. Parameters ---------- star : `~astropy.table.Row` Star which will be either the head of a cluster or an isolated one. starlist : `~astropy.table.Table` List of star positions. Columns named as ``x_0`` and ``y_0``, which corresponds to the centroid coordinates of the sources, must be provided. Returns ------- Array containing the ids of those stars which are at a distance less than ``crit_separation`` from ``star``.
[ "Find", "the", "ids", "of", "those", "stars", "in", "starlist", "which", "are", "at", "a", "distance", "less", "than", "crit_separation", "from", "star", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/groupstars.py#L152-L176
train
astropy/photutils
photutils/aperture/bounding_box.py
BoundingBox._from_float
def _from_float(cls, xmin, xmax, ymin, ymax): """ Return the smallest bounding box that fully contains a given rectangle defined by float coordinate values. Following the pixel index convention, an integer index corresponds to the center of a pixel and the pixel edges span from (index - 0.5) to (index + 0.5). For example, the pixel edge spans of the following pixels are: - pixel 0: from -0.5 to 0.5 - pixel 1: from 0.5 to 1.5 - pixel 2: from 1.5 to 2.5 In addition, because `BoundingBox` upper limits are exclusive (by definition), 1 is added to the upper pixel edges. See examples below. Parameters ---------- xmin, xmax, ymin, ymax : float Float coordinates defining a rectangle. The lower values (``xmin`` and ``ymin``) must not be greater than the respective upper values (``xmax`` and ``ymax``). Returns ------- bbox : `BoundingBox` object The minimal ``BoundingBox`` object fully containing the input rectangle coordinates. Examples -------- >>> from photutils import BoundingBox >>> BoundingBox._from_float(xmin=1.0, xmax=10.0, ymin=2.0, ymax=20.0) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=21) >>> BoundingBox._from_float(xmin=1.4, xmax=10.4, ymin=1.6, ymax=10.6) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=12) """ ixmin = int(np.floor(xmin + 0.5)) ixmax = int(np.ceil(xmax + 0.5)) iymin = int(np.floor(ymin + 0.5)) iymax = int(np.ceil(ymax + 0.5)) return cls(ixmin, ixmax, iymin, iymax)
python
def _from_float(cls, xmin, xmax, ymin, ymax): """ Return the smallest bounding box that fully contains a given rectangle defined by float coordinate values. Following the pixel index convention, an integer index corresponds to the center of a pixel and the pixel edges span from (index - 0.5) to (index + 0.5). For example, the pixel edge spans of the following pixels are: - pixel 0: from -0.5 to 0.5 - pixel 1: from 0.5 to 1.5 - pixel 2: from 1.5 to 2.5 In addition, because `BoundingBox` upper limits are exclusive (by definition), 1 is added to the upper pixel edges. See examples below. Parameters ---------- xmin, xmax, ymin, ymax : float Float coordinates defining a rectangle. The lower values (``xmin`` and ``ymin``) must not be greater than the respective upper values (``xmax`` and ``ymax``). Returns ------- bbox : `BoundingBox` object The minimal ``BoundingBox`` object fully containing the input rectangle coordinates. Examples -------- >>> from photutils import BoundingBox >>> BoundingBox._from_float(xmin=1.0, xmax=10.0, ymin=2.0, ymax=20.0) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=21) >>> BoundingBox._from_float(xmin=1.4, xmax=10.4, ymin=1.6, ymax=10.6) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=12) """ ixmin = int(np.floor(xmin + 0.5)) ixmax = int(np.ceil(xmax + 0.5)) iymin = int(np.floor(ymin + 0.5)) iymax = int(np.ceil(ymax + 0.5)) return cls(ixmin, ixmax, iymin, iymax)
[ "def", "_from_float", "(", "cls", ",", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", ":", "ixmin", "=", "int", "(", "np", ".", "floor", "(", "xmin", "+", "0.5", ")", ")", "ixmax", "=", "int", "(", "np", ".", "ceil", "(", "xmax", "+", "0.5", ")", ")", "iymin", "=", "int", "(", "np", ".", "floor", "(", "ymin", "+", "0.5", ")", ")", "iymax", "=", "int", "(", "np", ".", "ceil", "(", "ymax", "+", "0.5", ")", ")", "return", "cls", "(", "ixmin", ",", "ixmax", ",", "iymin", ",", "iymax", ")" ]
Return the smallest bounding box that fully contains a given rectangle defined by float coordinate values. Following the pixel index convention, an integer index corresponds to the center of a pixel and the pixel edges span from (index - 0.5) to (index + 0.5). For example, the pixel edge spans of the following pixels are: - pixel 0: from -0.5 to 0.5 - pixel 1: from 0.5 to 1.5 - pixel 2: from 1.5 to 2.5 In addition, because `BoundingBox` upper limits are exclusive (by definition), 1 is added to the upper pixel edges. See examples below. Parameters ---------- xmin, xmax, ymin, ymax : float Float coordinates defining a rectangle. The lower values (``xmin`` and ``ymin``) must not be greater than the respective upper values (``xmax`` and ``ymax``). Returns ------- bbox : `BoundingBox` object The minimal ``BoundingBox`` object fully containing the input rectangle coordinates. Examples -------- >>> from photutils import BoundingBox >>> BoundingBox._from_float(xmin=1.0, xmax=10.0, ymin=2.0, ymax=20.0) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=21) >>> BoundingBox._from_float(xmin=1.4, xmax=10.4, ymin=1.6, ymax=10.6) BoundingBox(ixmin=1, ixmax=11, iymin=2, iymax=12)
[ "Return", "the", "smallest", "bounding", "box", "that", "fully", "contains", "a", "given", "rectangle", "defined", "by", "float", "coordinate", "values", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/bounding_box.py#L73-L119
train
astropy/photutils
photutils/aperture/bounding_box.py
BoundingBox.slices
def slices(self): """ The bounding box as a tuple of `slice` objects. The slice tuple is in numpy axis order (i.e. ``(y, x)``) and therefore can be used to slice numpy arrays. """ return (slice(self.iymin, self.iymax), slice(self.ixmin, self.ixmax))
python
def slices(self): """ The bounding box as a tuple of `slice` objects. The slice tuple is in numpy axis order (i.e. ``(y, x)``) and therefore can be used to slice numpy arrays. """ return (slice(self.iymin, self.iymax), slice(self.ixmin, self.ixmax))
[ "def", "slices", "(", "self", ")", ":", "return", "(", "slice", "(", "self", ".", "iymin", ",", "self", ".", "iymax", ")", ",", "slice", "(", "self", ".", "ixmin", ",", "self", ".", "ixmax", ")", ")" ]
The bounding box as a tuple of `slice` objects. The slice tuple is in numpy axis order (i.e. ``(y, x)``) and therefore can be used to slice numpy arrays.
[ "The", "bounding", "box", "as", "a", "tuple", "of", "slice", "objects", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/bounding_box.py#L149-L157
train
astropy/photutils
photutils/aperture/bounding_box.py
BoundingBox.as_patch
def as_patch(self, **kwargs): """ Return a `matplotlib.patches.Rectangle` that represents the bounding box. Parameters ---------- kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Returns ------- result : `matplotlib.patches.Rectangle` A matplotlib rectangular patch. Examples -------- .. plot:: :include-source: import matplotlib.pyplot as plt from photutils import BoundingBox bbox = BoundingBox(2, 7, 3, 8) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) np.random.seed(12345) ax.imshow(np.random.random((10, 10)), interpolation='nearest', cmap='viridis') ax.add_patch(bbox.as_patch(facecolor='none', edgecolor='white', lw=2.)) """ from matplotlib.patches import Rectangle return Rectangle(xy=(self.extent[0], self.extent[2]), width=self.shape[1], height=self.shape[0], **kwargs)
python
def as_patch(self, **kwargs): """ Return a `matplotlib.patches.Rectangle` that represents the bounding box. Parameters ---------- kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Returns ------- result : `matplotlib.patches.Rectangle` A matplotlib rectangular patch. Examples -------- .. plot:: :include-source: import matplotlib.pyplot as plt from photutils import BoundingBox bbox = BoundingBox(2, 7, 3, 8) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) np.random.seed(12345) ax.imshow(np.random.random((10, 10)), interpolation='nearest', cmap='viridis') ax.add_patch(bbox.as_patch(facecolor='none', edgecolor='white', lw=2.)) """ from matplotlib.patches import Rectangle return Rectangle(xy=(self.extent[0], self.extent[2]), width=self.shape[1], height=self.shape[0], **kwargs)
[ "def", "as_patch", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", ".", "patches", "import", "Rectangle", "return", "Rectangle", "(", "xy", "=", "(", "self", ".", "extent", "[", "0", "]", ",", "self", ".", "extent", "[", "2", "]", ")", ",", "width", "=", "self", ".", "shape", "[", "1", "]", ",", "height", "=", "self", ".", "shape", "[", "0", "]", ",", "*", "*", "kwargs", ")" ]
Return a `matplotlib.patches.Rectangle` that represents the bounding box. Parameters ---------- kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. Returns ------- result : `matplotlib.patches.Rectangle` A matplotlib rectangular patch. Examples -------- .. plot:: :include-source: import matplotlib.pyplot as plt from photutils import BoundingBox bbox = BoundingBox(2, 7, 3, 8) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) np.random.seed(12345) ax.imshow(np.random.random((10, 10)), interpolation='nearest', cmap='viridis') ax.add_patch(bbox.as_patch(facecolor='none', edgecolor='white', lw=2.))
[ "Return", "a", "matplotlib", ".", "patches", ".", "Rectangle", "that", "represents", "the", "bounding", "box", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/bounding_box.py#L180-L216
train
astropy/photutils
photutils/aperture/bounding_box.py
BoundingBox.to_aperture
def to_aperture(self): """ Return a `~photutils.aperture.RectangularAperture` that represents the bounding box. """ from .rectangle import RectangularAperture xpos = (self.extent[1] + self.extent[0]) / 2. ypos = (self.extent[3] + self.extent[2]) / 2. xypos = (xpos, ypos) h, w = self.shape return RectangularAperture(xypos, w=w, h=h, theta=0.)
python
def to_aperture(self): """ Return a `~photutils.aperture.RectangularAperture` that represents the bounding box. """ from .rectangle import RectangularAperture xpos = (self.extent[1] + self.extent[0]) / 2. ypos = (self.extent[3] + self.extent[2]) / 2. xypos = (xpos, ypos) h, w = self.shape return RectangularAperture(xypos, w=w, h=h, theta=0.)
[ "def", "to_aperture", "(", "self", ")", ":", "from", ".", "rectangle", "import", "RectangularAperture", "xpos", "=", "(", "self", ".", "extent", "[", "1", "]", "+", "self", ".", "extent", "[", "0", "]", ")", "/", "2.", "ypos", "=", "(", "self", ".", "extent", "[", "3", "]", "+", "self", ".", "extent", "[", "2", "]", ")", "/", "2.", "xypos", "=", "(", "xpos", ",", "ypos", ")", "h", ",", "w", "=", "self", ".", "shape", "return", "RectangularAperture", "(", "xypos", ",", "w", "=", "w", ",", "h", "=", "h", ",", "theta", "=", "0.", ")" ]
Return a `~photutils.aperture.RectangularAperture` that represents the bounding box.
[ "Return", "a", "~photutils", ".", "aperture", ".", "RectangularAperture", "that", "represents", "the", "bounding", "box", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/bounding_box.py#L218-L231
train
astropy/photutils
photutils/aperture/bounding_box.py
BoundingBox.plot
def plot(self, origin=(0, 0), ax=None, fill=False, **kwargs): """ Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes` instance. Parameters ---------- origin : array_like, optional The ``(x, y)`` position of the origin of the displayed image. ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current `~matplotlib.axes.Axes` instance is used. fill : bool, optional Set whether to fill the aperture patch. The default is `False`. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. """ aper = self.to_aperture() aper.plot(origin=origin, ax=ax, fill=fill, **kwargs)
python
def plot(self, origin=(0, 0), ax=None, fill=False, **kwargs): """ Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes` instance. Parameters ---------- origin : array_like, optional The ``(x, y)`` position of the origin of the displayed image. ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current `~matplotlib.axes.Axes` instance is used. fill : bool, optional Set whether to fill the aperture patch. The default is `False`. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`. """ aper = self.to_aperture() aper.plot(origin=origin, ax=ax, fill=fill, **kwargs)
[ "def", "plot", "(", "self", ",", "origin", "=", "(", "0", ",", "0", ")", ",", "ax", "=", "None", ",", "fill", "=", "False", ",", "*", "*", "kwargs", ")", ":", "aper", "=", "self", ".", "to_aperture", "(", ")", "aper", ".", "plot", "(", "origin", "=", "origin", ",", "ax", "=", "ax", ",", "fill", "=", "fill", ",", "*", "*", "kwargs", ")" ]
Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes` instance. Parameters ---------- origin : array_like, optional The ``(x, y)`` position of the origin of the displayed image. ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current `~matplotlib.axes.Axes` instance is used. fill : bool, optional Set whether to fill the aperture patch. The default is `False`. kwargs Any keyword arguments accepted by `matplotlib.patches.Patch`.
[ "Plot", "the", "BoundingBox", "on", "a", "matplotlib", "~matplotlib", ".", "axes", ".", "Axes", "instance", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/bounding_box.py#L233-L257
train
astropy/photutils
photutils/detection/findstars.py
_find_stars
def _find_stars(data, kernel, threshold_eff, min_separation=None, mask=None, exclude_border=False): """ Find stars in an image. Parameters ---------- data : 2D array_like The 2D array of the image. kernel : `_StarFinderKernel` The convolution kernel. threshold_eff : float The absolute image value above which to select sources. This threshold should be the threshold input to the star finder class multiplied by the kernel relerr. mask : 2D bool array, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when searching for stars. exclude_border : bool, optional Set to `True` to exclude sources found within half the size of the convolution kernel from the image borders. The default is `False`, which is the mode used by IRAF's `DAOFIND`_ and `starfind`_ tasks. Returns ------- objects : list of `_StarCutout` A list of `_StarCutout` objects containing the image cutout for each source. .. _DAOFIND: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?daofind .. _starfind: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?starfind """ convolved_data = filter_data(data, kernel.data, mode='constant', fill_value=0.0, check_normalization=False) # define a local footprint for the peak finder if min_separation is None: # daofind footprint = kernel.mask.astype(np.bool) else: # define a circular footprint idx = np.arange(-min_separation, min_separation + 1) xx, yy = np.meshgrid(idx, idx) footprint = np.array((xx**2 + yy**2) <= min_separation**2, dtype=int) # pad the data and convolved image by the kernel x/y radius to allow # for detections near the edges if not exclude_border: ypad = kernel.yradius xpad = kernel.xradius pad = ((ypad, ypad), (xpad, xpad)) # mode must be a string for numpy < 0.11 # (see https://github.com/numpy/numpy/issues/7112) mode = str('constant') data = np.pad(data, pad, mode=mode, constant_values=[0.]) if mask is not None: mask = np.pad(mask, pad, mode=mode, constant_values=[0.]) convolved_data = np.pad(convolved_data, pad, mode=mode, constant_values=[0.]) # find local peaks in the convolved data with warnings.catch_warnings(): # suppress any NoDetectionsWarning from find_peaks warnings.filterwarnings('ignore', category=NoDetectionsWarning) tbl = find_peaks(convolved_data, threshold_eff, footprint=footprint, mask=mask) if tbl is None: return None coords = np.transpose([tbl['y_peak'], tbl['x_peak']]) star_cutouts = [] for (ypeak, xpeak) in coords: # now extract the object from the data, centered on the peak # pixel in the convolved image, with the same size as the kernel x0 = xpeak - kernel.xradius x1 = xpeak + kernel.xradius + 1 y0 = ypeak - kernel.yradius y1 = ypeak + kernel.yradius + 1 if x0 < 0 or x1 > data.shape[1]: continue # pragma: no cover if y0 < 0 or y1 > data.shape[0]: continue # pragma: no cover slices = (slice(y0, y1), slice(x0, x1)) data_cutout = data[slices] convdata_cutout = convolved_data[slices] # correct pixel values for the previous image padding if not exclude_border: x0 -= kernel.xradius x1 -= kernel.xradius y0 -= kernel.yradius y1 -= kernel.yradius xpeak -= kernel.xradius ypeak -= kernel.yradius slices = (slice(y0, y1), slice(x0, x1)) star_cutouts.append(_StarCutout(data_cutout, convdata_cutout, slices, xpeak, ypeak, kernel, threshold_eff)) return star_cutouts
python
def _find_stars(data, kernel, threshold_eff, min_separation=None, mask=None, exclude_border=False): """ Find stars in an image. Parameters ---------- data : 2D array_like The 2D array of the image. kernel : `_StarFinderKernel` The convolution kernel. threshold_eff : float The absolute image value above which to select sources. This threshold should be the threshold input to the star finder class multiplied by the kernel relerr. mask : 2D bool array, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when searching for stars. exclude_border : bool, optional Set to `True` to exclude sources found within half the size of the convolution kernel from the image borders. The default is `False`, which is the mode used by IRAF's `DAOFIND`_ and `starfind`_ tasks. Returns ------- objects : list of `_StarCutout` A list of `_StarCutout` objects containing the image cutout for each source. .. _DAOFIND: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?daofind .. _starfind: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?starfind """ convolved_data = filter_data(data, kernel.data, mode='constant', fill_value=0.0, check_normalization=False) # define a local footprint for the peak finder if min_separation is None: # daofind footprint = kernel.mask.astype(np.bool) else: # define a circular footprint idx = np.arange(-min_separation, min_separation + 1) xx, yy = np.meshgrid(idx, idx) footprint = np.array((xx**2 + yy**2) <= min_separation**2, dtype=int) # pad the data and convolved image by the kernel x/y radius to allow # for detections near the edges if not exclude_border: ypad = kernel.yradius xpad = kernel.xradius pad = ((ypad, ypad), (xpad, xpad)) # mode must be a string for numpy < 0.11 # (see https://github.com/numpy/numpy/issues/7112) mode = str('constant') data = np.pad(data, pad, mode=mode, constant_values=[0.]) if mask is not None: mask = np.pad(mask, pad, mode=mode, constant_values=[0.]) convolved_data = np.pad(convolved_data, pad, mode=mode, constant_values=[0.]) # find local peaks in the convolved data with warnings.catch_warnings(): # suppress any NoDetectionsWarning from find_peaks warnings.filterwarnings('ignore', category=NoDetectionsWarning) tbl = find_peaks(convolved_data, threshold_eff, footprint=footprint, mask=mask) if tbl is None: return None coords = np.transpose([tbl['y_peak'], tbl['x_peak']]) star_cutouts = [] for (ypeak, xpeak) in coords: # now extract the object from the data, centered on the peak # pixel in the convolved image, with the same size as the kernel x0 = xpeak - kernel.xradius x1 = xpeak + kernel.xradius + 1 y0 = ypeak - kernel.yradius y1 = ypeak + kernel.yradius + 1 if x0 < 0 or x1 > data.shape[1]: continue # pragma: no cover if y0 < 0 or y1 > data.shape[0]: continue # pragma: no cover slices = (slice(y0, y1), slice(x0, x1)) data_cutout = data[slices] convdata_cutout = convolved_data[slices] # correct pixel values for the previous image padding if not exclude_border: x0 -= kernel.xradius x1 -= kernel.xradius y0 -= kernel.yradius y1 -= kernel.yradius xpeak -= kernel.xradius ypeak -= kernel.yradius slices = (slice(y0, y1), slice(x0, x1)) star_cutouts.append(_StarCutout(data_cutout, convdata_cutout, slices, xpeak, ypeak, kernel, threshold_eff)) return star_cutouts
[ "def", "_find_stars", "(", "data", ",", "kernel", ",", "threshold_eff", ",", "min_separation", "=", "None", ",", "mask", "=", "None", ",", "exclude_border", "=", "False", ")", ":", "convolved_data", "=", "filter_data", "(", "data", ",", "kernel", ".", "data", ",", "mode", "=", "'constant'", ",", "fill_value", "=", "0.0", ",", "check_normalization", "=", "False", ")", "# define a local footprint for the peak finder", "if", "min_separation", "is", "None", ":", "# daofind", "footprint", "=", "kernel", ".", "mask", ".", "astype", "(", "np", ".", "bool", ")", "else", ":", "# define a circular footprint", "idx", "=", "np", ".", "arange", "(", "-", "min_separation", ",", "min_separation", "+", "1", ")", "xx", ",", "yy", "=", "np", ".", "meshgrid", "(", "idx", ",", "idx", ")", "footprint", "=", "np", ".", "array", "(", "(", "xx", "**", "2", "+", "yy", "**", "2", ")", "<=", "min_separation", "**", "2", ",", "dtype", "=", "int", ")", "# pad the data and convolved image by the kernel x/y radius to allow", "# for detections near the edges", "if", "not", "exclude_border", ":", "ypad", "=", "kernel", ".", "yradius", "xpad", "=", "kernel", ".", "xradius", "pad", "=", "(", "(", "ypad", ",", "ypad", ")", ",", "(", "xpad", ",", "xpad", ")", ")", "# mode must be a string for numpy < 0.11", "# (see https://github.com/numpy/numpy/issues/7112)", "mode", "=", "str", "(", "'constant'", ")", "data", "=", "np", ".", "pad", "(", "data", ",", "pad", ",", "mode", "=", "mode", ",", "constant_values", "=", "[", "0.", "]", ")", "if", "mask", "is", "not", "None", ":", "mask", "=", "np", ".", "pad", "(", "mask", ",", "pad", ",", "mode", "=", "mode", ",", "constant_values", "=", "[", "0.", "]", ")", "convolved_data", "=", "np", ".", "pad", "(", "convolved_data", ",", "pad", ",", "mode", "=", "mode", ",", "constant_values", "=", "[", "0.", "]", ")", "# find local peaks in the convolved data", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "# suppress any NoDetectionsWarning from find_peaks", "warnings", ".", "filterwarnings", "(", "'ignore'", ",", "category", "=", "NoDetectionsWarning", ")", "tbl", "=", "find_peaks", "(", "convolved_data", ",", "threshold_eff", ",", "footprint", "=", "footprint", ",", "mask", "=", "mask", ")", "if", "tbl", "is", "None", ":", "return", "None", "coords", "=", "np", ".", "transpose", "(", "[", "tbl", "[", "'y_peak'", "]", ",", "tbl", "[", "'x_peak'", "]", "]", ")", "star_cutouts", "=", "[", "]", "for", "(", "ypeak", ",", "xpeak", ")", "in", "coords", ":", "# now extract the object from the data, centered on the peak", "# pixel in the convolved image, with the same size as the kernel", "x0", "=", "xpeak", "-", "kernel", ".", "xradius", "x1", "=", "xpeak", "+", "kernel", ".", "xradius", "+", "1", "y0", "=", "ypeak", "-", "kernel", ".", "yradius", "y1", "=", "ypeak", "+", "kernel", ".", "yradius", "+", "1", "if", "x0", "<", "0", "or", "x1", ">", "data", ".", "shape", "[", "1", "]", ":", "continue", "# pragma: no cover", "if", "y0", "<", "0", "or", "y1", ">", "data", ".", "shape", "[", "0", "]", ":", "continue", "# pragma: no cover", "slices", "=", "(", "slice", "(", "y0", ",", "y1", ")", ",", "slice", "(", "x0", ",", "x1", ")", ")", "data_cutout", "=", "data", "[", "slices", "]", "convdata_cutout", "=", "convolved_data", "[", "slices", "]", "# correct pixel values for the previous image padding", "if", "not", "exclude_border", ":", "x0", "-=", "kernel", ".", "xradius", "x1", "-=", "kernel", ".", "xradius", "y0", "-=", "kernel", ".", "yradius", "y1", "-=", "kernel", ".", "yradius", "xpeak", "-=", "kernel", ".", "xradius", "ypeak", "-=", "kernel", ".", "yradius", "slices", "=", "(", "slice", "(", "y0", ",", "y1", ")", ",", "slice", "(", "x0", ",", "x1", ")", ")", "star_cutouts", ".", "append", "(", "_StarCutout", "(", "data_cutout", ",", "convdata_cutout", ",", "slices", ",", "xpeak", ",", "ypeak", ",", "kernel", ",", "threshold_eff", ")", ")", "return", "star_cutouts" ]
Find stars in an image. Parameters ---------- data : 2D array_like The 2D array of the image. kernel : `_StarFinderKernel` The convolution kernel. threshold_eff : float The absolute image value above which to select sources. This threshold should be the threshold input to the star finder class multiplied by the kernel relerr. mask : 2D bool array, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when searching for stars. exclude_border : bool, optional Set to `True` to exclude sources found within half the size of the convolution kernel from the image borders. The default is `False`, which is the mode used by IRAF's `DAOFIND`_ and `starfind`_ tasks. Returns ------- objects : list of `_StarCutout` A list of `_StarCutout` objects containing the image cutout for each source. .. _DAOFIND: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?daofind .. _starfind: http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?starfind
[ "Find", "stars", "in", "an", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/detection/findstars.py#L595-L704
train
astropy/photutils
photutils/detection/findstars.py
_DAOFind_Properties.roundness2
def roundness2(self): """ The star roundness. This roundness parameter represents the ratio of the difference in the height of the best fitting Gaussian function in x minus the best fitting Gaussian function in y, divided by the average of the best fitting Gaussian functions in x and y. A circular source will have a zero roundness. A source extended in x or y will have a negative or positive roundness, respectively. """ if np.isnan(self.hx) or np.isnan(self.hy): return np.nan else: return 2.0 * (self.hx - self.hy) / (self.hx + self.hy)
python
def roundness2(self): """ The star roundness. This roundness parameter represents the ratio of the difference in the height of the best fitting Gaussian function in x minus the best fitting Gaussian function in y, divided by the average of the best fitting Gaussian functions in x and y. A circular source will have a zero roundness. A source extended in x or y will have a negative or positive roundness, respectively. """ if np.isnan(self.hx) or np.isnan(self.hy): return np.nan else: return 2.0 * (self.hx - self.hy) / (self.hx + self.hy)
[ "def", "roundness2", "(", "self", ")", ":", "if", "np", ".", "isnan", "(", "self", ".", "hx", ")", "or", "np", ".", "isnan", "(", "self", ".", "hy", ")", ":", "return", "np", ".", "nan", "else", ":", "return", "2.0", "*", "(", "self", ".", "hx", "-", "self", ".", "hy", ")", "/", "(", "self", ".", "hx", "+", "self", ".", "hy", ")" ]
The star roundness. This roundness parameter represents the ratio of the difference in the height of the best fitting Gaussian function in x minus the best fitting Gaussian function in y, divided by the average of the best fitting Gaussian functions in x and y. A circular source will have a zero roundness. A source extended in x or y will have a negative or positive roundness, respectively.
[ "The", "star", "roundness", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/detection/findstars.py#L426-L441
train
astropy/photutils
photutils/segmentation/detect.py
detect_sources
def detect_sources(data, threshold, npixels, filter_kernel=None, connectivity=8, mask=None): """ Detect sources above a specified threshold value in an image and return a `~photutils.segmentation.SegmentationImage` object. Detected sources must have ``npixels`` connected pixels that are each greater than the ``threshold`` value. If the filtering option is used, then the ``threshold`` is applied to the filtered image. The input ``mask`` can be used to mask pixels in the input data. Masked pixels will not be included in any source. This function does not deblend overlapping sources. First use this function to detect sources followed by :func:`~photutils.segmentation.deblend_sources` to deblend sources. Parameters ---------- data : array_like The 2D array of the image. threshold : float or array-like The data value or pixel-wise data values to be used for the detection threshold. A 2D ``threshold`` must have the same shape as ``data``. See `~photutils.detection.detect_threshold` for one way to create a ``threshold`` image. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. connectivity : {4, 8}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 4 or 8 (default). 4-connected pixels touch along their edges. 8-connected pixels touch along their edges or corners. For reference, SExtractor uses 8-connected pixels. mask : array_like (bool) A boolean mask, with the same shape as the input ``data``, where `True` values indicate masked pixels. Masked pixels will not be included in any source. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` or `None` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. If no sources are found then `None` is returned. See Also -------- :func:`photutils.detection.detect_threshold`, :class:`photutils.segmentation.SegmentationImage`, :func:`photutils.segmentation.source_properties` :func:`photutils.segmentation.deblend_sources` Examples -------- .. plot:: :include-source: # make a table of Gaussian sources from astropy.table import Table table = Table() table['amplitude'] = [50, 70, 150, 210] table['x_mean'] = [160, 25, 150, 90] table['y_mean'] = [70, 40, 25, 60] table['x_stddev'] = [15.2, 5.1, 3., 8.1] table['y_stddev'] = [2.6, 2.5, 3., 4.7] table['theta'] = np.array([145., 20., 0., 60.]) * np.pi / 180. # make an image of the sources with Gaussian noise from photutils.datasets import make_gaussian_sources_image from photutils.datasets import make_noise_image shape = (100, 200) sources = make_gaussian_sources_image(shape, table) noise = make_noise_image(shape, type='gaussian', mean=0., stddev=5., random_state=12345) image = sources + noise # detect the sources from photutils import detect_threshold, detect_sources threshold = detect_threshold(image, snr=3) from astropy.convolution import Gaussian2DKernel sigma = 3.0 / (2.0 * np.sqrt(2.0 * np.log(2.0))) # FWHM = 3 kernel = Gaussian2DKernel(sigma, x_size=3, y_size=3) kernel.normalize() segm = detect_sources(image, threshold, npixels=5, filter_kernel=kernel) # plot the image and the segmentation image import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(image, origin='lower', interpolation='nearest') ax2.imshow(segm.data, origin='lower', interpolation='nearest') """ from scipy import ndimage if (npixels <= 0) or (int(npixels) != npixels): raise ValueError('npixels must be a positive integer, got ' '"{0}"'.format(npixels)) image = (filter_data(data, filter_kernel, mode='constant', fill_value=0.0, check_normalization=True) > threshold) if mask is not None: if mask.shape != image.shape: raise ValueError('mask must have the same shape as the input ' 'image.') image &= ~mask if connectivity == 4: selem = ndimage.generate_binary_structure(2, 1) elif connectivity == 8: selem = ndimage.generate_binary_structure(2, 2) else: raise ValueError('Invalid connectivity={0}. ' 'Options are 4 or 8'.format(connectivity)) segm_img, nobj = ndimage.label(image, structure=selem) # remove objects with less than npixels # NOTE: for typical data, making the cutout images is ~10x faster # than using segm_img directly segm_slices = ndimage.find_objects(segm_img) for i, slices in enumerate(segm_slices): cutout = segm_img[slices] segment_mask = (cutout == (i+1)) if np.count_nonzero(segment_mask) < npixels: cutout[segment_mask] = 0 # now relabel to make consecutive label indices segm_img, nobj = ndimage.label(segm_img, structure=selem) if nobj == 0: warnings.warn('No sources were found.', NoDetectionsWarning) return None else: return SegmentationImage(segm_img)
python
def detect_sources(data, threshold, npixels, filter_kernel=None, connectivity=8, mask=None): """ Detect sources above a specified threshold value in an image and return a `~photutils.segmentation.SegmentationImage` object. Detected sources must have ``npixels`` connected pixels that are each greater than the ``threshold`` value. If the filtering option is used, then the ``threshold`` is applied to the filtered image. The input ``mask`` can be used to mask pixels in the input data. Masked pixels will not be included in any source. This function does not deblend overlapping sources. First use this function to detect sources followed by :func:`~photutils.segmentation.deblend_sources` to deblend sources. Parameters ---------- data : array_like The 2D array of the image. threshold : float or array-like The data value or pixel-wise data values to be used for the detection threshold. A 2D ``threshold`` must have the same shape as ``data``. See `~photutils.detection.detect_threshold` for one way to create a ``threshold`` image. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. connectivity : {4, 8}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 4 or 8 (default). 4-connected pixels touch along their edges. 8-connected pixels touch along their edges or corners. For reference, SExtractor uses 8-connected pixels. mask : array_like (bool) A boolean mask, with the same shape as the input ``data``, where `True` values indicate masked pixels. Masked pixels will not be included in any source. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` or `None` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. If no sources are found then `None` is returned. See Also -------- :func:`photutils.detection.detect_threshold`, :class:`photutils.segmentation.SegmentationImage`, :func:`photutils.segmentation.source_properties` :func:`photutils.segmentation.deblend_sources` Examples -------- .. plot:: :include-source: # make a table of Gaussian sources from astropy.table import Table table = Table() table['amplitude'] = [50, 70, 150, 210] table['x_mean'] = [160, 25, 150, 90] table['y_mean'] = [70, 40, 25, 60] table['x_stddev'] = [15.2, 5.1, 3., 8.1] table['y_stddev'] = [2.6, 2.5, 3., 4.7] table['theta'] = np.array([145., 20., 0., 60.]) * np.pi / 180. # make an image of the sources with Gaussian noise from photutils.datasets import make_gaussian_sources_image from photutils.datasets import make_noise_image shape = (100, 200) sources = make_gaussian_sources_image(shape, table) noise = make_noise_image(shape, type='gaussian', mean=0., stddev=5., random_state=12345) image = sources + noise # detect the sources from photutils import detect_threshold, detect_sources threshold = detect_threshold(image, snr=3) from astropy.convolution import Gaussian2DKernel sigma = 3.0 / (2.0 * np.sqrt(2.0 * np.log(2.0))) # FWHM = 3 kernel = Gaussian2DKernel(sigma, x_size=3, y_size=3) kernel.normalize() segm = detect_sources(image, threshold, npixels=5, filter_kernel=kernel) # plot the image and the segmentation image import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(image, origin='lower', interpolation='nearest') ax2.imshow(segm.data, origin='lower', interpolation='nearest') """ from scipy import ndimage if (npixels <= 0) or (int(npixels) != npixels): raise ValueError('npixels must be a positive integer, got ' '"{0}"'.format(npixels)) image = (filter_data(data, filter_kernel, mode='constant', fill_value=0.0, check_normalization=True) > threshold) if mask is not None: if mask.shape != image.shape: raise ValueError('mask must have the same shape as the input ' 'image.') image &= ~mask if connectivity == 4: selem = ndimage.generate_binary_structure(2, 1) elif connectivity == 8: selem = ndimage.generate_binary_structure(2, 2) else: raise ValueError('Invalid connectivity={0}. ' 'Options are 4 or 8'.format(connectivity)) segm_img, nobj = ndimage.label(image, structure=selem) # remove objects with less than npixels # NOTE: for typical data, making the cutout images is ~10x faster # than using segm_img directly segm_slices = ndimage.find_objects(segm_img) for i, slices in enumerate(segm_slices): cutout = segm_img[slices] segment_mask = (cutout == (i+1)) if np.count_nonzero(segment_mask) < npixels: cutout[segment_mask] = 0 # now relabel to make consecutive label indices segm_img, nobj = ndimage.label(segm_img, structure=selem) if nobj == 0: warnings.warn('No sources were found.', NoDetectionsWarning) return None else: return SegmentationImage(segm_img)
[ "def", "detect_sources", "(", "data", ",", "threshold", ",", "npixels", ",", "filter_kernel", "=", "None", ",", "connectivity", "=", "8", ",", "mask", "=", "None", ")", ":", "from", "scipy", "import", "ndimage", "if", "(", "npixels", "<=", "0", ")", "or", "(", "int", "(", "npixels", ")", "!=", "npixels", ")", ":", "raise", "ValueError", "(", "'npixels must be a positive integer, got '", "'\"{0}\"'", ".", "format", "(", "npixels", ")", ")", "image", "=", "(", "filter_data", "(", "data", ",", "filter_kernel", ",", "mode", "=", "'constant'", ",", "fill_value", "=", "0.0", ",", "check_normalization", "=", "True", ")", ">", "threshold", ")", "if", "mask", "is", "not", "None", ":", "if", "mask", ".", "shape", "!=", "image", ".", "shape", ":", "raise", "ValueError", "(", "'mask must have the same shape as the input '", "'image.'", ")", "image", "&=", "~", "mask", "if", "connectivity", "==", "4", ":", "selem", "=", "ndimage", ".", "generate_binary_structure", "(", "2", ",", "1", ")", "elif", "connectivity", "==", "8", ":", "selem", "=", "ndimage", ".", "generate_binary_structure", "(", "2", ",", "2", ")", "else", ":", "raise", "ValueError", "(", "'Invalid connectivity={0}. '", "'Options are 4 or 8'", ".", "format", "(", "connectivity", ")", ")", "segm_img", ",", "nobj", "=", "ndimage", ".", "label", "(", "image", ",", "structure", "=", "selem", ")", "# remove objects with less than npixels", "# NOTE: for typical data, making the cutout images is ~10x faster", "# than using segm_img directly", "segm_slices", "=", "ndimage", ".", "find_objects", "(", "segm_img", ")", "for", "i", ",", "slices", "in", "enumerate", "(", "segm_slices", ")", ":", "cutout", "=", "segm_img", "[", "slices", "]", "segment_mask", "=", "(", "cutout", "==", "(", "i", "+", "1", ")", ")", "if", "np", ".", "count_nonzero", "(", "segment_mask", ")", "<", "npixels", ":", "cutout", "[", "segment_mask", "]", "=", "0", "# now relabel to make consecutive label indices", "segm_img", ",", "nobj", "=", "ndimage", ".", "label", "(", "segm_img", ",", "structure", "=", "selem", ")", "if", "nobj", "==", "0", ":", "warnings", ".", "warn", "(", "'No sources were found.'", ",", "NoDetectionsWarning", ")", "return", "None", "else", ":", "return", "SegmentationImage", "(", "segm_img", ")" ]
Detect sources above a specified threshold value in an image and return a `~photutils.segmentation.SegmentationImage` object. Detected sources must have ``npixels`` connected pixels that are each greater than the ``threshold`` value. If the filtering option is used, then the ``threshold`` is applied to the filtered image. The input ``mask`` can be used to mask pixels in the input data. Masked pixels will not be included in any source. This function does not deblend overlapping sources. First use this function to detect sources followed by :func:`~photutils.segmentation.deblend_sources` to deblend sources. Parameters ---------- data : array_like The 2D array of the image. threshold : float or array-like The data value or pixel-wise data values to be used for the detection threshold. A 2D ``threshold`` must have the same shape as ``data``. See `~photutils.detection.detect_threshold` for one way to create a ``threshold`` image. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. connectivity : {4, 8}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 4 or 8 (default). 4-connected pixels touch along their edges. 8-connected pixels touch along their edges or corners. For reference, SExtractor uses 8-connected pixels. mask : array_like (bool) A boolean mask, with the same shape as the input ``data``, where `True` values indicate masked pixels. Masked pixels will not be included in any source. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` or `None` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. If no sources are found then `None` is returned. See Also -------- :func:`photutils.detection.detect_threshold`, :class:`photutils.segmentation.SegmentationImage`, :func:`photutils.segmentation.source_properties` :func:`photutils.segmentation.deblend_sources` Examples -------- .. plot:: :include-source: # make a table of Gaussian sources from astropy.table import Table table = Table() table['amplitude'] = [50, 70, 150, 210] table['x_mean'] = [160, 25, 150, 90] table['y_mean'] = [70, 40, 25, 60] table['x_stddev'] = [15.2, 5.1, 3., 8.1] table['y_stddev'] = [2.6, 2.5, 3., 4.7] table['theta'] = np.array([145., 20., 0., 60.]) * np.pi / 180. # make an image of the sources with Gaussian noise from photutils.datasets import make_gaussian_sources_image from photutils.datasets import make_noise_image shape = (100, 200) sources = make_gaussian_sources_image(shape, table) noise = make_noise_image(shape, type='gaussian', mean=0., stddev=5., random_state=12345) image = sources + noise # detect the sources from photutils import detect_threshold, detect_sources threshold = detect_threshold(image, snr=3) from astropy.convolution import Gaussian2DKernel sigma = 3.0 / (2.0 * np.sqrt(2.0 * np.log(2.0))) # FWHM = 3 kernel = Gaussian2DKernel(sigma, x_size=3, y_size=3) kernel.normalize() segm = detect_sources(image, threshold, npixels=5, filter_kernel=kernel) # plot the image and the segmentation image import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(image, origin='lower', interpolation='nearest') ax2.imshow(segm.data, origin='lower', interpolation='nearest')
[ "Detect", "sources", "above", "a", "specified", "threshold", "value", "in", "an", "image", "and", "return", "a", "~photutils", ".", "segmentation", ".", "SegmentationImage", "object", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/detect.py#L18-L167
train
astropy/photutils
photutils/segmentation/detect.py
make_source_mask
def make_source_mask(data, snr, npixels, mask=None, mask_value=None, filter_fwhm=None, filter_size=3, filter_kernel=None, sigclip_sigma=3.0, sigclip_iters=5, dilate_size=11): """ Make a source mask using source segmentation and binary dilation. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. filter_fwhm : float, optional The full-width at half-maximum (FWHM) of the Gaussian kernel to filter the image before thresholding. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_size : float, optional The size of the square Gaussian kernel image. Used only if ``filter_fwhm`` is defined. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. ``filter_kernel`` overrides ``filter_fwhm`` and ``filter_size``. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. dilate_size : int, optional The size of the square array used to dilate the segmentation image. Returns ------- mask : 2D `~numpy.ndarray`, bool A 2D boolean image containing the source mask. """ from scipy import ndimage threshold = detect_threshold(data, snr, background=None, error=None, mask=mask, mask_value=None, sigclip_sigma=sigclip_sigma, sigclip_iters=sigclip_iters) kernel = None if filter_kernel is not None: kernel = filter_kernel if filter_fwhm is not None: sigma = filter_fwhm * gaussian_fwhm_to_sigma kernel = Gaussian2DKernel(sigma, x_size=filter_size, y_size=filter_size) if kernel is not None: kernel.normalize() segm = detect_sources(data, threshold, npixels, filter_kernel=kernel) selem = np.ones((dilate_size, dilate_size)) return ndimage.binary_dilation(segm.data.astype(np.bool), selem)
python
def make_source_mask(data, snr, npixels, mask=None, mask_value=None, filter_fwhm=None, filter_size=3, filter_kernel=None, sigclip_sigma=3.0, sigclip_iters=5, dilate_size=11): """ Make a source mask using source segmentation and binary dilation. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. filter_fwhm : float, optional The full-width at half-maximum (FWHM) of the Gaussian kernel to filter the image before thresholding. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_size : float, optional The size of the square Gaussian kernel image. Used only if ``filter_fwhm`` is defined. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. ``filter_kernel`` overrides ``filter_fwhm`` and ``filter_size``. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. dilate_size : int, optional The size of the square array used to dilate the segmentation image. Returns ------- mask : 2D `~numpy.ndarray`, bool A 2D boolean image containing the source mask. """ from scipy import ndimage threshold = detect_threshold(data, snr, background=None, error=None, mask=mask, mask_value=None, sigclip_sigma=sigclip_sigma, sigclip_iters=sigclip_iters) kernel = None if filter_kernel is not None: kernel = filter_kernel if filter_fwhm is not None: sigma = filter_fwhm * gaussian_fwhm_to_sigma kernel = Gaussian2DKernel(sigma, x_size=filter_size, y_size=filter_size) if kernel is not None: kernel.normalize() segm = detect_sources(data, threshold, npixels, filter_kernel=kernel) selem = np.ones((dilate_size, dilate_size)) return ndimage.binary_dilation(segm.data.astype(np.bool), selem)
[ "def", "make_source_mask", "(", "data", ",", "snr", ",", "npixels", ",", "mask", "=", "None", ",", "mask_value", "=", "None", ",", "filter_fwhm", "=", "None", ",", "filter_size", "=", "3", ",", "filter_kernel", "=", "None", ",", "sigclip_sigma", "=", "3.0", ",", "sigclip_iters", "=", "5", ",", "dilate_size", "=", "11", ")", ":", "from", "scipy", "import", "ndimage", "threshold", "=", "detect_threshold", "(", "data", ",", "snr", ",", "background", "=", "None", ",", "error", "=", "None", ",", "mask", "=", "mask", ",", "mask_value", "=", "None", ",", "sigclip_sigma", "=", "sigclip_sigma", ",", "sigclip_iters", "=", "sigclip_iters", ")", "kernel", "=", "None", "if", "filter_kernel", "is", "not", "None", ":", "kernel", "=", "filter_kernel", "if", "filter_fwhm", "is", "not", "None", ":", "sigma", "=", "filter_fwhm", "*", "gaussian_fwhm_to_sigma", "kernel", "=", "Gaussian2DKernel", "(", "sigma", ",", "x_size", "=", "filter_size", ",", "y_size", "=", "filter_size", ")", "if", "kernel", "is", "not", "None", ":", "kernel", ".", "normalize", "(", ")", "segm", "=", "detect_sources", "(", "data", ",", "threshold", ",", "npixels", ",", "filter_kernel", "=", "kernel", ")", "selem", "=", "np", ".", "ones", "(", "(", "dilate_size", ",", "dilate_size", ")", ")", "return", "ndimage", ".", "binary_dilation", "(", "segm", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", ",", "selem", ")" ]
Make a source mask using source segmentation and binary dilation. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. filter_fwhm : float, optional The full-width at half-maximum (FWHM) of the Gaussian kernel to filter the image before thresholding. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_size : float, optional The size of the square Gaussian kernel image. Used only if ``filter_fwhm`` is defined. ``filter_fwhm`` and ``filter_size`` are ignored if ``filter_kernel`` is defined. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. ``filter_kernel`` overrides ``filter_fwhm`` and ``filter_size``. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. dilate_size : int, optional The size of the square array used to dilate the segmentation image. Returns ------- mask : 2D `~numpy.ndarray`, bool A 2D boolean image containing the source mask.
[ "Make", "a", "source", "mask", "using", "source", "segmentation", "and", "binary", "dilation", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/detect.py#L170-L258
train
astropy/photutils
photutils/segmentation/core.py
Segment.data_ma
def data_ma(self): """ A 2D `~numpy.ma.MaskedArray` cutout image of the segment using the minimal bounding box. The mask is `True` for pixels outside of the source segment (i.e. neighboring segments within the rectangular cutout image are masked). """ mask = (self._segment_img[self.slices] != self.label) return np.ma.masked_array(self._segment_img[self.slices], mask=mask)
python
def data_ma(self): """ A 2D `~numpy.ma.MaskedArray` cutout image of the segment using the minimal bounding box. The mask is `True` for pixels outside of the source segment (i.e. neighboring segments within the rectangular cutout image are masked). """ mask = (self._segment_img[self.slices] != self.label) return np.ma.masked_array(self._segment_img[self.slices], mask=mask)
[ "def", "data_ma", "(", "self", ")", ":", "mask", "=", "(", "self", ".", "_segment_img", "[", "self", ".", "slices", "]", "!=", "self", ".", "label", ")", "return", "np", ".", "ma", ".", "masked_array", "(", "self", ".", "_segment_img", "[", "self", ".", "slices", "]", ",", "mask", "=", "mask", ")" ]
A 2D `~numpy.ma.MaskedArray` cutout image of the segment using the minimal bounding box. The mask is `True` for pixels outside of the source segment (i.e. neighboring segments within the rectangular cutout image are masked).
[ "A", "2D", "~numpy", ".", "ma", ".", "MaskedArray", "cutout", "image", "of", "the", "segment", "using", "the", "minimal", "bounding", "box", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L85-L96
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage._reset_lazy_properties
def _reset_lazy_properties(self): """Reset all lazy properties.""" for key, value in self.__class__.__dict__.items(): if isinstance(value, lazyproperty): self.__dict__.pop(key, None)
python
def _reset_lazy_properties(self): """Reset all lazy properties.""" for key, value in self.__class__.__dict__.items(): if isinstance(value, lazyproperty): self.__dict__.pop(key, None)
[ "def", "_reset_lazy_properties", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "__class__", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "lazyproperty", ")", ":", "self", ".", "__dict__", ".", "pop", "(", "key", ",", "None", ")" ]
Reset all lazy properties.
[ "Reset", "all", "lazy", "properties", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L200-L205
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.segments
def segments(self): """ A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ segments = [] for label, slc in zip(self.labels, self.slices): segments.append(Segment(self.data, label, slc, self.get_area(label))) return segments
python
def segments(self): """ A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ segments = [] for label, slc in zip(self.labels, self.slices): segments.append(Segment(self.data, label, slc, self.get_area(label))) return segments
[ "def", "segments", "(", "self", ")", ":", "segments", "=", "[", "]", "for", "label", ",", "slc", "in", "zip", "(", "self", ".", "labels", ",", "self", ".", "slices", ")", ":", "segments", ".", "append", "(", "Segment", "(", "self", ".", "data", ",", "label", ",", "slc", ",", "self", ".", "get_area", "(", "label", ")", ")", ")", "return", "segments" ]
A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute.
[ "A", "list", "of", "Segment", "objects", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L258-L271
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.get_index
def get_index(self, label): """ Find the index of the input ``label``. Parameters ---------- labels : int The label numbers to find. Returns ------- index : int The array index. Raises ------ ValueError If ``label`` is invalid. """ self.check_labels(label) return np.searchsorted(self.labels, label)
python
def get_index(self, label): """ Find the index of the input ``label``. Parameters ---------- labels : int The label numbers to find. Returns ------- index : int The array index. Raises ------ ValueError If ``label`` is invalid. """ self.check_labels(label) return np.searchsorted(self.labels, label)
[ "def", "get_index", "(", "self", ",", "label", ")", ":", "self", ".", "check_labels", "(", "label", ")", "return", "np", ".", "searchsorted", "(", "self", ".", "labels", ",", "label", ")" ]
Find the index of the input ``label``. Parameters ---------- labels : int The label numbers to find. Returns ------- index : int The array index. Raises ------ ValueError If ``label`` is invalid.
[ "Find", "the", "index", "of", "the", "input", "label", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L333-L354
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.get_indices
def get_indices(self, labels): """ Find the indices of the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to find. Returns ------- indices : int `~numpy.ndarray` An integer array of indices with the same shape as ``labels``. If ``labels`` is a scalar, then the returned index will also be a scalar. Raises ------ ValueError If any input ``labels`` are invalid. """ self.check_labels(labels) return np.searchsorted(self.labels, labels)
python
def get_indices(self, labels): """ Find the indices of the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to find. Returns ------- indices : int `~numpy.ndarray` An integer array of indices with the same shape as ``labels``. If ``labels`` is a scalar, then the returned index will also be a scalar. Raises ------ ValueError If any input ``labels`` are invalid. """ self.check_labels(labels) return np.searchsorted(self.labels, labels)
[ "def", "get_indices", "(", "self", ",", "labels", ")", ":", "self", ".", "check_labels", "(", "labels", ")", "return", "np", ".", "searchsorted", "(", "self", ".", "labels", ",", "labels", ")" ]
Find the indices of the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to find. Returns ------- indices : int `~numpy.ndarray` An integer array of indices with the same shape as ``labels``. If ``labels`` is a scalar, then the returned index will also be a scalar. Raises ------ ValueError If any input ``labels`` are invalid.
[ "Find", "the", "indices", "of", "the", "input", "labels", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L356-L379
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.slices
def slices(self): """ A list of tuples, where each tuple contains two slices representing the minimal box that contains the labeled region. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ from scipy.ndimage import find_objects return [slc for slc in find_objects(self._data) if slc is not None]
python
def slices(self): """ A list of tuples, where each tuple contains two slices representing the minimal box that contains the labeled region. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ from scipy.ndimage import find_objects return [slc for slc in find_objects(self._data) if slc is not None]
[ "def", "slices", "(", "self", ")", ":", "from", "scipy", ".", "ndimage", "import", "find_objects", "return", "[", "slc", "for", "slc", "in", "find_objects", "(", "self", ".", "_data", ")", "if", "slc", "is", "not", "None", "]" ]
A list of tuples, where each tuple contains two slices representing the minimal box that contains the labeled region. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute.
[ "A", "list", "of", "tuples", "where", "each", "tuple", "contains", "two", "slices", "representing", "the", "minimal", "box", "that", "contains", "the", "labeled", "region", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L382-L394
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.missing_labels
def missing_labels(self): """ A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number. """ return np.array(sorted(set(range(0, self.max_label + 1)). difference(np.insert(self.labels, 0, 0))))
python
def missing_labels(self): """ A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number. """ return np.array(sorted(set(range(0, self.max_label + 1)). difference(np.insert(self.labels, 0, 0))))
[ "def", "missing_labels", "(", "self", ")", ":", "return", "np", ".", "array", "(", "sorted", "(", "set", "(", "range", "(", "0", ",", "self", ".", "max_label", "+", "1", ")", ")", ".", "difference", "(", "np", ".", "insert", "(", "self", ".", "labels", ",", "0", ",", "0", ")", ")", ")", ")" ]
A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number.
[ "A", "1D", "~numpy", ".", "ndarray", "of", "the", "sorted", "non", "-", "zero", "labels", "that", "are", "missing", "in", "the", "consecutive", "sequence", "from", "zero", "to", "the", "maximum", "label", "number", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L466-L474
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.reassign_label
def reassign_label(self, label, new_label, relabel=False): """ Reassign a label number to a new number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``label`` number. Parameters ---------- labels : int The label number to reassign. new_label : int The newly assigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4, relabel=True) >>> segm.data array([[2, 2, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 1, 1, 0, 0], [4, 0, 0, 0, 0, 3], [4, 4, 0, 3, 3, 3], [4, 4, 0, 0, 3, 3]]) """ self.reassign_labels(label, new_label, relabel=relabel)
python
def reassign_label(self, label, new_label, relabel=False): """ Reassign a label number to a new number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``label`` number. Parameters ---------- labels : int The label number to reassign. new_label : int The newly assigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4, relabel=True) >>> segm.data array([[2, 2, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 1, 1, 0, 0], [4, 0, 0, 0, 0, 3], [4, 4, 0, 3, 3, 3], [4, 4, 0, 0, 3, 3]]) """ self.reassign_labels(label, new_label, relabel=relabel)
[ "def", "reassign_label", "(", "self", ",", "label", ",", "new_label", ",", "relabel", "=", "False", ")", ":", "self", ".", "reassign_labels", "(", "label", ",", "new_label", ",", "relabel", "=", "relabel", ")" ]
Reassign a label number to a new number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``label`` number. Parameters ---------- labels : int The label number to reassign. new_label : int The newly assigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_label(label=1, new_label=4, relabel=True) >>> segm.data array([[2, 2, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 1, 1, 0, 0], [4, 0, 0, 0, 0, 3], [4, 4, 0, 3, 3, 3], [4, 4, 0, 0, 3, 3]])
[ "Reassign", "a", "label", "number", "to", "a", "new", "number", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L611-L680
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.reassign_labels
def reassign_labels(self, labels, new_label, relabel=False): """ Reassign one or more label numbers. Multiple input ``labels`` will all be reassigned to the same ``new_label`` number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to reassign. new_label : int The reassigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [2, 0, 0, 0, 0, 5], [2, 2, 0, 5, 5, 5], [2, 2, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [4, 0, 0, 0, 0, 5], [4, 4, 0, 5, 5, 5], [4, 4, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [1, 0, 0, 0, 0, 4], [1, 1, 0, 4, 4, 4], [1, 1, 0, 0, 4, 4]]) """ self.check_labels(labels) labels = np.atleast_1d(labels) if len(labels) == 0: return idx = np.zeros(self.max_label + 1, dtype=int) idx[self.labels] = self.labels idx[labels] = new_label # calling the data setter resets all cached properties self.data = idx[self.data] if relabel: self.relabel_consecutive()
python
def reassign_labels(self, labels, new_label, relabel=False): """ Reassign one or more label numbers. Multiple input ``labels`` will all be reassigned to the same ``new_label`` number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to reassign. new_label : int The reassigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [2, 0, 0, 0, 0, 5], [2, 2, 0, 5, 5, 5], [2, 2, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [4, 0, 0, 0, 0, 5], [4, 4, 0, 5, 5, 5], [4, 4, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [1, 0, 0, 0, 0, 4], [1, 1, 0, 4, 4, 4], [1, 1, 0, 0, 4, 4]]) """ self.check_labels(labels) labels = np.atleast_1d(labels) if len(labels) == 0: return idx = np.zeros(self.max_label + 1, dtype=int) idx[self.labels] = self.labels idx[labels] = new_label # calling the data setter resets all cached properties self.data = idx[self.data] if relabel: self.relabel_consecutive()
[ "def", "reassign_labels", "(", "self", ",", "labels", ",", "new_label", ",", "relabel", "=", "False", ")", ":", "self", ".", "check_labels", "(", "labels", ")", "labels", "=", "np", ".", "atleast_1d", "(", "labels", ")", "if", "len", "(", "labels", ")", "==", "0", ":", "return", "idx", "=", "np", ".", "zeros", "(", "self", ".", "max_label", "+", "1", ",", "dtype", "=", "int", ")", "idx", "[", "self", ".", "labels", "]", "=", "self", ".", "labels", "idx", "[", "labels", "]", "=", "new_label", "# calling the data setter resets all cached properties", "self", ".", "data", "=", "idx", "[", "self", ".", "data", "]", "if", "relabel", ":", "self", ".", "relabel_consecutive", "(", ")" ]
Reassign one or more label numbers. Multiple input ``labels`` will all be reassigned to the same ``new_label`` number. If ``new_label`` is already present in the segmentation image, then it will be combined with the input ``labels``. Parameters ---------- labels : int, array-like (1D, int) The label numbers(s) to reassign. new_label : int The reassigned label number. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2) >>> segm.data array([[2, 2, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [2, 0, 0, 0, 0, 5], [2, 2, 0, 5, 5, 5], [2, 2, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=4) >>> segm.data array([[4, 4, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [4, 0, 0, 0, 0, 5], [4, 4, 0, 5, 5, 5], [4, 4, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.reassign_labels(labels=[1, 7], new_label=2, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [1, 0, 0, 0, 0, 4], [1, 1, 0, 4, 4, 4], [1, 1, 0, 0, 4, 4]])
[ "Reassign", "one", "or", "more", "label", "numbers", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L682-L767
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.relabel_consecutive
def relabel_consecutive(self, start_label=1): """ Reassign the label numbers consecutively, such that there are no missing label numbers. Parameters ---------- start_label : int, optional The starting label number, which should be a positive integer. The default is 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.relabel_consecutive() >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [5, 0, 0, 0, 0, 4], [5, 5, 0, 4, 4, 4], [5, 5, 0, 0, 4, 4]]) """ if start_label <= 0: raise ValueError('start_label must be > 0.') if self.is_consecutive and (self.labels[0] == start_label): return new_labels = np.zeros(self.max_label + 1, dtype=np.int) new_labels[self.labels] = np.arange(self.nlabels) + start_label self.data = new_labels[self.data]
python
def relabel_consecutive(self, start_label=1): """ Reassign the label numbers consecutively, such that there are no missing label numbers. Parameters ---------- start_label : int, optional The starting label number, which should be a positive integer. The default is 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.relabel_consecutive() >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [5, 0, 0, 0, 0, 4], [5, 5, 0, 4, 4, 4], [5, 5, 0, 0, 4, 4]]) """ if start_label <= 0: raise ValueError('start_label must be > 0.') if self.is_consecutive and (self.labels[0] == start_label): return new_labels = np.zeros(self.max_label + 1, dtype=np.int) new_labels[self.labels] = np.arange(self.nlabels) + start_label self.data = new_labels[self.data]
[ "def", "relabel_consecutive", "(", "self", ",", "start_label", "=", "1", ")", ":", "if", "start_label", "<=", "0", ":", "raise", "ValueError", "(", "'start_label must be > 0.'", ")", "if", "self", ".", "is_consecutive", "and", "(", "self", ".", "labels", "[", "0", "]", "==", "start_label", ")", ":", "return", "new_labels", "=", "np", ".", "zeros", "(", "self", ".", "max_label", "+", "1", ",", "dtype", "=", "np", ".", "int", ")", "new_labels", "[", "self", ".", "labels", "]", "=", "np", ".", "arange", "(", "self", ".", "nlabels", ")", "+", "start_label", "self", ".", "data", "=", "new_labels", "[", "self", ".", "data", "]" ]
Reassign the label numbers consecutively, such that there are no missing label numbers. Parameters ---------- start_label : int, optional The starting label number, which should be a positive integer. The default is 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.relabel_consecutive() >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [5, 0, 0, 0, 0, 4], [5, 5, 0, 4, 4, 4], [5, 5, 0, 0, 4, 4]])
[ "Reassign", "the", "label", "numbers", "consecutively", "such", "that", "there", "are", "no", "missing", "label", "numbers", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L769-L807
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.keep_label
def keep_label(self, label, relabel=False): """ Keep only the specified label. Parameters ---------- label : int The label number to keep. relabel : bool, optional If `True`, then the single segment will be assigned a label value of 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3, relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) """ self.keep_labels(label, relabel=relabel)
python
def keep_label(self, label, relabel=False): """ Keep only the specified label. Parameters ---------- label : int The label number to keep. relabel : bool, optional If `True`, then the single segment will be assigned a label value of 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3, relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) """ self.keep_labels(label, relabel=relabel)
[ "def", "keep_label", "(", "self", ",", "label", ",", "relabel", "=", "False", ")", ":", "self", ".", "keep_labels", "(", "label", ",", "relabel", "=", "relabel", ")" ]
Keep only the specified label. Parameters ---------- label : int The label number to keep. relabel : bool, optional If `True`, then the single segment will be assigned a label value of 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_label(label=3, relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]])
[ "Keep", "only", "the", "specified", "label", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L809-L856
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.keep_labels
def keep_labels(self, labels, relabel=False): """ Keep only the specified labels. Parameters ---------- labels : int, array-like (1D, int) The label number(s) to keep. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3]) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 5], [0, 0, 0, 5, 5, 5], [0, 0, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3], relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 2], [0, 0, 0, 2, 2, 2], [0, 0, 0, 0, 2, 2]]) """ self.check_labels(labels) labels = np.atleast_1d(labels) labels_tmp = list(set(self.labels) - set(labels)) self.remove_labels(labels_tmp, relabel=relabel)
python
def keep_labels(self, labels, relabel=False): """ Keep only the specified labels. Parameters ---------- labels : int, array-like (1D, int) The label number(s) to keep. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3]) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 5], [0, 0, 0, 5, 5, 5], [0, 0, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3], relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 2], [0, 0, 0, 2, 2, 2], [0, 0, 0, 0, 2, 2]]) """ self.check_labels(labels) labels = np.atleast_1d(labels) labels_tmp = list(set(self.labels) - set(labels)) self.remove_labels(labels_tmp, relabel=relabel)
[ "def", "keep_labels", "(", "self", ",", "labels", ",", "relabel", "=", "False", ")", ":", "self", ".", "check_labels", "(", "labels", ")", "labels", "=", "np", ".", "atleast_1d", "(", "labels", ")", "labels_tmp", "=", "list", "(", "set", "(", "self", ".", "labels", ")", "-", "set", "(", "labels", ")", ")", "self", ".", "remove_labels", "(", "labels_tmp", ",", "relabel", "=", "relabel", ")" ]
Keep only the specified labels. Parameters ---------- labels : int, array-like (1D, int) The label number(s) to keep. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3]) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 5], [0, 0, 0, 5, 5, 5], [0, 0, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.keep_labels(labels=[5, 3], relabel=True) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 2], [0, 0, 0, 2, 2, 2], [0, 0, 0, 0, 2, 2]])
[ "Keep", "only", "the", "specified", "labels", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L858-L910
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.remove_label
def remove_label(self, label, relabel=False): """ Remove the label number. The removed label is assigned a value of zero (i.e., background). Parameters ---------- label : int The label number to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [4, 0, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0]]) """ self.remove_labels(label, relabel=relabel)
python
def remove_label(self, label, relabel=False): """ Remove the label number. The removed label is assigned a value of zero (i.e., background). Parameters ---------- label : int The label number to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [4, 0, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0]]) """ self.remove_labels(label, relabel=relabel)
[ "def", "remove_label", "(", "self", ",", "label", ",", "relabel", "=", "False", ")", ":", "self", ".", "remove_labels", "(", "label", ",", "relabel", "=", "relabel", ")" ]
Remove the label number. The removed label is assigned a value of zero (i.e., background). Parameters ---------- label : int The label number to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_label(label=5, relabel=True) >>> segm.data array([[1, 1, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3], [0, 0, 2, 2, 0, 0], [4, 0, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0], [4, 4, 0, 0, 0, 0]])
[ "Remove", "the", "label", "number", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L912-L963
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.remove_labels
def remove_labels(self, labels, relabel=False): """ Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3]) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3], relabel=True) >>> segm.data array([[1, 1, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0]]) """ self.check_labels(labels) self.reassign_label(labels, new_label=0) if relabel: self.relabel_consecutive()
python
def remove_labels(self, labels, relabel=False): """ Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3]) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3], relabel=True) >>> segm.data array([[1, 1, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0]]) """ self.check_labels(labels) self.reassign_label(labels, new_label=0) if relabel: self.relabel_consecutive()
[ "def", "remove_labels", "(", "self", ",", "labels", ",", "relabel", "=", "False", ")", ":", "self", ".", "check_labels", "(", "labels", ")", "self", ".", "reassign_label", "(", "labels", ",", "new_label", "=", "0", ")", "if", "relabel", ":", "self", ".", "relabel_consecutive", "(", ")" ]
Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3]) >>> segm.data array([[1, 1, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0], [7, 7, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_labels(labels=[5, 3], relabel=True) >>> segm.data array([[1, 1, 0, 0, 2, 2], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0]])
[ "Remove", "one", "or", "more", "labels", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L965-L1019
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.remove_border_labels
def remove_border_labels(self, border_width, partial_overlap=True, relabel=False): """ Remove labeled segments near the image border. Labels within the defined border region will be removed. Parameters ---------- border_width : int The width of the border region in pixels. partial_overlap : bool, optional If this is set to `True` (the default), a segment that partially extends into the border region will be removed. Segments that are completely within the border region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1, ... partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) """ if border_width >= min(self.shape) / 2: raise ValueError('border_width must be smaller than half the ' 'image size in either dimension') border = np.zeros(self.shape, dtype=np.bool) border[:border_width, :] = True border[-border_width:, :] = True border[:, :border_width] = True border[:, -border_width:] = True self.remove_masked_labels(border, partial_overlap=partial_overlap, relabel=relabel)
python
def remove_border_labels(self, border_width, partial_overlap=True, relabel=False): """ Remove labeled segments near the image border. Labels within the defined border region will be removed. Parameters ---------- border_width : int The width of the border region in pixels. partial_overlap : bool, optional If this is set to `True` (the default), a segment that partially extends into the border region will be removed. Segments that are completely within the border region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1, ... partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) """ if border_width >= min(self.shape) / 2: raise ValueError('border_width must be smaller than half the ' 'image size in either dimension') border = np.zeros(self.shape, dtype=np.bool) border[:border_width, :] = True border[-border_width:, :] = True border[:, :border_width] = True border[:, -border_width:] = True self.remove_masked_labels(border, partial_overlap=partial_overlap, relabel=relabel)
[ "def", "remove_border_labels", "(", "self", ",", "border_width", ",", "partial_overlap", "=", "True", ",", "relabel", "=", "False", ")", ":", "if", "border_width", ">=", "min", "(", "self", ".", "shape", ")", "/", "2", ":", "raise", "ValueError", "(", "'border_width must be smaller than half the '", "'image size in either dimension'", ")", "border", "=", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "np", ".", "bool", ")", "border", "[", ":", "border_width", ",", ":", "]", "=", "True", "border", "[", "-", "border_width", ":", ",", ":", "]", "=", "True", "border", "[", ":", ",", ":", "border_width", "]", "=", "True", "border", "[", ":", ",", "-", "border_width", ":", "]", "=", "True", "self", ".", "remove_masked_labels", "(", "border", ",", "partial_overlap", "=", "partial_overlap", ",", "relabel", "=", "relabel", ")" ]
Remove labeled segments near the image border. Labels within the defined border region will be removed. Parameters ---------- border_width : int The width of the border region in pixels. partial_overlap : bool, optional If this is set to `True` (the default), a segment that partially extends into the border region will be removed. Segments that are completely within the border region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_border_labels(border_width=1, ... partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]])
[ "Remove", "labeled", "segments", "near", "the", "image", "border", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L1021-L1088
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.remove_masked_labels
def remove_masked_labels(self, mask, partial_overlap=True, relabel=False): """ Remove labeled segments located within a masked region. Parameters ---------- mask : array_like (bool) A boolean mask, with the same shape as the segmentation image, where `True` values indicate masked pixels. partial_overlap : bool, optional If this is set to `True` (default), a segment that partially extends into a masked region will also be removed. Segments that are completely within a masked region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> mask = np.zeros_like(segm.data, dtype=np.bool) >>> mask[0, :] = True # mask the first row >>> segm.remove_masked_labels(mask) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_masked_labels(mask, partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) """ if mask.shape != self.shape: raise ValueError('mask must have the same shape as the ' 'segmentation image') remove_labels = self._get_labels(self.data[mask]) if not partial_overlap: interior_labels = self._get_labels(self.data[~mask]) remove_labels = list(set(remove_labels) - set(interior_labels)) self.remove_labels(remove_labels, relabel=relabel)
python
def remove_masked_labels(self, mask, partial_overlap=True, relabel=False): """ Remove labeled segments located within a masked region. Parameters ---------- mask : array_like (bool) A boolean mask, with the same shape as the segmentation image, where `True` values indicate masked pixels. partial_overlap : bool, optional If this is set to `True` (default), a segment that partially extends into a masked region will also be removed. Segments that are completely within a masked region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> mask = np.zeros_like(segm.data, dtype=np.bool) >>> mask[0, :] = True # mask the first row >>> segm.remove_masked_labels(mask) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_masked_labels(mask, partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) """ if mask.shape != self.shape: raise ValueError('mask must have the same shape as the ' 'segmentation image') remove_labels = self._get_labels(self.data[mask]) if not partial_overlap: interior_labels = self._get_labels(self.data[~mask]) remove_labels = list(set(remove_labels) - set(interior_labels)) self.remove_labels(remove_labels, relabel=relabel)
[ "def", "remove_masked_labels", "(", "self", ",", "mask", ",", "partial_overlap", "=", "True", ",", "relabel", "=", "False", ")", ":", "if", "mask", ".", "shape", "!=", "self", ".", "shape", ":", "raise", "ValueError", "(", "'mask must have the same shape as the '", "'segmentation image'", ")", "remove_labels", "=", "self", ".", "_get_labels", "(", "self", ".", "data", "[", "mask", "]", ")", "if", "not", "partial_overlap", ":", "interior_labels", "=", "self", ".", "_get_labels", "(", "self", ".", "data", "[", "~", "mask", "]", ")", "remove_labels", "=", "list", "(", "set", "(", "remove_labels", ")", "-", "set", "(", "interior_labels", ")", ")", "self", ".", "remove_labels", "(", "remove_labels", ",", "relabel", "=", "relabel", ")" ]
Remove labeled segments located within a masked region. Parameters ---------- mask : array_like (bool) A boolean mask, with the same shape as the segmentation image, where `True` values indicate masked pixels. partial_overlap : bool, optional If this is set to `True` (default), a segment that partially extends into a masked region will also be removed. Segments that are completely within a masked region are always removed. relabel : bool, optional If `True`, then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> mask = np.zeros_like(segm.data, dtype=np.bool) >>> mask[0, :] = True # mask the first row >>> segm.remove_masked_labels(mask) >>> segm.data array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]]) >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4], ... [0, 0, 0, 0, 0, 4], ... [0, 0, 3, 3, 0, 0], ... [7, 0, 0, 0, 0, 5], ... [7, 7, 0, 5, 5, 5], ... [7, 7, 0, 0, 5, 5]]) >>> segm.remove_masked_labels(mask, partial_overlap=False) >>> segm.data array([[0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 0, 4], [0, 0, 3, 3, 0, 0], [7, 0, 0, 0, 0, 5], [7, 7, 0, 5, 5, 5], [7, 7, 0, 0, 5, 5]])
[ "Remove", "labeled", "segments", "located", "within", "a", "masked", "region", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L1090-L1155
train
astropy/photutils
photutils/segmentation/core.py
SegmentationImage.outline_segments
def outline_segments(self, mask_background=False): """ Outline the labeled segments. The "outlines" represent the pixels *just inside* the segments, leaving the background pixels unmodified. Parameters ---------- mask_background : bool, optional Set to `True` to mask the background pixels (labels = 0) in the returned image. This is useful for overplotting the segment outlines on an image. The default is `False`. Returns ------- boundaries : 2D `~numpy.ndarray` or `~numpy.ma.MaskedArray` An image with the same shape of the segmentation image containing only the outlines of the labeled segments. The pixel values in the outlines correspond to the labels in the segmentation image. If ``mask_background`` is `True`, then a `~numpy.ma.MaskedArray` is returned. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[0, 0, 0, 0, 0, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 0, 0, 0, 0, 0]]) >>> segm.outline_segments() array([[0, 0, 0, 0, 0, 0], [0, 2, 2, 2, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0]]) """ from scipy.ndimage import grey_erosion, grey_dilation # mode='constant' ensures outline is included on the image borders selem = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) eroded = grey_erosion(self.data, footprint=selem, mode='constant', cval=0.) dilated = grey_dilation(self.data, footprint=selem, mode='constant', cval=0.) outlines = ((dilated != eroded) & (self.data != 0)).astype(int) outlines *= self.data if mask_background: outlines = np.ma.masked_where(outlines == 0, outlines) return outlines
python
def outline_segments(self, mask_background=False): """ Outline the labeled segments. The "outlines" represent the pixels *just inside* the segments, leaving the background pixels unmodified. Parameters ---------- mask_background : bool, optional Set to `True` to mask the background pixels (labels = 0) in the returned image. This is useful for overplotting the segment outlines on an image. The default is `False`. Returns ------- boundaries : 2D `~numpy.ndarray` or `~numpy.ma.MaskedArray` An image with the same shape of the segmentation image containing only the outlines of the labeled segments. The pixel values in the outlines correspond to the labels in the segmentation image. If ``mask_background`` is `True`, then a `~numpy.ma.MaskedArray` is returned. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[0, 0, 0, 0, 0, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 0, 0, 0, 0, 0]]) >>> segm.outline_segments() array([[0, 0, 0, 0, 0, 0], [0, 2, 2, 2, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0]]) """ from scipy.ndimage import grey_erosion, grey_dilation # mode='constant' ensures outline is included on the image borders selem = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) eroded = grey_erosion(self.data, footprint=selem, mode='constant', cval=0.) dilated = grey_dilation(self.data, footprint=selem, mode='constant', cval=0.) outlines = ((dilated != eroded) & (self.data != 0)).astype(int) outlines *= self.data if mask_background: outlines = np.ma.masked_where(outlines == 0, outlines) return outlines
[ "def", "outline_segments", "(", "self", ",", "mask_background", "=", "False", ")", ":", "from", "scipy", ".", "ndimage", "import", "grey_erosion", ",", "grey_dilation", "# mode='constant' ensures outline is included on the image borders", "selem", "=", "np", ".", "array", "(", "[", "[", "0", ",", "1", ",", "0", "]", ",", "[", "1", ",", "1", ",", "1", "]", ",", "[", "0", ",", "1", ",", "0", "]", "]", ")", "eroded", "=", "grey_erosion", "(", "self", ".", "data", ",", "footprint", "=", "selem", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.", ")", "dilated", "=", "grey_dilation", "(", "self", ".", "data", ",", "footprint", "=", "selem", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.", ")", "outlines", "=", "(", "(", "dilated", "!=", "eroded", ")", "&", "(", "self", ".", "data", "!=", "0", ")", ")", ".", "astype", "(", "int", ")", "outlines", "*=", "self", ".", "data", "if", "mask_background", ":", "outlines", "=", "np", ".", "ma", ".", "masked_where", "(", "outlines", "==", "0", ",", "outlines", ")", "return", "outlines" ]
Outline the labeled segments. The "outlines" represent the pixels *just inside* the segments, leaving the background pixels unmodified. Parameters ---------- mask_background : bool, optional Set to `True` to mask the background pixels (labels = 0) in the returned image. This is useful for overplotting the segment outlines on an image. The default is `False`. Returns ------- boundaries : 2D `~numpy.ndarray` or `~numpy.ma.MaskedArray` An image with the same shape of the segmentation image containing only the outlines of the labeled segments. The pixel values in the outlines correspond to the labels in the segmentation image. If ``mask_background`` is `True`, then a `~numpy.ma.MaskedArray` is returned. Examples -------- >>> from photutils import SegmentationImage >>> segm = SegmentationImage([[0, 0, 0, 0, 0, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 2, 2, 2, 2, 0], ... [0, 0, 0, 0, 0, 0]]) >>> segm.outline_segments() array([[0, 0, 0, 0, 0, 0], [0, 2, 2, 2, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 0, 0, 2, 0], [0, 2, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0]])
[ "Outline", "the", "labeled", "segments", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L1157-L1213
train
astropy/photutils
photutils/aperture/mask.py
ApertureMask._overlap_slices
def _overlap_slices(self, shape): """ Calculate the slices for the overlapping part of the bounding box and an array of the given shape. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of array where the slices are to be applied. Returns ------- slices_large : tuple of slices A tuple of slice objects for each axis of the large array, such that ``large_array[slices_large]`` extracts the region of the large array that overlaps with the small array. slices_small : slice A tuple of slice objects for each axis of the small array, such that ``small_array[slices_small]`` extracts the region of the small array that is inside the large array. """ if len(shape) != 2: raise ValueError('input shape must have 2 elements.') xmin = self.bbox.ixmin xmax = self.bbox.ixmax ymin = self.bbox.iymin ymax = self.bbox.iymax if xmin >= shape[1] or ymin >= shape[0] or xmax <= 0 or ymax <= 0: # no overlap of the aperture with the data return None, None slices_large = (slice(max(ymin, 0), min(ymax, shape[0])), slice(max(xmin, 0), min(xmax, shape[1]))) slices_small = (slice(max(-ymin, 0), min(ymax - ymin, shape[0] - ymin)), slice(max(-xmin, 0), min(xmax - xmin, shape[1] - xmin))) return slices_large, slices_small
python
def _overlap_slices(self, shape): """ Calculate the slices for the overlapping part of the bounding box and an array of the given shape. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of array where the slices are to be applied. Returns ------- slices_large : tuple of slices A tuple of slice objects for each axis of the large array, such that ``large_array[slices_large]`` extracts the region of the large array that overlaps with the small array. slices_small : slice A tuple of slice objects for each axis of the small array, such that ``small_array[slices_small]`` extracts the region of the small array that is inside the large array. """ if len(shape) != 2: raise ValueError('input shape must have 2 elements.') xmin = self.bbox.ixmin xmax = self.bbox.ixmax ymin = self.bbox.iymin ymax = self.bbox.iymax if xmin >= shape[1] or ymin >= shape[0] or xmax <= 0 or ymax <= 0: # no overlap of the aperture with the data return None, None slices_large = (slice(max(ymin, 0), min(ymax, shape[0])), slice(max(xmin, 0), min(xmax, shape[1]))) slices_small = (slice(max(-ymin, 0), min(ymax - ymin, shape[0] - ymin)), slice(max(-xmin, 0), min(xmax - xmin, shape[1] - xmin))) return slices_large, slices_small
[ "def", "_overlap_slices", "(", "self", ",", "shape", ")", ":", "if", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'input shape must have 2 elements.'", ")", "xmin", "=", "self", ".", "bbox", ".", "ixmin", "xmax", "=", "self", ".", "bbox", ".", "ixmax", "ymin", "=", "self", ".", "bbox", ".", "iymin", "ymax", "=", "self", ".", "bbox", ".", "iymax", "if", "xmin", ">=", "shape", "[", "1", "]", "or", "ymin", ">=", "shape", "[", "0", "]", "or", "xmax", "<=", "0", "or", "ymax", "<=", "0", ":", "# no overlap of the aperture with the data", "return", "None", ",", "None", "slices_large", "=", "(", "slice", "(", "max", "(", "ymin", ",", "0", ")", ",", "min", "(", "ymax", ",", "shape", "[", "0", "]", ")", ")", ",", "slice", "(", "max", "(", "xmin", ",", "0", ")", ",", "min", "(", "xmax", ",", "shape", "[", "1", "]", ")", ")", ")", "slices_small", "=", "(", "slice", "(", "max", "(", "-", "ymin", ",", "0", ")", ",", "min", "(", "ymax", "-", "ymin", ",", "shape", "[", "0", "]", "-", "ymin", ")", ")", ",", "slice", "(", "max", "(", "-", "xmin", ",", "0", ")", ",", "min", "(", "xmax", "-", "xmin", ",", "shape", "[", "1", "]", "-", "xmin", ")", ")", ")", "return", "slices_large", ",", "slices_small" ]
Calculate the slices for the overlapping part of the bounding box and an array of the given shape. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of array where the slices are to be applied. Returns ------- slices_large : tuple of slices A tuple of slice objects for each axis of the large array, such that ``large_array[slices_large]`` extracts the region of the large array that overlaps with the small array. slices_small : slice A tuple of slice objects for each axis of the small array, such that ``small_array[slices_small]`` extracts the region of the small array that is inside the large array.
[ "Calculate", "the", "slices", "for", "the", "overlapping", "part", "of", "the", "bounding", "box", "and", "an", "array", "of", "the", "given", "shape", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/mask.py#L49-L93
train
astropy/photutils
photutils/aperture/mask.py
ApertureMask.to_image
def to_image(self, shape): """ Return an image of the mask in a 2D array of the given shape, taking any edge effects into account. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of the output array. Returns ------- result : `~numpy.ndarray` A 2D array of the mask. """ if len(shape) != 2: raise ValueError('input shape must have 2 elements.') image = np.zeros(shape) if self.bbox.ixmin < 0 or self.bbox.iymin < 0: return self._to_image_partial_overlap(image) try: image[self.bbox.slices] = self.data except ValueError: # partial or no overlap image = self._to_image_partial_overlap(image) return image
python
def to_image(self, shape): """ Return an image of the mask in a 2D array of the given shape, taking any edge effects into account. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of the output array. Returns ------- result : `~numpy.ndarray` A 2D array of the mask. """ if len(shape) != 2: raise ValueError('input shape must have 2 elements.') image = np.zeros(shape) if self.bbox.ixmin < 0 or self.bbox.iymin < 0: return self._to_image_partial_overlap(image) try: image[self.bbox.slices] = self.data except ValueError: # partial or no overlap image = self._to_image_partial_overlap(image) return image
[ "def", "to_image", "(", "self", ",", "shape", ")", ":", "if", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'input shape must have 2 elements.'", ")", "image", "=", "np", ".", "zeros", "(", "shape", ")", "if", "self", ".", "bbox", ".", "ixmin", "<", "0", "or", "self", ".", "bbox", ".", "iymin", "<", "0", ":", "return", "self", ".", "_to_image_partial_overlap", "(", "image", ")", "try", ":", "image", "[", "self", ".", "bbox", ".", "slices", "]", "=", "self", ".", "data", "except", "ValueError", ":", "# partial or no overlap", "image", "=", "self", ".", "_to_image_partial_overlap", "(", "image", ")", "return", "image" ]
Return an image of the mask in a 2D array of the given shape, taking any edge effects into account. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of the output array. Returns ------- result : `~numpy.ndarray` A 2D array of the mask.
[ "Return", "an", "image", "of", "the", "mask", "in", "a", "2D", "array", "of", "the", "given", "shape", "taking", "any", "edge", "effects", "into", "account", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/mask.py#L112-L141
train
astropy/photutils
photutils/aperture/mask.py
ApertureMask.cutout
def cutout(self, data, fill_value=0., copy=False): """ Create a cutout from the input data over the mask bounding box, taking any edge effects into account. Parameters ---------- data : array_like A 2D array on which to apply the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. copy : bool, optional If `True` then the returned cutout array will always be hold a copy of the input ``data``. If `False` and the mask is fully within the input ``data``, then the returned cutout array will be a view into the input ``data``. In cases where the mask partially overlaps or has no overlap with the input ``data``, the returned cutout array will always hold a copy of the input ``data`` (i.e. this keyword has no effect). Returns ------- result : `~numpy.ndarray` A 2D array cut out from the input ``data`` representing the same cutout region as the aperture mask. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value``. `None` is returned if there is no overlap of the aperture with the input ``data``. """ data = np.asanyarray(data) if data.ndim != 2: raise ValueError('data must be a 2D array.') partial_overlap = False if self.bbox.ixmin < 0 or self.bbox.iymin < 0: partial_overlap = True if not partial_overlap: # try this for speed -- the result may still be a partial # overlap, in which case the next block will be triggered if copy: cutout = np.copy(data[self.bbox.slices]) else: cutout = data[self.bbox.slices] if partial_overlap or (cutout.shape != self.shape): slices_large, slices_small = self._overlap_slices(data.shape) if slices_small is None: return None # no overlap # cutout is a copy cutout = np.zeros(self.shape, dtype=data.dtype) cutout[:] = fill_value cutout[slices_small] = data[slices_large] if isinstance(data, u.Quantity): cutout = u.Quantity(cutout, unit=data.unit) return cutout
python
def cutout(self, data, fill_value=0., copy=False): """ Create a cutout from the input data over the mask bounding box, taking any edge effects into account. Parameters ---------- data : array_like A 2D array on which to apply the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. copy : bool, optional If `True` then the returned cutout array will always be hold a copy of the input ``data``. If `False` and the mask is fully within the input ``data``, then the returned cutout array will be a view into the input ``data``. In cases where the mask partially overlaps or has no overlap with the input ``data``, the returned cutout array will always hold a copy of the input ``data`` (i.e. this keyword has no effect). Returns ------- result : `~numpy.ndarray` A 2D array cut out from the input ``data`` representing the same cutout region as the aperture mask. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value``. `None` is returned if there is no overlap of the aperture with the input ``data``. """ data = np.asanyarray(data) if data.ndim != 2: raise ValueError('data must be a 2D array.') partial_overlap = False if self.bbox.ixmin < 0 or self.bbox.iymin < 0: partial_overlap = True if not partial_overlap: # try this for speed -- the result may still be a partial # overlap, in which case the next block will be triggered if copy: cutout = np.copy(data[self.bbox.slices]) else: cutout = data[self.bbox.slices] if partial_overlap or (cutout.shape != self.shape): slices_large, slices_small = self._overlap_slices(data.shape) if slices_small is None: return None # no overlap # cutout is a copy cutout = np.zeros(self.shape, dtype=data.dtype) cutout[:] = fill_value cutout[slices_small] = data[slices_large] if isinstance(data, u.Quantity): cutout = u.Quantity(cutout, unit=data.unit) return cutout
[ "def", "cutout", "(", "self", ",", "data", ",", "fill_value", "=", "0.", ",", "copy", "=", "False", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'data must be a 2D array.'", ")", "partial_overlap", "=", "False", "if", "self", ".", "bbox", ".", "ixmin", "<", "0", "or", "self", ".", "bbox", ".", "iymin", "<", "0", ":", "partial_overlap", "=", "True", "if", "not", "partial_overlap", ":", "# try this for speed -- the result may still be a partial", "# overlap, in which case the next block will be triggered", "if", "copy", ":", "cutout", "=", "np", ".", "copy", "(", "data", "[", "self", ".", "bbox", ".", "slices", "]", ")", "else", ":", "cutout", "=", "data", "[", "self", ".", "bbox", ".", "slices", "]", "if", "partial_overlap", "or", "(", "cutout", ".", "shape", "!=", "self", ".", "shape", ")", ":", "slices_large", ",", "slices_small", "=", "self", ".", "_overlap_slices", "(", "data", ".", "shape", ")", "if", "slices_small", "is", "None", ":", "return", "None", "# no overlap", "# cutout is a copy", "cutout", "=", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "data", ".", "dtype", ")", "cutout", "[", ":", "]", "=", "fill_value", "cutout", "[", "slices_small", "]", "=", "data", "[", "slices_large", "]", "if", "isinstance", "(", "data", ",", "u", ".", "Quantity", ")", ":", "cutout", "=", "u", ".", "Quantity", "(", "cutout", ",", "unit", "=", "data", ".", "unit", ")", "return", "cutout" ]
Create a cutout from the input data over the mask bounding box, taking any edge effects into account. Parameters ---------- data : array_like A 2D array on which to apply the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. copy : bool, optional If `True` then the returned cutout array will always be hold a copy of the input ``data``. If `False` and the mask is fully within the input ``data``, then the returned cutout array will be a view into the input ``data``. In cases where the mask partially overlaps or has no overlap with the input ``data``, the returned cutout array will always hold a copy of the input ``data`` (i.e. this keyword has no effect). Returns ------- result : `~numpy.ndarray` A 2D array cut out from the input ``data`` representing the same cutout region as the aperture mask. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value``. `None` is returned if there is no overlap of the aperture with the input ``data``.
[ "Create", "a", "cutout", "from", "the", "input", "data", "over", "the", "mask", "bounding", "box", "taking", "any", "edge", "effects", "into", "account", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/mask.py#L143-L208
train
astropy/photutils
photutils/aperture/mask.py
ApertureMask.multiply
def multiply(self, data, fill_value=0.): """ Multiply the aperture mask with the input data, taking any edge effects into account. The result is a mask-weighted cutout from the data. Parameters ---------- data : array_like or `~astropy.units.Quantity` The 2D array to multiply with the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. Returns ------- result : `~numpy.ndarray` A 2D mask-weighted cutout from the input ``data``. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value`` before being multipled with the mask. `None` is returned if there is no overlap of the aperture with the input ``data``. """ cutout = self.cutout(data, fill_value=fill_value) if cutout is None: return None else: return cutout * self.data
python
def multiply(self, data, fill_value=0.): """ Multiply the aperture mask with the input data, taking any edge effects into account. The result is a mask-weighted cutout from the data. Parameters ---------- data : array_like or `~astropy.units.Quantity` The 2D array to multiply with the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. Returns ------- result : `~numpy.ndarray` A 2D mask-weighted cutout from the input ``data``. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value`` before being multipled with the mask. `None` is returned if there is no overlap of the aperture with the input ``data``. """ cutout = self.cutout(data, fill_value=fill_value) if cutout is None: return None else: return cutout * self.data
[ "def", "multiply", "(", "self", ",", "data", ",", "fill_value", "=", "0.", ")", ":", "cutout", "=", "self", ".", "cutout", "(", "data", ",", "fill_value", "=", "fill_value", ")", "if", "cutout", "is", "None", ":", "return", "None", "else", ":", "return", "cutout", "*", "self", ".", "data" ]
Multiply the aperture mask with the input data, taking any edge effects into account. The result is a mask-weighted cutout from the data. Parameters ---------- data : array_like or `~astropy.units.Quantity` The 2D array to multiply with the aperture mask. fill_value : float, optional The value is used to fill pixels where the aperture mask does not overlap with the input ``data``. The default is 0. Returns ------- result : `~numpy.ndarray` A 2D mask-weighted cutout from the input ``data``. If there is a partial overlap of the aperture mask with the input data, pixels outside of the data will be assigned to ``fill_value`` before being multipled with the mask. `None` is returned if there is no overlap of the aperture with the input ``data``.
[ "Multiply", "the", "aperture", "mask", "with", "the", "input", "data", "taking", "any", "edge", "effects", "into", "account", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/mask.py#L210-L241
train
astropy/photutils
photutils/segmentation/deblend.py
deblend_sources
def deblend_sources(data, segment_img, npixels, filter_kernel=None, labels=None, nlevels=32, contrast=0.001, mode='exponential', connectivity=8, relabel=True): """ Deblend overlapping sources labeled in a segmentation image. Sources are deblended using a combination of multi-thresholding and `watershed segmentation <https://en.wikipedia.org/wiki/Watershed_(image_processing)>`_. In order to deblend sources, they must be separated enough such that there is a saddle between them. Parameters ---------- data : array_like The 2D array of the image. segment_img : `~photutils.segmentation.SegmentationImage` or array_like (int) A 2D segmentation image, either as a `~photutils.segmentation.SegmentationImage` object or an `~numpy.ndarray`, with the same shape as ``data`` where sources are labeled by different positive integer values. A value of zero is reserved for the background. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. labels : int or array-like of int, optional The label numbers to deblend. If `None` (default), then all labels in the segmentation image will be deblended. nlevels : int, optional The number of multi-thresholding levels to use. Each source will be re-thresholded at ``nlevels``, spaced exponentially or linearly (see the ``mode`` keyword), between its minimum and maximum values within the source segment. contrast : float, optional The fraction of the total (blended) source flux that a local peak must have to be considered as a separate object. ``contrast`` must be between 0 and 1, inclusive. If ``contrast = 0`` then every local peak will be made a separate object (maximum deblending). If ``contrast = 1`` then no deblending will occur. The default is 0.001, which will deblend sources with a magnitude difference of about 7.5. mode : {'exponential', 'linear'}, optional The mode used in defining the spacing between the multi-thresholding levels (see the ``nlevels`` keyword). The default is 'exponential'. connectivity : {8, 4}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 8 (default) or 4. 8-connected pixels touch along their edges or corners. 4-connected pixels touch along their edges. For reference, SExtractor uses 8-connected pixels. relabel : bool If `True` (default), then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. See Also -------- :func:`photutils.detect_sources` """ if not isinstance(segment_img, SegmentationImage): segment_img = SegmentationImage(segment_img) if segment_img.shape != data.shape: raise ValueError('The data and segmentation image must have ' 'the same shape') if labels is None: labels = segment_img.labels labels = np.atleast_1d(labels) segment_img.check_labels(labels) data = filter_data(data, filter_kernel, mode='constant', fill_value=0.0) last_label = segment_img.max_label segm_deblended = deepcopy(segment_img) for label in labels: source_slice = segment_img.slices[segment_img.get_index(label)] source_data = data[source_slice] source_segm = SegmentationImage(np.copy( segment_img.data[source_slice])) source_segm.keep_labels(label) # include only one label source_deblended = _deblend_source( source_data, source_segm, npixels, nlevels=nlevels, contrast=contrast, mode=mode, connectivity=connectivity) if not np.array_equal(source_deblended.data.astype(bool), source_segm.data.astype(bool)): raise ValueError('Deblending failed for source "{0}". Please ' 'ensure you used the same pixel connectivity ' 'in detect_sources and deblend_sources. If ' 'this issue persists, then please inform the ' 'developers.'.format(label)) if source_deblended.nlabels > 1: # replace the original source with the deblended source source_mask = (source_deblended.data > 0) segm_tmp = segm_deblended.data segm_tmp[source_slice][source_mask] = ( source_deblended.data[source_mask] + last_label) segm_deblended.data = segm_tmp # needed to call data setter last_label += source_deblended.nlabels if relabel: segm_deblended.relabel_consecutive() return segm_deblended
python
def deblend_sources(data, segment_img, npixels, filter_kernel=None, labels=None, nlevels=32, contrast=0.001, mode='exponential', connectivity=8, relabel=True): """ Deblend overlapping sources labeled in a segmentation image. Sources are deblended using a combination of multi-thresholding and `watershed segmentation <https://en.wikipedia.org/wiki/Watershed_(image_processing)>`_. In order to deblend sources, they must be separated enough such that there is a saddle between them. Parameters ---------- data : array_like The 2D array of the image. segment_img : `~photutils.segmentation.SegmentationImage` or array_like (int) A 2D segmentation image, either as a `~photutils.segmentation.SegmentationImage` object or an `~numpy.ndarray`, with the same shape as ``data`` where sources are labeled by different positive integer values. A value of zero is reserved for the background. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. labels : int or array-like of int, optional The label numbers to deblend. If `None` (default), then all labels in the segmentation image will be deblended. nlevels : int, optional The number of multi-thresholding levels to use. Each source will be re-thresholded at ``nlevels``, spaced exponentially or linearly (see the ``mode`` keyword), between its minimum and maximum values within the source segment. contrast : float, optional The fraction of the total (blended) source flux that a local peak must have to be considered as a separate object. ``contrast`` must be between 0 and 1, inclusive. If ``contrast = 0`` then every local peak will be made a separate object (maximum deblending). If ``contrast = 1`` then no deblending will occur. The default is 0.001, which will deblend sources with a magnitude difference of about 7.5. mode : {'exponential', 'linear'}, optional The mode used in defining the spacing between the multi-thresholding levels (see the ``nlevels`` keyword). The default is 'exponential'. connectivity : {8, 4}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 8 (default) or 4. 8-connected pixels touch along their edges or corners. 4-connected pixels touch along their edges. For reference, SExtractor uses 8-connected pixels. relabel : bool If `True` (default), then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. See Also -------- :func:`photutils.detect_sources` """ if not isinstance(segment_img, SegmentationImage): segment_img = SegmentationImage(segment_img) if segment_img.shape != data.shape: raise ValueError('The data and segmentation image must have ' 'the same shape') if labels is None: labels = segment_img.labels labels = np.atleast_1d(labels) segment_img.check_labels(labels) data = filter_data(data, filter_kernel, mode='constant', fill_value=0.0) last_label = segment_img.max_label segm_deblended = deepcopy(segment_img) for label in labels: source_slice = segment_img.slices[segment_img.get_index(label)] source_data = data[source_slice] source_segm = SegmentationImage(np.copy( segment_img.data[source_slice])) source_segm.keep_labels(label) # include only one label source_deblended = _deblend_source( source_data, source_segm, npixels, nlevels=nlevels, contrast=contrast, mode=mode, connectivity=connectivity) if not np.array_equal(source_deblended.data.astype(bool), source_segm.data.astype(bool)): raise ValueError('Deblending failed for source "{0}". Please ' 'ensure you used the same pixel connectivity ' 'in detect_sources and deblend_sources. If ' 'this issue persists, then please inform the ' 'developers.'.format(label)) if source_deblended.nlabels > 1: # replace the original source with the deblended source source_mask = (source_deblended.data > 0) segm_tmp = segm_deblended.data segm_tmp[source_slice][source_mask] = ( source_deblended.data[source_mask] + last_label) segm_deblended.data = segm_tmp # needed to call data setter last_label += source_deblended.nlabels if relabel: segm_deblended.relabel_consecutive() return segm_deblended
[ "def", "deblend_sources", "(", "data", ",", "segment_img", ",", "npixels", ",", "filter_kernel", "=", "None", ",", "labels", "=", "None", ",", "nlevels", "=", "32", ",", "contrast", "=", "0.001", ",", "mode", "=", "'exponential'", ",", "connectivity", "=", "8", ",", "relabel", "=", "True", ")", ":", "if", "not", "isinstance", "(", "segment_img", ",", "SegmentationImage", ")", ":", "segment_img", "=", "SegmentationImage", "(", "segment_img", ")", "if", "segment_img", ".", "shape", "!=", "data", ".", "shape", ":", "raise", "ValueError", "(", "'The data and segmentation image must have '", "'the same shape'", ")", "if", "labels", "is", "None", ":", "labels", "=", "segment_img", ".", "labels", "labels", "=", "np", ".", "atleast_1d", "(", "labels", ")", "segment_img", ".", "check_labels", "(", "labels", ")", "data", "=", "filter_data", "(", "data", ",", "filter_kernel", ",", "mode", "=", "'constant'", ",", "fill_value", "=", "0.0", ")", "last_label", "=", "segment_img", ".", "max_label", "segm_deblended", "=", "deepcopy", "(", "segment_img", ")", "for", "label", "in", "labels", ":", "source_slice", "=", "segment_img", ".", "slices", "[", "segment_img", ".", "get_index", "(", "label", ")", "]", "source_data", "=", "data", "[", "source_slice", "]", "source_segm", "=", "SegmentationImage", "(", "np", ".", "copy", "(", "segment_img", ".", "data", "[", "source_slice", "]", ")", ")", "source_segm", ".", "keep_labels", "(", "label", ")", "# include only one label", "source_deblended", "=", "_deblend_source", "(", "source_data", ",", "source_segm", ",", "npixels", ",", "nlevels", "=", "nlevels", ",", "contrast", "=", "contrast", ",", "mode", "=", "mode", ",", "connectivity", "=", "connectivity", ")", "if", "not", "np", ".", "array_equal", "(", "source_deblended", ".", "data", ".", "astype", "(", "bool", ")", ",", "source_segm", ".", "data", ".", "astype", "(", "bool", ")", ")", ":", "raise", "ValueError", "(", "'Deblending failed for source \"{0}\". Please '", "'ensure you used the same pixel connectivity '", "'in detect_sources and deblend_sources. If '", "'this issue persists, then please inform the '", "'developers.'", ".", "format", "(", "label", ")", ")", "if", "source_deblended", ".", "nlabels", ">", "1", ":", "# replace the original source with the deblended source", "source_mask", "=", "(", "source_deblended", ".", "data", ">", "0", ")", "segm_tmp", "=", "segm_deblended", ".", "data", "segm_tmp", "[", "source_slice", "]", "[", "source_mask", "]", "=", "(", "source_deblended", ".", "data", "[", "source_mask", "]", "+", "last_label", ")", "segm_deblended", ".", "data", "=", "segm_tmp", "# needed to call data setter", "last_label", "+=", "source_deblended", ".", "nlabels", "if", "relabel", ":", "segm_deblended", ".", "relabel_consecutive", "(", ")", "return", "segm_deblended" ]
Deblend overlapping sources labeled in a segmentation image. Sources are deblended using a combination of multi-thresholding and `watershed segmentation <https://en.wikipedia.org/wiki/Watershed_(image_processing)>`_. In order to deblend sources, they must be separated enough such that there is a saddle between them. Parameters ---------- data : array_like The 2D array of the image. segment_img : `~photutils.segmentation.SegmentationImage` or array_like (int) A 2D segmentation image, either as a `~photutils.segmentation.SegmentationImage` object or an `~numpy.ndarray`, with the same shape as ``data`` where sources are labeled by different positive integer values. A value of zero is reserved for the background. npixels : int The number of connected pixels, each greater than ``threshold``, that an object must have to be detected. ``npixels`` must be a positive integer. filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional The 2D array of the kernel used to filter the image before thresholding. Filtering the image will smooth the noise and maximize detectability of objects with a shape similar to the kernel. labels : int or array-like of int, optional The label numbers to deblend. If `None` (default), then all labels in the segmentation image will be deblended. nlevels : int, optional The number of multi-thresholding levels to use. Each source will be re-thresholded at ``nlevels``, spaced exponentially or linearly (see the ``mode`` keyword), between its minimum and maximum values within the source segment. contrast : float, optional The fraction of the total (blended) source flux that a local peak must have to be considered as a separate object. ``contrast`` must be between 0 and 1, inclusive. If ``contrast = 0`` then every local peak will be made a separate object (maximum deblending). If ``contrast = 1`` then no deblending will occur. The default is 0.001, which will deblend sources with a magnitude difference of about 7.5. mode : {'exponential', 'linear'}, optional The mode used in defining the spacing between the multi-thresholding levels (see the ``nlevels`` keyword). The default is 'exponential'. connectivity : {8, 4}, optional The type of pixel connectivity used in determining how pixels are grouped into a detected source. The options are 8 (default) or 4. 8-connected pixels touch along their edges or corners. 4-connected pixels touch along their edges. For reference, SExtractor uses 8-connected pixels. relabel : bool If `True` (default), then the segmentation image will be relabeled such that the labels are in consecutive order starting from 1. Returns ------- segment_image : `~photutils.segmentation.SegmentationImage` A 2D segmentation image, with the same shape as ``data``, where sources are marked by different positive integer values. A value of zero is reserved for the background. See Also -------- :func:`photutils.detect_sources`
[ "Deblend", "overlapping", "sources", "labeled", "in", "a", "segmentation", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/deblend.py#L18-L147
train
astropy/photutils
photutils/utils/_moments.py
_moments_central
def _moments_central(data, center=None, order=1): """ Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it will calculated as the "center of mass" of the input ``data``. order : int, optional The maximum order of the moments to calculate. Returns ------- moments : 2D `~numpy.ndarray` The central image moments. """ data = np.asarray(data).astype(float) if data.ndim != 2: raise ValueError('data must be a 2D array.') if center is None: from ..centroids import centroid_com center = centroid_com(data) indices = np.ogrid[[slice(0, i) for i in data.shape]] ypowers = (indices[0] - center[1]) ** np.arange(order + 1) xpowers = np.transpose(indices[1] - center[0]) ** np.arange(order + 1) return np.dot(np.dot(np.transpose(ypowers), data), xpowers)
python
def _moments_central(data, center=None, order=1): """ Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it will calculated as the "center of mass" of the input ``data``. order : int, optional The maximum order of the moments to calculate. Returns ------- moments : 2D `~numpy.ndarray` The central image moments. """ data = np.asarray(data).astype(float) if data.ndim != 2: raise ValueError('data must be a 2D array.') if center is None: from ..centroids import centroid_com center = centroid_com(data) indices = np.ogrid[[slice(0, i) for i in data.shape]] ypowers = (indices[0] - center[1]) ** np.arange(order + 1) xpowers = np.transpose(indices[1] - center[0]) ** np.arange(order + 1) return np.dot(np.dot(np.transpose(ypowers), data), xpowers)
[ "def", "_moments_central", "(", "data", ",", "center", "=", "None", ",", "order", "=", "1", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", ".", "astype", "(", "float", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'data must be a 2D array.'", ")", "if", "center", "is", "None", ":", "from", ".", ".", "centroids", "import", "centroid_com", "center", "=", "centroid_com", "(", "data", ")", "indices", "=", "np", ".", "ogrid", "[", "[", "slice", "(", "0", ",", "i", ")", "for", "i", "in", "data", ".", "shape", "]", "]", "ypowers", "=", "(", "indices", "[", "0", "]", "-", "center", "[", "1", "]", ")", "**", "np", ".", "arange", "(", "order", "+", "1", ")", "xpowers", "=", "np", ".", "transpose", "(", "indices", "[", "1", "]", "-", "center", "[", "0", "]", ")", "**", "np", ".", "arange", "(", "order", "+", "1", ")", "return", "np", ".", "dot", "(", "np", ".", "dot", "(", "np", ".", "transpose", "(", "ypowers", ")", ",", "data", ")", ",", "xpowers", ")" ]
Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it will calculated as the "center of mass" of the input ``data``. order : int, optional The maximum order of the moments to calculate. Returns ------- moments : 2D `~numpy.ndarray` The central image moments.
[ "Calculate", "the", "central", "image", "moments", "up", "to", "the", "specified", "order", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/_moments.py#L9-L44
train
astropy/photutils
photutils/isophote/harmonics.py
first_and_second_harmonic_function
def first_and_second_harmonic_function(phi, c): """ Compute the harmonic function value used to calculate the corrections for ellipse fitting. This function includes simultaneously both the first and second order harmonics: .. math:: f(phi) = c[0] + c[1]*\\sin(phi) + c[2]*\\cos(phi) + c[3]*\\sin(2*phi) + c[4]*\\cos(2*phi) Parameters ---------- phi : float or `~numpy.ndarray` The angle(s) along the elliptical path, going towards the positive y axis, starting coincident with the position angle. That is, the angles are defined from the semimajor axis that lies in the positive x quadrant. c : `~numpy.ndarray` of shape (5,) Array containing the five harmonic coefficients. Returns ------- result : float or `~numpy.ndarray` The function value(s) at the given input angle(s). """ return (c[0] + c[1]*np.sin(phi) + c[2]*np.cos(phi) + c[3]*np.sin(2*phi) + c[4]*np.cos(2*phi))
python
def first_and_second_harmonic_function(phi, c): """ Compute the harmonic function value used to calculate the corrections for ellipse fitting. This function includes simultaneously both the first and second order harmonics: .. math:: f(phi) = c[0] + c[1]*\\sin(phi) + c[2]*\\cos(phi) + c[3]*\\sin(2*phi) + c[4]*\\cos(2*phi) Parameters ---------- phi : float or `~numpy.ndarray` The angle(s) along the elliptical path, going towards the positive y axis, starting coincident with the position angle. That is, the angles are defined from the semimajor axis that lies in the positive x quadrant. c : `~numpy.ndarray` of shape (5,) Array containing the five harmonic coefficients. Returns ------- result : float or `~numpy.ndarray` The function value(s) at the given input angle(s). """ return (c[0] + c[1]*np.sin(phi) + c[2]*np.cos(phi) + c[3]*np.sin(2*phi) + c[4]*np.cos(2*phi))
[ "def", "first_and_second_harmonic_function", "(", "phi", ",", "c", ")", ":", "return", "(", "c", "[", "0", "]", "+", "c", "[", "1", "]", "*", "np", ".", "sin", "(", "phi", ")", "+", "c", "[", "2", "]", "*", "np", ".", "cos", "(", "phi", ")", "+", "c", "[", "3", "]", "*", "np", ".", "sin", "(", "2", "*", "phi", ")", "+", "c", "[", "4", "]", "*", "np", ".", "cos", "(", "2", "*", "phi", ")", ")" ]
Compute the harmonic function value used to calculate the corrections for ellipse fitting. This function includes simultaneously both the first and second order harmonics: .. math:: f(phi) = c[0] + c[1]*\\sin(phi) + c[2]*\\cos(phi) + c[3]*\\sin(2*phi) + c[4]*\\cos(2*phi) Parameters ---------- phi : float or `~numpy.ndarray` The angle(s) along the elliptical path, going towards the positive y axis, starting coincident with the position angle. That is, the angles are defined from the semimajor axis that lies in the positive x quadrant. c : `~numpy.ndarray` of shape (5,) Array containing the five harmonic coefficients. Returns ------- result : float or `~numpy.ndarray` The function value(s) at the given input angle(s).
[ "Compute", "the", "harmonic", "function", "value", "used", "to", "calculate", "the", "corrections", "for", "ellipse", "fitting", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/harmonics.py#L23-L53
train
astropy/photutils
photutils/psf/matching/windows.py
_radial_distance
def _radial_distance(shape): """ Return an array where each value is the Euclidean distance from the array center. Parameters ---------- shape : tuple of int The size of the output array along each axis. Returns ------- result : `~numpy.ndarray` An array containing the Euclidian radial distances from the array center. """ if len(shape) != 2: raise ValueError('shape must have only 2 elements') position = (np.asarray(shape) - 1) / 2. x = np.arange(shape[1]) - position[1] y = np.arange(shape[0]) - position[0] xx, yy = np.meshgrid(x, y) return np.sqrt(xx**2 + yy**2)
python
def _radial_distance(shape): """ Return an array where each value is the Euclidean distance from the array center. Parameters ---------- shape : tuple of int The size of the output array along each axis. Returns ------- result : `~numpy.ndarray` An array containing the Euclidian radial distances from the array center. """ if len(shape) != 2: raise ValueError('shape must have only 2 elements') position = (np.asarray(shape) - 1) / 2. x = np.arange(shape[1]) - position[1] y = np.arange(shape[0]) - position[0] xx, yy = np.meshgrid(x, y) return np.sqrt(xx**2 + yy**2)
[ "def", "_radial_distance", "(", "shape", ")", ":", "if", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'shape must have only 2 elements'", ")", "position", "=", "(", "np", ".", "asarray", "(", "shape", ")", "-", "1", ")", "/", "2.", "x", "=", "np", ".", "arange", "(", "shape", "[", "1", "]", ")", "-", "position", "[", "1", "]", "y", "=", "np", ".", "arange", "(", "shape", "[", "0", "]", ")", "-", "position", "[", "0", "]", "xx", ",", "yy", "=", "np", ".", "meshgrid", "(", "x", ",", "y", ")", "return", "np", ".", "sqrt", "(", "xx", "**", "2", "+", "yy", "**", "2", ")" ]
Return an array where each value is the Euclidean distance from the array center. Parameters ---------- shape : tuple of int The size of the output array along each axis. Returns ------- result : `~numpy.ndarray` An array containing the Euclidian radial distances from the array center.
[ "Return", "an", "array", "where", "each", "value", "is", "the", "Euclidean", "distance", "from", "the", "array", "center", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/matching/windows.py#L13-L36
train
astropy/photutils
photutils/datasets/load.py
load_spitzer_image
def load_spitzer_image(show_progress=False): # pragma: no cover """ Load a 4.5 micron Spitzer image. The catalog for this image is returned by :func:`load_spitzer_catalog`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The 4.5 micron Spitzer image in a FITS image HDU. See Also -------- load_spitzer_catalog Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_spitzer_image() plt.imshow(hdu.data, origin='lower', vmax=50) """ path = get_path('spitzer_example_image.fits', location='remote', show_progress=show_progress) hdu = fits.open(path)[0] return hdu
python
def load_spitzer_image(show_progress=False): # pragma: no cover """ Load a 4.5 micron Spitzer image. The catalog for this image is returned by :func:`load_spitzer_catalog`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The 4.5 micron Spitzer image in a FITS image HDU. See Also -------- load_spitzer_catalog Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_spitzer_image() plt.imshow(hdu.data, origin='lower', vmax=50) """ path = get_path('spitzer_example_image.fits', location='remote', show_progress=show_progress) hdu = fits.open(path)[0] return hdu
[ "def", "load_spitzer_image", "(", "show_progress", "=", "False", ")", ":", "# pragma: no cover", "path", "=", "get_path", "(", "'spitzer_example_image.fits'", ",", "location", "=", "'remote'", ",", "show_progress", "=", "show_progress", ")", "hdu", "=", "fits", ".", "open", "(", "path", ")", "[", "0", "]", "return", "hdu" ]
Load a 4.5 micron Spitzer image. The catalog for this image is returned by :func:`load_spitzer_catalog`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The 4.5 micron Spitzer image in a FITS image HDU. See Also -------- load_spitzer_catalog Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_spitzer_image() plt.imshow(hdu.data, origin='lower', vmax=50)
[ "Load", "a", "4", ".", "5", "micron", "Spitzer", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/load.py#L73-L109
train
astropy/photutils
photutils/datasets/load.py
load_spitzer_catalog
def load_spitzer_catalog(show_progress=False): # pragma: no cover """ Load a 4.5 micron Spitzer catalog. The image from which this catalog was derived is returned by :func:`load_spitzer_image`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- catalog : `~astropy.table.Table` The catalog of sources. See Also -------- load_spitzer_image Examples -------- .. plot:: :include-source: from photutils import datasets catalog = datasets.load_spitzer_catalog() plt.scatter(catalog['l'], catalog['b']) plt.xlabel('Galactic l') plt.ylabel('Galactic b') plt.xlim(18.39, 18.05) plt.ylim(0.13, 0.30) """ path = get_path('spitzer_example_catalog.xml', location='remote', show_progress=show_progress) table = Table.read(path) return table
python
def load_spitzer_catalog(show_progress=False): # pragma: no cover """ Load a 4.5 micron Spitzer catalog. The image from which this catalog was derived is returned by :func:`load_spitzer_image`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- catalog : `~astropy.table.Table` The catalog of sources. See Also -------- load_spitzer_image Examples -------- .. plot:: :include-source: from photutils import datasets catalog = datasets.load_spitzer_catalog() plt.scatter(catalog['l'], catalog['b']) plt.xlabel('Galactic l') plt.ylabel('Galactic b') plt.xlim(18.39, 18.05) plt.ylim(0.13, 0.30) """ path = get_path('spitzer_example_catalog.xml', location='remote', show_progress=show_progress) table = Table.read(path) return table
[ "def", "load_spitzer_catalog", "(", "show_progress", "=", "False", ")", ":", "# pragma: no cover", "path", "=", "get_path", "(", "'spitzer_example_catalog.xml'", ",", "location", "=", "'remote'", ",", "show_progress", "=", "show_progress", ")", "table", "=", "Table", ".", "read", "(", "path", ")", "return", "table" ]
Load a 4.5 micron Spitzer catalog. The image from which this catalog was derived is returned by :func:`load_spitzer_image`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- catalog : `~astropy.table.Table` The catalog of sources. See Also -------- load_spitzer_image Examples -------- .. plot:: :include-source: from photutils import datasets catalog = datasets.load_spitzer_catalog() plt.scatter(catalog['l'], catalog['b']) plt.xlabel('Galactic l') plt.ylabel('Galactic b') plt.xlim(18.39, 18.05) plt.ylim(0.13, 0.30)
[ "Load", "a", "4", ".", "5", "micron", "Spitzer", "catalog", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/load.py#L112-L152
train
astropy/photutils
photutils/datasets/load.py
load_irac_psf
def load_irac_psf(channel, show_progress=False): # pragma: no cover """ Load a Spitzer IRAC PSF image. Parameters ---------- channel : int (1-4) The IRAC channel number: * Channel 1: 3.6 microns * Channel 2: 4.5 microns * Channel 3: 5.8 microns * Channel 4: 8.0 microns show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The IRAC PSF in a FITS image HDU. Examples -------- .. plot:: :include-source: from astropy.visualization import LogStretch, ImageNormalize from photutils.datasets import load_irac_psf hdu1 = load_irac_psf(1) hdu2 = load_irac_psf(2) hdu3 = load_irac_psf(3) hdu4 = load_irac_psf(4) norm = ImageNormalize(hdu1.data, stretch=LogStretch()) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.imshow(hdu1.data, origin='lower', interpolation='nearest', norm=norm) ax1.set_title('IRAC Ch1 PSF') ax2.imshow(hdu2.data, origin='lower', interpolation='nearest', norm=norm) ax2.set_title('IRAC Ch2 PSF') ax3.imshow(hdu3.data, origin='lower', interpolation='nearest', norm=norm) ax3.set_title('IRAC Ch3 PSF') ax4.imshow(hdu4.data, origin='lower', interpolation='nearest', norm=norm) ax4.set_title('IRAC Ch4 PSF') plt.tight_layout() plt.show() """ channel = int(channel) if channel < 1 or channel > 4: raise ValueError('channel must be 1, 2, 3, or 4') fn = 'irac_ch{0}_flight.fits'.format(channel) path = get_path(fn, location='remote', show_progress=show_progress) hdu = fits.open(path)[0] return hdu
python
def load_irac_psf(channel, show_progress=False): # pragma: no cover """ Load a Spitzer IRAC PSF image. Parameters ---------- channel : int (1-4) The IRAC channel number: * Channel 1: 3.6 microns * Channel 2: 4.5 microns * Channel 3: 5.8 microns * Channel 4: 8.0 microns show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The IRAC PSF in a FITS image HDU. Examples -------- .. plot:: :include-source: from astropy.visualization import LogStretch, ImageNormalize from photutils.datasets import load_irac_psf hdu1 = load_irac_psf(1) hdu2 = load_irac_psf(2) hdu3 = load_irac_psf(3) hdu4 = load_irac_psf(4) norm = ImageNormalize(hdu1.data, stretch=LogStretch()) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.imshow(hdu1.data, origin='lower', interpolation='nearest', norm=norm) ax1.set_title('IRAC Ch1 PSF') ax2.imshow(hdu2.data, origin='lower', interpolation='nearest', norm=norm) ax2.set_title('IRAC Ch2 PSF') ax3.imshow(hdu3.data, origin='lower', interpolation='nearest', norm=norm) ax3.set_title('IRAC Ch3 PSF') ax4.imshow(hdu4.data, origin='lower', interpolation='nearest', norm=norm) ax4.set_title('IRAC Ch4 PSF') plt.tight_layout() plt.show() """ channel = int(channel) if channel < 1 or channel > 4: raise ValueError('channel must be 1, 2, 3, or 4') fn = 'irac_ch{0}_flight.fits'.format(channel) path = get_path(fn, location='remote', show_progress=show_progress) hdu = fits.open(path)[0] return hdu
[ "def", "load_irac_psf", "(", "channel", ",", "show_progress", "=", "False", ")", ":", "# pragma: no cover", "channel", "=", "int", "(", "channel", ")", "if", "channel", "<", "1", "or", "channel", ">", "4", ":", "raise", "ValueError", "(", "'channel must be 1, 2, 3, or 4'", ")", "fn", "=", "'irac_ch{0}_flight.fits'", ".", "format", "(", "channel", ")", "path", "=", "get_path", "(", "fn", ",", "location", "=", "'remote'", ",", "show_progress", "=", "show_progress", ")", "hdu", "=", "fits", ".", "open", "(", "path", ")", "[", "0", "]", "return", "hdu" ]
Load a Spitzer IRAC PSF image. Parameters ---------- channel : int (1-4) The IRAC channel number: * Channel 1: 3.6 microns * Channel 2: 4.5 microns * Channel 3: 5.8 microns * Channel 4: 8.0 microns show_progress : bool, optional Whether to display a progress bar during the download (default is `False`). Returns ------- hdu : `~astropy.io.fits.ImageHDU` The IRAC PSF in a FITS image HDU. Examples -------- .. plot:: :include-source: from astropy.visualization import LogStretch, ImageNormalize from photutils.datasets import load_irac_psf hdu1 = load_irac_psf(1) hdu2 = load_irac_psf(2) hdu3 = load_irac_psf(3) hdu4 = load_irac_psf(4) norm = ImageNormalize(hdu1.data, stretch=LogStretch()) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.imshow(hdu1.data, origin='lower', interpolation='nearest', norm=norm) ax1.set_title('IRAC Ch1 PSF') ax2.imshow(hdu2.data, origin='lower', interpolation='nearest', norm=norm) ax2.set_title('IRAC Ch2 PSF') ax3.imshow(hdu3.data, origin='lower', interpolation='nearest', norm=norm) ax3.set_title('IRAC Ch3 PSF') ax4.imshow(hdu4.data, origin='lower', interpolation='nearest', norm=norm) ax4.set_title('IRAC Ch4 PSF') plt.tight_layout() plt.show()
[ "Load", "a", "Spitzer", "IRAC", "PSF", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/load.py#L155-L217
train
astropy/photutils
photutils/isophote/ellipse.py
Ellipse.fit_image
def fit_image(self, sma0=None, minsma=0., maxsma=None, step=0.1, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, sclip=3., nclip=0, integrmode=BILINEAR, linear=False, maxrit=None): # This parameter list is quite large and should in principle be # simplified by re-distributing these controls to somewhere else. # We keep this design though because it better mimics the flat # architecture used in the original STSDAS task `ellipse`. """ Fit multiple isophotes to the image array. This method loops over each value of the semimajor axis (sma) length (constructed from the input parameters), fitting a single isophote at each sma. The entire set of isophotes is returned in an `~photutils.isophote.IsophoteList` instance. Parameters ---------- sma0 : float, optional The starting value for the semimajor axis length (pixels). This value must not be the minimum or maximum semimajor axis length, but something in between. The algorithm can't start from the very center of the galaxy image because the modelling of elliptical isophotes on that region is poor and it will diverge very easily if not tied to other previously fit isophotes. It can't start from the maximum value either because the maximum is not known beforehand, depending on signal-to-noise. The ``sma0`` value should be selected such that the corresponding isophote has a good signal-to-noise ratio and a clearly defined geometry. If set to `None` (the default), one of two actions will be taken: if a `~photutils.isophote.EllipseGeometry` instance was input to the `~photutils.isophote.Ellipse` constructor, its ``sma`` value will be used. Otherwise, a default value of 10. will be used. minsma : float, optional The minimum value for the semimajor axis length (pixels). The default is 0. maxsma : float or `None`, optional The maximum value for the semimajor axis length (pixels). When set to `None` (default), the algorithm will increase the semimajor axis until one of several conditions will cause it to stop and revert to fit ellipses with sma < ``sma0``. step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. If `False` (default), the geometric growing mode is chosen, thus the semimajor axis length is increased by a factor of (1. + ``step``), and the process is repeated until either the semimajor axis value reaches the value of parameter ``maxsma``, or the last fitted ellipse has more than a given fraction of its sampled points flagged out (see ``fflag``). The process then resumes from the first fitted ellipse (at ``sma0``) inwards, in steps of (1./(1. + ``step``)), until the semimajor axis length reaches the value ``minsma``. In case of linear growing, the increment or decrement value is given directly by ``step`` in pixels. If ``maxsma`` is set to `None`, the semimajor axis will grow until a low signal-to-noise criterion is met. See ``maxgerr``. maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. Returns ------- result : `~photutils.isophote.IsophoteList` instance A list-like object of `~photutils.isophote.Isophote` instances, sorted by increasing semimajor axis length. """ # multiple fitted isophotes will be stored here isophote_list = [] # get starting sma from appropriate source: keyword parameter, # internal EllipseGeometry instance, or fixed default value. if not sma0: if self._geometry: sma = self._geometry.sma else: sma = 10. else: sma = sma0 # first, go from initial sma outwards until # hitting one of several stopping criteria. noiter = False first_isophote = True while True: # first isophote runs longer minit_a = 2 * minit if first_isophote else minit first_isophote = False isophote = self.fit_isophote(sma, step, conver, minit_a, maxit, fflag, maxgerr, sclip, nclip, integrmode, linear, maxrit, noniterate=noiter, isophote_list=isophote_list) # check for failed fit. if (isophote.stop_code < 0 or isophote.stop_code == 1): # in case the fit failed right at the outset, return an # empty list. This is the usual case when the user # provides initial guesses that are too way off to enable # the fitting algorithm to find any meaningful solution. if len(isophote_list) == 1: warnings.warn('No meaningful fit was possible.', AstropyUserWarning) return IsophoteList([]) self._fix_last_isophote(isophote_list, -1) # get last isophote from the actual list, since the last # `isophote` instance in this context may no longer be OK. isophote = isophote_list[-1] # if two consecutive isophotes failed to fit, # shut off iterative mode. Or, bail out and # change to go inwards. if len(isophote_list) > 2: if ((isophote.stop_code == 5 and isophote_list[-2].stop_code == 5) or isophote.stop_code == 1): if maxsma and maxsma > isophote.sma: # if a maximum sma value was provided by # user, and the current sma is smaller than # maxsma, keep growing sma in non-iterative # mode until reaching it. noiter = True else: # if no maximum sma, stop growing and change # to go inwards. break # reset variable from the actual list, since the last # `isophote` instance may no longer be OK. isophote = isophote_list[-1] # update sma. If exceeded user-defined # maximum, bail out from this loop. sma = isophote.sample.geometry.update_sma(step) if maxsma and sma >= maxsma: break # reset sma so as to go inwards. first_isophote = isophote_list[0] sma, step = first_isophote.sample.geometry.reset_sma(step) # now, go from initial sma inwards towards center. while True: isophote = self.fit_isophote(sma, step, conver, minit, maxit, fflag, maxgerr, sclip, nclip, integrmode, linear, maxrit, going_inwards=True, isophote_list=isophote_list) # if abnormal condition, fix isophote but keep going. if isophote.stop_code < 0: self._fix_last_isophote(isophote_list, 0) # reset variable from the actual list, since the last # `isophote` instance may no longer be OK. isophote = isophote_list[-1] # figure out next sma; if exceeded user-defined # minimum, or too small, bail out from this loop sma = isophote.sample.geometry.update_sma(step) if sma <= max(minsma, 0.5): break # if user asked for minsma=0, extract special isophote there if minsma == 0.0: isophote = self.fit_isophote(0.0, isophote_list=isophote_list) # sort list of isophotes according to sma isophote_list.sort() return IsophoteList(isophote_list)
python
def fit_image(self, sma0=None, minsma=0., maxsma=None, step=0.1, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, sclip=3., nclip=0, integrmode=BILINEAR, linear=False, maxrit=None): # This parameter list is quite large and should in principle be # simplified by re-distributing these controls to somewhere else. # We keep this design though because it better mimics the flat # architecture used in the original STSDAS task `ellipse`. """ Fit multiple isophotes to the image array. This method loops over each value of the semimajor axis (sma) length (constructed from the input parameters), fitting a single isophote at each sma. The entire set of isophotes is returned in an `~photutils.isophote.IsophoteList` instance. Parameters ---------- sma0 : float, optional The starting value for the semimajor axis length (pixels). This value must not be the minimum or maximum semimajor axis length, but something in between. The algorithm can't start from the very center of the galaxy image because the modelling of elliptical isophotes on that region is poor and it will diverge very easily if not tied to other previously fit isophotes. It can't start from the maximum value either because the maximum is not known beforehand, depending on signal-to-noise. The ``sma0`` value should be selected such that the corresponding isophote has a good signal-to-noise ratio and a clearly defined geometry. If set to `None` (the default), one of two actions will be taken: if a `~photutils.isophote.EllipseGeometry` instance was input to the `~photutils.isophote.Ellipse` constructor, its ``sma`` value will be used. Otherwise, a default value of 10. will be used. minsma : float, optional The minimum value for the semimajor axis length (pixels). The default is 0. maxsma : float or `None`, optional The maximum value for the semimajor axis length (pixels). When set to `None` (default), the algorithm will increase the semimajor axis until one of several conditions will cause it to stop and revert to fit ellipses with sma < ``sma0``. step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. If `False` (default), the geometric growing mode is chosen, thus the semimajor axis length is increased by a factor of (1. + ``step``), and the process is repeated until either the semimajor axis value reaches the value of parameter ``maxsma``, or the last fitted ellipse has more than a given fraction of its sampled points flagged out (see ``fflag``). The process then resumes from the first fitted ellipse (at ``sma0``) inwards, in steps of (1./(1. + ``step``)), until the semimajor axis length reaches the value ``minsma``. In case of linear growing, the increment or decrement value is given directly by ``step`` in pixels. If ``maxsma`` is set to `None`, the semimajor axis will grow until a low signal-to-noise criterion is met. See ``maxgerr``. maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. Returns ------- result : `~photutils.isophote.IsophoteList` instance A list-like object of `~photutils.isophote.Isophote` instances, sorted by increasing semimajor axis length. """ # multiple fitted isophotes will be stored here isophote_list = [] # get starting sma from appropriate source: keyword parameter, # internal EllipseGeometry instance, or fixed default value. if not sma0: if self._geometry: sma = self._geometry.sma else: sma = 10. else: sma = sma0 # first, go from initial sma outwards until # hitting one of several stopping criteria. noiter = False first_isophote = True while True: # first isophote runs longer minit_a = 2 * minit if first_isophote else minit first_isophote = False isophote = self.fit_isophote(sma, step, conver, minit_a, maxit, fflag, maxgerr, sclip, nclip, integrmode, linear, maxrit, noniterate=noiter, isophote_list=isophote_list) # check for failed fit. if (isophote.stop_code < 0 or isophote.stop_code == 1): # in case the fit failed right at the outset, return an # empty list. This is the usual case when the user # provides initial guesses that are too way off to enable # the fitting algorithm to find any meaningful solution. if len(isophote_list) == 1: warnings.warn('No meaningful fit was possible.', AstropyUserWarning) return IsophoteList([]) self._fix_last_isophote(isophote_list, -1) # get last isophote from the actual list, since the last # `isophote` instance in this context may no longer be OK. isophote = isophote_list[-1] # if two consecutive isophotes failed to fit, # shut off iterative mode. Or, bail out and # change to go inwards. if len(isophote_list) > 2: if ((isophote.stop_code == 5 and isophote_list[-2].stop_code == 5) or isophote.stop_code == 1): if maxsma and maxsma > isophote.sma: # if a maximum sma value was provided by # user, and the current sma is smaller than # maxsma, keep growing sma in non-iterative # mode until reaching it. noiter = True else: # if no maximum sma, stop growing and change # to go inwards. break # reset variable from the actual list, since the last # `isophote` instance may no longer be OK. isophote = isophote_list[-1] # update sma. If exceeded user-defined # maximum, bail out from this loop. sma = isophote.sample.geometry.update_sma(step) if maxsma and sma >= maxsma: break # reset sma so as to go inwards. first_isophote = isophote_list[0] sma, step = first_isophote.sample.geometry.reset_sma(step) # now, go from initial sma inwards towards center. while True: isophote = self.fit_isophote(sma, step, conver, minit, maxit, fflag, maxgerr, sclip, nclip, integrmode, linear, maxrit, going_inwards=True, isophote_list=isophote_list) # if abnormal condition, fix isophote but keep going. if isophote.stop_code < 0: self._fix_last_isophote(isophote_list, 0) # reset variable from the actual list, since the last # `isophote` instance may no longer be OK. isophote = isophote_list[-1] # figure out next sma; if exceeded user-defined # minimum, or too small, bail out from this loop sma = isophote.sample.geometry.update_sma(step) if sma <= max(minsma, 0.5): break # if user asked for minsma=0, extract special isophote there if minsma == 0.0: isophote = self.fit_isophote(0.0, isophote_list=isophote_list) # sort list of isophotes according to sma isophote_list.sort() return IsophoteList(isophote_list)
[ "def", "fit_image", "(", "self", ",", "sma0", "=", "None", ",", "minsma", "=", "0.", ",", "maxsma", "=", "None", ",", "step", "=", "0.1", ",", "conver", "=", "DEFAULT_CONVERGENCE", ",", "minit", "=", "DEFAULT_MINIT", ",", "maxit", "=", "DEFAULT_MAXIT", ",", "fflag", "=", "DEFAULT_FFLAG", ",", "maxgerr", "=", "DEFAULT_MAXGERR", ",", "sclip", "=", "3.", ",", "nclip", "=", "0", ",", "integrmode", "=", "BILINEAR", ",", "linear", "=", "False", ",", "maxrit", "=", "None", ")", ":", "# This parameter list is quite large and should in principle be", "# simplified by re-distributing these controls to somewhere else.", "# We keep this design though because it better mimics the flat", "# architecture used in the original STSDAS task `ellipse`.", "# multiple fitted isophotes will be stored here", "isophote_list", "=", "[", "]", "# get starting sma from appropriate source: keyword parameter,", "# internal EllipseGeometry instance, or fixed default value.", "if", "not", "sma0", ":", "if", "self", ".", "_geometry", ":", "sma", "=", "self", ".", "_geometry", ".", "sma", "else", ":", "sma", "=", "10.", "else", ":", "sma", "=", "sma0", "# first, go from initial sma outwards until", "# hitting one of several stopping criteria.", "noiter", "=", "False", "first_isophote", "=", "True", "while", "True", ":", "# first isophote runs longer", "minit_a", "=", "2", "*", "minit", "if", "first_isophote", "else", "minit", "first_isophote", "=", "False", "isophote", "=", "self", ".", "fit_isophote", "(", "sma", ",", "step", ",", "conver", ",", "minit_a", ",", "maxit", ",", "fflag", ",", "maxgerr", ",", "sclip", ",", "nclip", ",", "integrmode", ",", "linear", ",", "maxrit", ",", "noniterate", "=", "noiter", ",", "isophote_list", "=", "isophote_list", ")", "# check for failed fit.", "if", "(", "isophote", ".", "stop_code", "<", "0", "or", "isophote", ".", "stop_code", "==", "1", ")", ":", "# in case the fit failed right at the outset, return an", "# empty list. This is the usual case when the user", "# provides initial guesses that are too way off to enable", "# the fitting algorithm to find any meaningful solution.", "if", "len", "(", "isophote_list", ")", "==", "1", ":", "warnings", ".", "warn", "(", "'No meaningful fit was possible.'", ",", "AstropyUserWarning", ")", "return", "IsophoteList", "(", "[", "]", ")", "self", ".", "_fix_last_isophote", "(", "isophote_list", ",", "-", "1", ")", "# get last isophote from the actual list, since the last", "# `isophote` instance in this context may no longer be OK.", "isophote", "=", "isophote_list", "[", "-", "1", "]", "# if two consecutive isophotes failed to fit,", "# shut off iterative mode. Or, bail out and", "# change to go inwards.", "if", "len", "(", "isophote_list", ")", ">", "2", ":", "if", "(", "(", "isophote", ".", "stop_code", "==", "5", "and", "isophote_list", "[", "-", "2", "]", ".", "stop_code", "==", "5", ")", "or", "isophote", ".", "stop_code", "==", "1", ")", ":", "if", "maxsma", "and", "maxsma", ">", "isophote", ".", "sma", ":", "# if a maximum sma value was provided by", "# user, and the current sma is smaller than", "# maxsma, keep growing sma in non-iterative", "# mode until reaching it.", "noiter", "=", "True", "else", ":", "# if no maximum sma, stop growing and change", "# to go inwards.", "break", "# reset variable from the actual list, since the last", "# `isophote` instance may no longer be OK.", "isophote", "=", "isophote_list", "[", "-", "1", "]", "# update sma. If exceeded user-defined", "# maximum, bail out from this loop.", "sma", "=", "isophote", ".", "sample", ".", "geometry", ".", "update_sma", "(", "step", ")", "if", "maxsma", "and", "sma", ">=", "maxsma", ":", "break", "# reset sma so as to go inwards.", "first_isophote", "=", "isophote_list", "[", "0", "]", "sma", ",", "step", "=", "first_isophote", ".", "sample", ".", "geometry", ".", "reset_sma", "(", "step", ")", "# now, go from initial sma inwards towards center.", "while", "True", ":", "isophote", "=", "self", ".", "fit_isophote", "(", "sma", ",", "step", ",", "conver", ",", "minit", ",", "maxit", ",", "fflag", ",", "maxgerr", ",", "sclip", ",", "nclip", ",", "integrmode", ",", "linear", ",", "maxrit", ",", "going_inwards", "=", "True", ",", "isophote_list", "=", "isophote_list", ")", "# if abnormal condition, fix isophote but keep going.", "if", "isophote", ".", "stop_code", "<", "0", ":", "self", ".", "_fix_last_isophote", "(", "isophote_list", ",", "0", ")", "# reset variable from the actual list, since the last", "# `isophote` instance may no longer be OK.", "isophote", "=", "isophote_list", "[", "-", "1", "]", "# figure out next sma; if exceeded user-defined", "# minimum, or too small, bail out from this loop", "sma", "=", "isophote", ".", "sample", ".", "geometry", ".", "update_sma", "(", "step", ")", "if", "sma", "<=", "max", "(", "minsma", ",", "0.5", ")", ":", "break", "# if user asked for minsma=0, extract special isophote there", "if", "minsma", "==", "0.0", ":", "isophote", "=", "self", ".", "fit_isophote", "(", "0.0", ",", "isophote_list", "=", "isophote_list", ")", "# sort list of isophotes according to sma", "isophote_list", ".", "sort", "(", ")", "return", "IsophoteList", "(", "isophote_list", ")" ]
Fit multiple isophotes to the image array. This method loops over each value of the semimajor axis (sma) length (constructed from the input parameters), fitting a single isophote at each sma. The entire set of isophotes is returned in an `~photutils.isophote.IsophoteList` instance. Parameters ---------- sma0 : float, optional The starting value for the semimajor axis length (pixels). This value must not be the minimum or maximum semimajor axis length, but something in between. The algorithm can't start from the very center of the galaxy image because the modelling of elliptical isophotes on that region is poor and it will diverge very easily if not tied to other previously fit isophotes. It can't start from the maximum value either because the maximum is not known beforehand, depending on signal-to-noise. The ``sma0`` value should be selected such that the corresponding isophote has a good signal-to-noise ratio and a clearly defined geometry. If set to `None` (the default), one of two actions will be taken: if a `~photutils.isophote.EllipseGeometry` instance was input to the `~photutils.isophote.Ellipse` constructor, its ``sma`` value will be used. Otherwise, a default value of 10. will be used. minsma : float, optional The minimum value for the semimajor axis length (pixels). The default is 0. maxsma : float or `None`, optional The maximum value for the semimajor axis length (pixels). When set to `None` (default), the algorithm will increase the semimajor axis until one of several conditions will cause it to stop and revert to fit ellipses with sma < ``sma0``. step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. This is the main control for preventing ellipses to grow to regions of too low signal-to-noise ratio. It specifies the maximum acceptable relative error in the local radial intensity gradient. `Busko (1996; ASPC 101, 139) <http://adsabs.harvard.edu/abs/1996ASPC..101..139B>`_ showed that the fitting precision relates to that relative error. The usual behavior of the gradient relative error is to increase with semimajor axis, being larger in outer, fainter regions of a galaxy image. In the current implementation, the ``maxgerr`` criterion is triggered only when two consecutive isophotes exceed the value specified by the parameter. This prevents premature stopping caused by contamination such as stars and HII regions. A number of actions may happen when the gradient error exceeds ``maxgerr`` (or becomes non-significant and is set to `None`). If the maximum semimajor axis specified by ``maxsma`` is set to `None`, semimajor axis growth is stopped and the algorithm proceeds inwards to the galaxy center. If ``maxsma`` is set to some finite value, and this value is larger than the current semimajor axis length, the algorithm enters non-iterative mode and proceeds outwards until reaching ``maxsma``. The default is 0.5. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. If `False` (default), the geometric growing mode is chosen, thus the semimajor axis length is increased by a factor of (1. + ``step``), and the process is repeated until either the semimajor axis value reaches the value of parameter ``maxsma``, or the last fitted ellipse has more than a given fraction of its sampled points flagged out (see ``fflag``). The process then resumes from the first fitted ellipse (at ``sma0``) inwards, in steps of (1./(1. + ``step``)), until the semimajor axis length reaches the value ``minsma``. In case of linear growing, the increment or decrement value is given directly by ``step`` in pixels. If ``maxsma`` is set to `None`, the semimajor axis will grow until a low signal-to-noise criterion is met. See ``maxgerr``. maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. Returns ------- result : `~photutils.isophote.IsophoteList` instance A list-like object of `~photutils.isophote.Isophote` instances, sorted by increasing semimajor axis length.
[ "Fit", "multiple", "isophotes", "to", "the", "image", "array", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/ellipse.py#L199-L449
train
astropy/photutils
photutils/isophote/ellipse.py
Ellipse.fit_isophote
def fit_isophote(self, sma, step=0.1, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, sclip=3., nclip=0, integrmode=BILINEAR, linear=False, maxrit=None, noniterate=False, going_inwards=False, isophote_list=None): """ Fit a single isophote with a given semimajor axis length. The ``step`` and ``linear`` parameters are not used to actually grow or shrink the current fitting semimajor axis length. They are necessary so the sampling algorithm can know where to start the gradient computation and also how to compute the elliptical sector areas (when area integration mode is selected). Parameters ---------- sma : float The semimajor axis length (pixels). step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. When fitting a single isophote by itself this paramter doesn't have any effect on the outcome. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. When fitting just one isophote, this parameter is used only by the code that define the details of how elliptical arc segments ("sectors") are extracted from the image when using area extraction modes (see the ``integrmode`` parameter). maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. noniterate : bool, optional Whether the fitting algorithm should be bypassed and an isophote should be extracted with the geometry taken directly from the most recent `~photutils.isophote.Isophote` instance stored in the ``isophote_list`` parameter. This parameter is mainly used when running the method in a loop over different values of semimajor axis length, and we want to change from iterative to non-iterative mode somewhere along the sequence of isophotes. When set to `True`, this parameter overrides the behavior associated with parameter ``maxrit``. The default is `False`. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter). The default is `False`. isophote_list : list or `None`, optional If not `None` (the default), the fitted `~photutils.isophote.Isophote` instance is appended to this list. It must be created and managed by the caller. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote. The fitted isophote is also appended to the input list input to the ``isophote_list`` parameter. """ geometry = self._geometry # if available, geometry from last fitted isophote will be # used as initial guess for next isophote. if isophote_list is not None and len(isophote_list) > 0: geometry = isophote_list[-1].sample.geometry # do the fit if noniterate or (maxrit and sma > maxrit): isophote = self._non_iterative(sma, step, linear, geometry, sclip, nclip, integrmode) else: isophote = self._iterative(sma, step, linear, geometry, sclip, nclip, integrmode, conver, minit, maxit, fflag, maxgerr, going_inwards) # store result in list if isophote_list is not None and isophote.valid: isophote_list.append(isophote) return isophote
python
def fit_isophote(self, sma, step=0.1, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, sclip=3., nclip=0, integrmode=BILINEAR, linear=False, maxrit=None, noniterate=False, going_inwards=False, isophote_list=None): """ Fit a single isophote with a given semimajor axis length. The ``step`` and ``linear`` parameters are not used to actually grow or shrink the current fitting semimajor axis length. They are necessary so the sampling algorithm can know where to start the gradient computation and also how to compute the elliptical sector areas (when area integration mode is selected). Parameters ---------- sma : float The semimajor axis length (pixels). step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. When fitting a single isophote by itself this paramter doesn't have any effect on the outcome. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. When fitting just one isophote, this parameter is used only by the code that define the details of how elliptical arc segments ("sectors") are extracted from the image when using area extraction modes (see the ``integrmode`` parameter). maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. noniterate : bool, optional Whether the fitting algorithm should be bypassed and an isophote should be extracted with the geometry taken directly from the most recent `~photutils.isophote.Isophote` instance stored in the ``isophote_list`` parameter. This parameter is mainly used when running the method in a loop over different values of semimajor axis length, and we want to change from iterative to non-iterative mode somewhere along the sequence of isophotes. When set to `True`, this parameter overrides the behavior associated with parameter ``maxrit``. The default is `False`. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter). The default is `False`. isophote_list : list or `None`, optional If not `None` (the default), the fitted `~photutils.isophote.Isophote` instance is appended to this list. It must be created and managed by the caller. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote. The fitted isophote is also appended to the input list input to the ``isophote_list`` parameter. """ geometry = self._geometry # if available, geometry from last fitted isophote will be # used as initial guess for next isophote. if isophote_list is not None and len(isophote_list) > 0: geometry = isophote_list[-1].sample.geometry # do the fit if noniterate or (maxrit and sma > maxrit): isophote = self._non_iterative(sma, step, linear, geometry, sclip, nclip, integrmode) else: isophote = self._iterative(sma, step, linear, geometry, sclip, nclip, integrmode, conver, minit, maxit, fflag, maxgerr, going_inwards) # store result in list if isophote_list is not None and isophote.valid: isophote_list.append(isophote) return isophote
[ "def", "fit_isophote", "(", "self", ",", "sma", ",", "step", "=", "0.1", ",", "conver", "=", "DEFAULT_CONVERGENCE", ",", "minit", "=", "DEFAULT_MINIT", ",", "maxit", "=", "DEFAULT_MAXIT", ",", "fflag", "=", "DEFAULT_FFLAG", ",", "maxgerr", "=", "DEFAULT_MAXGERR", ",", "sclip", "=", "3.", ",", "nclip", "=", "0", ",", "integrmode", "=", "BILINEAR", ",", "linear", "=", "False", ",", "maxrit", "=", "None", ",", "noniterate", "=", "False", ",", "going_inwards", "=", "False", ",", "isophote_list", "=", "None", ")", ":", "geometry", "=", "self", ".", "_geometry", "# if available, geometry from last fitted isophote will be", "# used as initial guess for next isophote.", "if", "isophote_list", "is", "not", "None", "and", "len", "(", "isophote_list", ")", ">", "0", ":", "geometry", "=", "isophote_list", "[", "-", "1", "]", ".", "sample", ".", "geometry", "# do the fit", "if", "noniterate", "or", "(", "maxrit", "and", "sma", ">", "maxrit", ")", ":", "isophote", "=", "self", ".", "_non_iterative", "(", "sma", ",", "step", ",", "linear", ",", "geometry", ",", "sclip", ",", "nclip", ",", "integrmode", ")", "else", ":", "isophote", "=", "self", ".", "_iterative", "(", "sma", ",", "step", ",", "linear", ",", "geometry", ",", "sclip", ",", "nclip", ",", "integrmode", ",", "conver", ",", "minit", ",", "maxit", ",", "fflag", ",", "maxgerr", ",", "going_inwards", ")", "# store result in list", "if", "isophote_list", "is", "not", "None", "and", "isophote", ".", "valid", ":", "isophote_list", ".", "append", "(", "isophote", ")", "return", "isophote" ]
Fit a single isophote with a given semimajor axis length. The ``step`` and ``linear`` parameters are not used to actually grow or shrink the current fitting semimajor axis length. They are necessary so the sampling algorithm can know where to start the gradient computation and also how to compute the elliptical sector areas (when area integration mode is selected). Parameters ---------- sma : float The semimajor axis length (pixels). step : float, optional The step value used to grow/shrink the semimajor axis length (pixels if ``linear=True``, or a relative value if ``linear=False``). See the ``linear`` parameter. The default is 0.1. conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The default is 0.05. minit : int, optional The minimum number of iterations to perform. A minimum of 10 (the default) iterations guarantees that, on average, 2 iterations will be available for fitting each independent parameter (the four harmonic amplitudes and the intensity level). For the first isophote, the minimum number of iterations is 2 * ``minit`` to ensure that, even departing from not-so-good initial values, the algorithm has a better chance to converge to a sensible solution. maxit : int, optional The maximum number of iterations to perform. The default is 50. fflag : float, optional The acceptable fraction of flagged data points in the sample. If the actual fraction of valid data points is smaller than this, the iterations will stop and the current `~photutils.isophote.Isophote` will be returned. Flagged data points are points that either lie outside the image frame, are masked, or were rejected by sigma-clipping. The default is 0.7. maxgerr : float, optional The maximum acceptable relative error in the local radial intensity gradient. When fitting a single isophote by itself this paramter doesn't have any effect on the outcome. sclip : float, optional The sigma-clip sigma value. The default is 3.0. nclip : int, optional The number of sigma-clip interations. The default is 0, which means sigma-clipping is skipped. integrmode : {'bilinear', 'nearest_neighbor', 'mean', 'median'}, optional The area integration mode. The default is 'bilinear'. linear : bool, optional The semimajor axis growing/shrinking mode. When fitting just one isophote, this parameter is used only by the code that define the details of how elliptical arc segments ("sectors") are extracted from the image when using area extraction modes (see the ``integrmode`` parameter). maxrit : float or `None`, optional The maximum value of semimajor axis to perform an actual fit. Whenever the current semimajor axis length is larger than ``maxrit``, the isophotes will be extracted using the current geometry, without being fitted. This non-iterative mode may be useful for sampling regions of very low surface brightness, where the algorithm may become unstable and unable to recover reliable geometry information. Non-iterative mode can also be entered automatically whenever the ellipticity exceeds 1.0 or the ellipse center crosses the image boundaries. If `None` (default), then no maximum value is used. noniterate : bool, optional Whether the fitting algorithm should be bypassed and an isophote should be extracted with the geometry taken directly from the most recent `~photutils.isophote.Isophote` instance stored in the ``isophote_list`` parameter. This parameter is mainly used when running the method in a loop over different values of semimajor axis length, and we want to change from iterative to non-iterative mode somewhere along the sequence of isophotes. When set to `True`, this parameter overrides the behavior associated with parameter ``maxrit``. The default is `False`. going_inwards : bool, optional Parameter to define the sense of SMA growth. When fitting just one isophote, this parameter is used only by the code that defines the details of how elliptical arc segments ("sectors") are extracted from the image, when using area extraction modes (see the ``integrmode`` parameter). The default is `False`. isophote_list : list or `None`, optional If not `None` (the default), the fitted `~photutils.isophote.Isophote` instance is appended to this list. It must be created and managed by the caller. Returns ------- result : `~photutils.isophote.Isophote` instance The fitted isophote. The fitted isophote is also appended to the input list input to the ``isophote_list`` parameter.
[ "Fit", "a", "single", "isophote", "with", "a", "given", "semimajor", "axis", "length", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/isophote/ellipse.py#L451-L579
train
astropy/photutils
photutils/aperture/circle.py
CircularAperture.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyCircularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAperture` object A `SkyCircularAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyCircularAperture(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyCircularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAperture` object A `SkyCircularAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyCircularAperture(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyCircularAperture", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyCircularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAperture` object A `SkyCircularAperture` object.
[ "Convert", "the", "aperture", "to", "a", "SkyCircularAperture", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/circle.py#L157-L179
train
astropy/photutils
photutils/aperture/circle.py
CircularAnnulus.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyCircularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAnnulus` object A `SkyCircularAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyCircularAnnulus(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyCircularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAnnulus` object A `SkyCircularAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyCircularAnnulus(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyCircularAnnulus", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyCircularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyCircularAnnulus` object A `SkyCircularAnnulus` object.
[ "Convert", "the", "aperture", "to", "a", "SkyCircularAnnulus", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/circle.py#L254-L276
train
astropy/photutils
photutils/aperture/circle.py
SkyCircularAperture.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `CircularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAperture` object A `CircularAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return CircularAperture(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `CircularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAperture` object A `CircularAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return CircularAperture(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "CircularAperture", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to a `CircularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAperture` object A `CircularAperture` object.
[ "Convert", "the", "aperture", "to", "a", "CircularAperture", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/circle.py#L303-L325
train
astropy/photutils
photutils/aperture/circle.py
SkyCircularAnnulus.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `CircularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAnnulus` object A `CircularAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return CircularAnnulus(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `CircularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAnnulus` object A `CircularAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return CircularAnnulus(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "CircularAnnulus", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to a `CircularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `CircularAnnulus` object A `CircularAnnulus` object.
[ "Convert", "the", "aperture", "to", "a", "CircularAnnulus", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/circle.py#L364-L386
train
astropy/photutils
photutils/datasets/make.py
apply_poisson_noise
def apply_poisson_noise(data, random_state=None): """ Apply Poisson noise to an array, where the value of each element in the input array represents the expected number of counts. Each pixel in the output array is generated by drawing a random sample from a Poisson distribution whose expectation value is given by the pixel value in the input array. Parameters ---------- data : array-like The array on which to apply Poisson noise. Every pixel in the array must have a positive value (i.e. counts). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- result : `~numpy.ndarray` The data array after applying Poisson noise. See Also -------- make_noise_image Examples -------- .. plot:: :include-source: from photutils.datasets import make_4gaussians_image from photutils.datasets import apply_poisson_noise data1 = make_4gaussians_image(noise=False) data2 = apply_poisson_noise(data1, random_state=12345) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(data1, origin='lower', interpolation='nearest') ax1.set_title('Original image') ax2.imshow(data2, origin='lower', interpolation='nearest') ax2.set_title('Original image with Poisson noise applied') """ data = np.asanyarray(data) if np.any(data < 0): raise ValueError('data must not contain any negative values') prng = check_random_state(random_state) return prng.poisson(data)
python
def apply_poisson_noise(data, random_state=None): """ Apply Poisson noise to an array, where the value of each element in the input array represents the expected number of counts. Each pixel in the output array is generated by drawing a random sample from a Poisson distribution whose expectation value is given by the pixel value in the input array. Parameters ---------- data : array-like The array on which to apply Poisson noise. Every pixel in the array must have a positive value (i.e. counts). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- result : `~numpy.ndarray` The data array after applying Poisson noise. See Also -------- make_noise_image Examples -------- .. plot:: :include-source: from photutils.datasets import make_4gaussians_image from photutils.datasets import apply_poisson_noise data1 = make_4gaussians_image(noise=False) data2 = apply_poisson_noise(data1, random_state=12345) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(data1, origin='lower', interpolation='nearest') ax1.set_title('Original image') ax2.imshow(data2, origin='lower', interpolation='nearest') ax2.set_title('Original image with Poisson noise applied') """ data = np.asanyarray(data) if np.any(data < 0): raise ValueError('data must not contain any negative values') prng = check_random_state(random_state) return prng.poisson(data)
[ "def", "apply_poisson_noise", "(", "data", ",", "random_state", "=", "None", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "if", "np", ".", "any", "(", "data", "<", "0", ")", ":", "raise", "ValueError", "(", "'data must not contain any negative values'", ")", "prng", "=", "check_random_state", "(", "random_state", ")", "return", "prng", ".", "poisson", "(", "data", ")" ]
Apply Poisson noise to an array, where the value of each element in the input array represents the expected number of counts. Each pixel in the output array is generated by drawing a random sample from a Poisson distribution whose expectation value is given by the pixel value in the input array. Parameters ---------- data : array-like The array on which to apply Poisson noise. Every pixel in the array must have a positive value (i.e. counts). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- result : `~numpy.ndarray` The data array after applying Poisson noise. See Also -------- make_noise_image Examples -------- .. plot:: :include-source: from photutils.datasets import make_4gaussians_image from photutils.datasets import apply_poisson_noise data1 = make_4gaussians_image(noise=False) data2 = apply_poisson_noise(data1, random_state=12345) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax1.imshow(data1, origin='lower', interpolation='nearest') ax1.set_title('Original image') ax2.imshow(data2, origin='lower', interpolation='nearest') ax2.set_title('Original image with Poisson noise applied')
[ "Apply", "Poisson", "noise", "to", "an", "array", "where", "the", "value", "of", "each", "element", "in", "the", "input", "array", "represents", "the", "expected", "number", "of", "counts", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L26-L78
train
astropy/photutils
photutils/datasets/make.py
make_noise_image
def make_noise_image(shape, type='gaussian', mean=None, stddev=None, random_state=None): """ Make a noise image containing Gaussian or Poisson noise. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. type : {'gaussian', 'poisson'} The distribution used to generate the random noise: * ``'gaussian'``: Gaussian distributed noise. * ``'poisson'``: Poisson distributed noise. mean : float The mean of the random distribution. Required for both Gaussian and Poisson noise. The default is 0. stddev : float, optional The standard deviation of the Gaussian noise to add to the output image. Required for Gaussian noise and ignored for Poisson noise (the variance of the Poisson distribution is equal to its mean). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Separate function calls with the same noise parameters and ``random_state`` will generate the identical noise image. Returns ------- image : 2D `~numpy.ndarray` Image containing random noise. See Also -------- apply_poisson_noise Examples -------- .. plot:: :include-source: # make Gaussian and Poisson noise images from photutils.datasets import make_noise_image shape = (100, 100) image1 = make_noise_image(shape, type='gaussian', mean=0., stddev=5.) image2 = make_noise_image(shape, type='poisson', mean=5.) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4)) ax1.imshow(image1, origin='lower', interpolation='nearest') ax1.set_title('Gaussian noise ($\\mu=0$, $\\sigma=5.$)') ax2.imshow(image2, origin='lower', interpolation='nearest') ax2.set_title('Poisson noise ($\\mu=5$)') """ if mean is None: raise ValueError('"mean" must be input') prng = check_random_state(random_state) if type == 'gaussian': if stddev is None: raise ValueError('"stddev" must be input for Gaussian noise') image = prng.normal(loc=mean, scale=stddev, size=shape) elif type == 'poisson': image = prng.poisson(lam=mean, size=shape) else: raise ValueError('Invalid type: {0}. Use one of ' '{"gaussian", "poisson"}.'.format(type)) return image
python
def make_noise_image(shape, type='gaussian', mean=None, stddev=None, random_state=None): """ Make a noise image containing Gaussian or Poisson noise. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. type : {'gaussian', 'poisson'} The distribution used to generate the random noise: * ``'gaussian'``: Gaussian distributed noise. * ``'poisson'``: Poisson distributed noise. mean : float The mean of the random distribution. Required for both Gaussian and Poisson noise. The default is 0. stddev : float, optional The standard deviation of the Gaussian noise to add to the output image. Required for Gaussian noise and ignored for Poisson noise (the variance of the Poisson distribution is equal to its mean). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Separate function calls with the same noise parameters and ``random_state`` will generate the identical noise image. Returns ------- image : 2D `~numpy.ndarray` Image containing random noise. See Also -------- apply_poisson_noise Examples -------- .. plot:: :include-source: # make Gaussian and Poisson noise images from photutils.datasets import make_noise_image shape = (100, 100) image1 = make_noise_image(shape, type='gaussian', mean=0., stddev=5.) image2 = make_noise_image(shape, type='poisson', mean=5.) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4)) ax1.imshow(image1, origin='lower', interpolation='nearest') ax1.set_title('Gaussian noise ($\\mu=0$, $\\sigma=5.$)') ax2.imshow(image2, origin='lower', interpolation='nearest') ax2.set_title('Poisson noise ($\\mu=5$)') """ if mean is None: raise ValueError('"mean" must be input') prng = check_random_state(random_state) if type == 'gaussian': if stddev is None: raise ValueError('"stddev" must be input for Gaussian noise') image = prng.normal(loc=mean, scale=stddev, size=shape) elif type == 'poisson': image = prng.poisson(lam=mean, size=shape) else: raise ValueError('Invalid type: {0}. Use one of ' '{"gaussian", "poisson"}.'.format(type)) return image
[ "def", "make_noise_image", "(", "shape", ",", "type", "=", "'gaussian'", ",", "mean", "=", "None", ",", "stddev", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "mean", "is", "None", ":", "raise", "ValueError", "(", "'\"mean\" must be input'", ")", "prng", "=", "check_random_state", "(", "random_state", ")", "if", "type", "==", "'gaussian'", ":", "if", "stddev", "is", "None", ":", "raise", "ValueError", "(", "'\"stddev\" must be input for Gaussian noise'", ")", "image", "=", "prng", ".", "normal", "(", "loc", "=", "mean", ",", "scale", "=", "stddev", ",", "size", "=", "shape", ")", "elif", "type", "==", "'poisson'", ":", "image", "=", "prng", ".", "poisson", "(", "lam", "=", "mean", ",", "size", "=", "shape", ")", "else", ":", "raise", "ValueError", "(", "'Invalid type: {0}. Use one of '", "'{\"gaussian\", \"poisson\"}.'", ".", "format", "(", "type", ")", ")", "return", "image" ]
Make a noise image containing Gaussian or Poisson noise. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. type : {'gaussian', 'poisson'} The distribution used to generate the random noise: * ``'gaussian'``: Gaussian distributed noise. * ``'poisson'``: Poisson distributed noise. mean : float The mean of the random distribution. Required for both Gaussian and Poisson noise. The default is 0. stddev : float, optional The standard deviation of the Gaussian noise to add to the output image. Required for Gaussian noise and ignored for Poisson noise (the variance of the Poisson distribution is equal to its mean). random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Separate function calls with the same noise parameters and ``random_state`` will generate the identical noise image. Returns ------- image : 2D `~numpy.ndarray` Image containing random noise. See Also -------- apply_poisson_noise Examples -------- .. plot:: :include-source: # make Gaussian and Poisson noise images from photutils.datasets import make_noise_image shape = (100, 100) image1 = make_noise_image(shape, type='gaussian', mean=0., stddev=5.) image2 = make_noise_image(shape, type='poisson', mean=5.) # plot the images import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4)) ax1.imshow(image1, origin='lower', interpolation='nearest') ax1.set_title('Gaussian noise ($\\mu=0$, $\\sigma=5.$)') ax2.imshow(image2, origin='lower', interpolation='nearest') ax2.set_title('Poisson noise ($\\mu=5$)')
[ "Make", "a", "noise", "image", "containing", "Gaussian", "or", "Poisson", "noise", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L81-L156
train
astropy/photutils
photutils/datasets/make.py
make_random_models_table
def make_random_models_table(n_sources, param_ranges, random_state=None): """ Make a `~astropy.table.Table` containing randomly generated parameters for an Astropy model to simulate a set of sources. Each row of the table corresponds to a source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_model_sources_image` to create an image containing the model sources. Parameters ---------- n_sources : float The number of random model sources to generate. param_ranges : dict The lower and upper boundaries for each of the model parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated sources. Each row of the table corresponds to a source whose model parameters are defined by the column names. The column names will be the keys of the dictionary ``param_ranges``. See Also -------- make_random_gaussians_table, make_model_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_models_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_models_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 """ prng = check_random_state(random_state) sources = Table() for param_name, (lower, upper) in param_ranges.items(): # Generate a column for every item in param_ranges, even if it # is not in the model (e.g. flux). However, such columns will # be ignored when rendering the image. sources[param_name] = prng.uniform(lower, upper, n_sources) return sources
python
def make_random_models_table(n_sources, param_ranges, random_state=None): """ Make a `~astropy.table.Table` containing randomly generated parameters for an Astropy model to simulate a set of sources. Each row of the table corresponds to a source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_model_sources_image` to create an image containing the model sources. Parameters ---------- n_sources : float The number of random model sources to generate. param_ranges : dict The lower and upper boundaries for each of the model parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated sources. Each row of the table corresponds to a source whose model parameters are defined by the column names. The column names will be the keys of the dictionary ``param_ranges``. See Also -------- make_random_gaussians_table, make_model_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_models_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_models_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 """ prng = check_random_state(random_state) sources = Table() for param_name, (lower, upper) in param_ranges.items(): # Generate a column for every item in param_ranges, even if it # is not in the model (e.g. flux). However, such columns will # be ignored when rendering the image. sources[param_name] = prng.uniform(lower, upper, n_sources) return sources
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
Make a `~astropy.table.Table` containing randomly generated parameters for an Astropy model to simulate a set of sources. Each row of the table corresponds to a source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_model_sources_image` to create an image containing the model sources. Parameters ---------- n_sources : float The number of random model sources to generate. param_ranges : dict The lower and upper boundaries for each of the model parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated sources. Each row of the table corresponds to a source whose model parameters are defined by the column names. The column names will be the keys of the dictionary ``param_ranges``. See Also -------- make_random_gaussians_table, make_model_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_models_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_models_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298
[ "Make", "a", "~astropy", ".", "table", ".", "Table", "containing", "randomly", "generated", "parameters", "for", "an", "Astropy", "model", "to", "simulate", "a", "set", "of", "sources", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L159-L237
train
astropy/photutils
photutils/datasets/make.py
make_random_gaussians_table
def make_random_gaussians_table(n_sources, param_ranges, random_state=None): """ Make a `~astropy.table.Table` containing randomly generated parameters for 2D Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_gaussian_sources_image` to create an image containing the 2D Gaussian sources. Parameters ---------- n_sources : float The number of random Gaussian sources to generate. param_ranges : dict The lower and upper boundaries for each of the `~astropy.modeling.functional_models.Gaussian2D` parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. The dictionary keys must be valid `~astropy.modeling.functional_models.Gaussian2D` parameter names or ``'flux'``. If ``'flux'`` is specified, but not ``'amplitude'`` then the 2D Gaussian amplitudes will be calculated and placed in the output table. If both ``'flux'`` and ``'amplitude'`` are specified, then ``'flux'`` will be ignored. Model parameters not defined in ``param_ranges`` will be set to the default value. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. See Also -------- make_random_models_table, make_gaussian_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_gaussians_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 To specifying the flux range instead of the amplitude range: >>> param_ranges = [('flux', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) flux x_mean y_mean x_stddev y_stddev theta amplitude --------- --------- --------- --------- --------- ---------- --------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 11.863685 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 6.3854388 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 7.3122209 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 8.5691781 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 11.611707 Note that in this case the output table contains both a flux and amplitude column. The flux column will be ignored when generating an image of the models using :func:`make_gaussian_sources_image`. """ sources = make_random_models_table(n_sources, param_ranges, random_state=random_state) # convert Gaussian2D flux to amplitude if 'flux' in param_ranges and 'amplitude' not in param_ranges: model = Gaussian2D(x_stddev=1, y_stddev=1) if 'x_stddev' in sources.colnames: xstd = sources['x_stddev'] else: xstd = model.x_stddev.value # default if 'y_stddev' in sources.colnames: ystd = sources['y_stddev'] else: ystd = model.y_stddev.value # default sources = sources.copy() sources['amplitude'] = sources['flux'] / (2. * np.pi * xstd * ystd) return sources
python
def make_random_gaussians_table(n_sources, param_ranges, random_state=None): """ Make a `~astropy.table.Table` containing randomly generated parameters for 2D Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_gaussian_sources_image` to create an image containing the 2D Gaussian sources. Parameters ---------- n_sources : float The number of random Gaussian sources to generate. param_ranges : dict The lower and upper boundaries for each of the `~astropy.modeling.functional_models.Gaussian2D` parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. The dictionary keys must be valid `~astropy.modeling.functional_models.Gaussian2D` parameter names or ``'flux'``. If ``'flux'`` is specified, but not ``'amplitude'`` then the 2D Gaussian amplitudes will be calculated and placed in the output table. If both ``'flux'`` and ``'amplitude'`` are specified, then ``'flux'`` will be ignored. Model parameters not defined in ``param_ranges`` will be set to the default value. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. See Also -------- make_random_models_table, make_gaussian_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_gaussians_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 To specifying the flux range instead of the amplitude range: >>> param_ranges = [('flux', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) flux x_mean y_mean x_stddev y_stddev theta amplitude --------- --------- --------- --------- --------- ---------- --------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 11.863685 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 6.3854388 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 7.3122209 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 8.5691781 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 11.611707 Note that in this case the output table contains both a flux and amplitude column. The flux column will be ignored when generating an image of the models using :func:`make_gaussian_sources_image`. """ sources = make_random_models_table(n_sources, param_ranges, random_state=random_state) # convert Gaussian2D flux to amplitude if 'flux' in param_ranges and 'amplitude' not in param_ranges: model = Gaussian2D(x_stddev=1, y_stddev=1) if 'x_stddev' in sources.colnames: xstd = sources['x_stddev'] else: xstd = model.x_stddev.value # default if 'y_stddev' in sources.colnames: ystd = sources['y_stddev'] else: ystd = model.y_stddev.value # default sources = sources.copy() sources['amplitude'] = sources['flux'] / (2. * np.pi * xstd * ystd) return sources
[ "def", "make_random_gaussians_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "sources", "=", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "random_state", ")", "# convert Gaussian2D flux to amplitude", "if", "'flux'", "in", "param_ranges", "and", "'amplitude'", "not", "in", "param_ranges", ":", "model", "=", "Gaussian2D", "(", "x_stddev", "=", "1", ",", "y_stddev", "=", "1", ")", "if", "'x_stddev'", "in", "sources", ".", "colnames", ":", "xstd", "=", "sources", "[", "'x_stddev'", "]", "else", ":", "xstd", "=", "model", ".", "x_stddev", ".", "value", "# default", "if", "'y_stddev'", "in", "sources", ".", "colnames", ":", "ystd", "=", "sources", "[", "'y_stddev'", "]", "else", ":", "ystd", "=", "model", ".", "y_stddev", ".", "value", "# default", "sources", "=", "sources", ".", "copy", "(", ")", "sources", "[", "'amplitude'", "]", "=", "sources", "[", "'flux'", "]", "/", "(", "2.", "*", "np", ".", "pi", "*", "xstd", "*", "ystd", ")", "return", "sources" ]
Make a `~astropy.table.Table` containing randomly generated parameters for 2D Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. The parameters are drawn from a uniform distribution over the specified input ranges. The output table can be input into :func:`make_gaussian_sources_image` to create an image containing the 2D Gaussian sources. Parameters ---------- n_sources : float The number of random Gaussian sources to generate. param_ranges : dict The lower and upper boundaries for each of the `~astropy.modeling.functional_models.Gaussian2D` parameters as a `dict` mapping the parameter name to its ``(lower, upper)`` bounds. The dictionary keys must be valid `~astropy.modeling.functional_models.Gaussian2D` parameter names or ``'flux'``. If ``'flux'`` is specified, but not ``'amplitude'`` then the 2D Gaussian amplitudes will be calculated and placed in the output table. If both ``'flux'`` and ``'amplitude'`` are specified, then ``'flux'`` will be ignored. Model parameters not defined in ``param_ranges`` will be set to the default value. random_state : int or `~numpy.random.RandomState`, optional Pseudo-random number generator state used for random sampling. Returns ------- table : `~astropy.table.Table` A table of parameters for the randomly generated Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. See Also -------- make_random_models_table, make_gaussian_sources_image Notes ----- To generate identical parameter values from separate function calls, ``param_ranges`` must be input as an `~collections.OrderedDict` with the same parameter ranges and ``random_state`` must be the same. Examples -------- >>> from collections import OrderedDict >>> from photutils.datasets import make_random_gaussians_table >>> n_sources = 5 >>> param_ranges = [('amplitude', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) amplitude x_mean y_mean x_stddev y_stddev theta --------- --------- --------- --------- --------- ---------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 To specifying the flux range instead of the amplitude range: >>> param_ranges = [('flux', [500, 1000]), ... ('x_mean', [0, 500]), ... ('y_mean', [0, 300]), ... ('x_stddev', [1, 5]), ... ('y_stddev', [1, 5]), ... ('theta', [0, np.pi])] >>> param_ranges = OrderedDict(param_ranges) >>> sources = make_random_gaussians_table(n_sources, param_ranges, ... random_state=12345) >>> for col in sources.colnames: ... sources[col].info.format = '%.8g' # for consistent table output >>> print(sources) flux x_mean y_mean x_stddev y_stddev theta amplitude --------- --------- --------- --------- --------- ---------- --------- 964.80805 297.77235 224.31444 3.6256447 3.5699013 2.2923859 11.863685 658.18778 482.25726 288.39202 4.2392502 3.8698145 3.1227889 6.3854388 591.95941 326.58855 2.5164894 4.4887037 2.870396 2.1264615 7.3122209 602.28014 374.45332 31.933313 4.8585904 2.3023387 2.4844422 8.5691781 783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 11.611707 Note that in this case the output table contains both a flux and amplitude column. The flux column will be ignored when generating an image of the models using :func:`make_gaussian_sources_image`.
[ "Make", "a", "~astropy", ".", "table", ".", "Table", "containing", "randomly", "generated", "parameters", "for", "2D", "Gaussian", "sources", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L240-L363
train
astropy/photutils
photutils/datasets/make.py
make_model_sources_image
def make_model_sources_image(shape, model, source_table, oversample=1): """ Make an image containing sources generated from a user-specified model. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. model : 2D astropy.modeling.models object The model to be used for rendering the sources. source_table : `~astropy.table.Table` Table of parameters for the sources. Each row of the table corresponds to a source whose model parameters are defined by the column names, which must match the model parameter names. Column names that do not match model parameters will be ignored. Model parameters not defined in the table will be set to the ``model`` default value. oversample : float, optional The sampling factor used to discretize the models on a pixel grid. If the value is 1.0 (the default), then the models will be discretized by taking the value at the center of the pixel bin. Note that this method will not preserve the total flux of very small sources. Otherwise, the models will be discretized by taking the average over an oversampled grid. The pixels will be oversampled by the ``oversample`` factor. Returns ------- image : 2D `~numpy.ndarray` Image containing model sources. See Also -------- make_random_models_table, make_gaussian_sources_image Examples -------- .. plot:: :include-source: from collections import OrderedDict from astropy.modeling.models import Moffat2D from photutils.datasets import (make_random_models_table, make_model_sources_image) model = Moffat2D() n_sources = 10 shape = (100, 100) param_ranges = [('amplitude', [100, 200]), ('x_0', [0, shape[1]]), ('y_0', [0, shape[0]]), ('gamma', [5, 10]), ('alpha', [1, 2])] param_ranges = OrderedDict(param_ranges) sources = make_random_models_table(n_sources, param_ranges, random_state=12345) data = make_model_sources_image(shape, model, sources) plt.imshow(data) """ image = np.zeros(shape, dtype=np.float64) y, x = np.indices(shape) params_to_set = [] for param in source_table.colnames: if param in model.param_names: params_to_set.append(param) # Save the initial parameter values so we can set them back when # done with the loop. It's best not to copy a model, because some # models (e.g. PSF models) may have substantial amounts of data in # them. init_params = {param: getattr(model, param) for param in params_to_set} try: for i, source in enumerate(source_table): for param in params_to_set: setattr(model, param, source[param]) if oversample == 1: image += model(x, y) else: image += discretize_model(model, (0, shape[1]), (0, shape[0]), mode='oversample', factor=oversample) finally: for param, value in init_params.items(): setattr(model, param, value) return image
python
def make_model_sources_image(shape, model, source_table, oversample=1): """ Make an image containing sources generated from a user-specified model. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. model : 2D astropy.modeling.models object The model to be used for rendering the sources. source_table : `~astropy.table.Table` Table of parameters for the sources. Each row of the table corresponds to a source whose model parameters are defined by the column names, which must match the model parameter names. Column names that do not match model parameters will be ignored. Model parameters not defined in the table will be set to the ``model`` default value. oversample : float, optional The sampling factor used to discretize the models on a pixel grid. If the value is 1.0 (the default), then the models will be discretized by taking the value at the center of the pixel bin. Note that this method will not preserve the total flux of very small sources. Otherwise, the models will be discretized by taking the average over an oversampled grid. The pixels will be oversampled by the ``oversample`` factor. Returns ------- image : 2D `~numpy.ndarray` Image containing model sources. See Also -------- make_random_models_table, make_gaussian_sources_image Examples -------- .. plot:: :include-source: from collections import OrderedDict from astropy.modeling.models import Moffat2D from photutils.datasets import (make_random_models_table, make_model_sources_image) model = Moffat2D() n_sources = 10 shape = (100, 100) param_ranges = [('amplitude', [100, 200]), ('x_0', [0, shape[1]]), ('y_0', [0, shape[0]]), ('gamma', [5, 10]), ('alpha', [1, 2])] param_ranges = OrderedDict(param_ranges) sources = make_random_models_table(n_sources, param_ranges, random_state=12345) data = make_model_sources_image(shape, model, sources) plt.imshow(data) """ image = np.zeros(shape, dtype=np.float64) y, x = np.indices(shape) params_to_set = [] for param in source_table.colnames: if param in model.param_names: params_to_set.append(param) # Save the initial parameter values so we can set them back when # done with the loop. It's best not to copy a model, because some # models (e.g. PSF models) may have substantial amounts of data in # them. init_params = {param: getattr(model, param) for param in params_to_set} try: for i, source in enumerate(source_table): for param in params_to_set: setattr(model, param, source[param]) if oversample == 1: image += model(x, y) else: image += discretize_model(model, (0, shape[1]), (0, shape[0]), mode='oversample', factor=oversample) finally: for param, value in init_params.items(): setattr(model, param, value) return image
[ "def", "make_model_sources_image", "(", "shape", ",", "model", ",", "source_table", ",", "oversample", "=", "1", ")", ":", "image", "=", "np", ".", "zeros", "(", "shape", ",", "dtype", "=", "np", ".", "float64", ")", "y", ",", "x", "=", "np", ".", "indices", "(", "shape", ")", "params_to_set", "=", "[", "]", "for", "param", "in", "source_table", ".", "colnames", ":", "if", "param", "in", "model", ".", "param_names", ":", "params_to_set", ".", "append", "(", "param", ")", "# Save the initial parameter values so we can set them back when", "# done with the loop. It's best not to copy a model, because some", "# models (e.g. PSF models) may have substantial amounts of data in", "# them.", "init_params", "=", "{", "param", ":", "getattr", "(", "model", ",", "param", ")", "for", "param", "in", "params_to_set", "}", "try", ":", "for", "i", ",", "source", "in", "enumerate", "(", "source_table", ")", ":", "for", "param", "in", "params_to_set", ":", "setattr", "(", "model", ",", "param", ",", "source", "[", "param", "]", ")", "if", "oversample", "==", "1", ":", "image", "+=", "model", "(", "x", ",", "y", ")", "else", ":", "image", "+=", "discretize_model", "(", "model", ",", "(", "0", ",", "shape", "[", "1", "]", ")", ",", "(", "0", ",", "shape", "[", "0", "]", ")", ",", "mode", "=", "'oversample'", ",", "factor", "=", "oversample", ")", "finally", ":", "for", "param", ",", "value", "in", "init_params", ".", "items", "(", ")", ":", "setattr", "(", "model", ",", "param", ",", "value", ")", "return", "image" ]
Make an image containing sources generated from a user-specified model. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. model : 2D astropy.modeling.models object The model to be used for rendering the sources. source_table : `~astropy.table.Table` Table of parameters for the sources. Each row of the table corresponds to a source whose model parameters are defined by the column names, which must match the model parameter names. Column names that do not match model parameters will be ignored. Model parameters not defined in the table will be set to the ``model`` default value. oversample : float, optional The sampling factor used to discretize the models on a pixel grid. If the value is 1.0 (the default), then the models will be discretized by taking the value at the center of the pixel bin. Note that this method will not preserve the total flux of very small sources. Otherwise, the models will be discretized by taking the average over an oversampled grid. The pixels will be oversampled by the ``oversample`` factor. Returns ------- image : 2D `~numpy.ndarray` Image containing model sources. See Also -------- make_random_models_table, make_gaussian_sources_image Examples -------- .. plot:: :include-source: from collections import OrderedDict from astropy.modeling.models import Moffat2D from photutils.datasets import (make_random_models_table, make_model_sources_image) model = Moffat2D() n_sources = 10 shape = (100, 100) param_ranges = [('amplitude', [100, 200]), ('x_0', [0, shape[1]]), ('y_0', [0, shape[0]]), ('gamma', [5, 10]), ('alpha', [1, 2])] param_ranges = OrderedDict(param_ranges) sources = make_random_models_table(n_sources, param_ranges, random_state=12345) data = make_model_sources_image(shape, model, sources) plt.imshow(data)
[ "Make", "an", "image", "containing", "sources", "generated", "from", "a", "user", "-", "specified", "model", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L366-L460
train
astropy/photutils
photutils/datasets/make.py
make_4gaussians_image
def make_4gaussians_image(noise=True): """ Make an example image containing four 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 5 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing four 2D Gaussian sources. See Also -------- make_100gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_4gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest') """ table = Table() table['amplitude'] = [50, 70, 150, 210] table['x_mean'] = [160, 25, 150, 90] table['y_mean'] = [70, 40, 25, 60] table['x_stddev'] = [15.2, 5.1, 3., 8.1] table['y_stddev'] = [2.6, 2.5, 3., 4.7] table['theta'] = np.array([145., 20., 0., 60.]) * np.pi / 180. shape = (100, 200) data = make_gaussian_sources_image(shape, table) + 5. if noise: data += make_noise_image(shape, type='gaussian', mean=0., stddev=5., random_state=12345) return data
python
def make_4gaussians_image(noise=True): """ Make an example image containing four 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 5 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing four 2D Gaussian sources. See Also -------- make_100gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_4gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest') """ table = Table() table['amplitude'] = [50, 70, 150, 210] table['x_mean'] = [160, 25, 150, 90] table['y_mean'] = [70, 40, 25, 60] table['x_stddev'] = [15.2, 5.1, 3., 8.1] table['y_stddev'] = [2.6, 2.5, 3., 4.7] table['theta'] = np.array([145., 20., 0., 60.]) * np.pi / 180. shape = (100, 200) data = make_gaussian_sources_image(shape, table) + 5. if noise: data += make_noise_image(shape, type='gaussian', mean=0., stddev=5., random_state=12345) return data
[ "def", "make_4gaussians_image", "(", "noise", "=", "True", ")", ":", "table", "=", "Table", "(", ")", "table", "[", "'amplitude'", "]", "=", "[", "50", ",", "70", ",", "150", ",", "210", "]", "table", "[", "'x_mean'", "]", "=", "[", "160", ",", "25", ",", "150", ",", "90", "]", "table", "[", "'y_mean'", "]", "=", "[", "70", ",", "40", ",", "25", ",", "60", "]", "table", "[", "'x_stddev'", "]", "=", "[", "15.2", ",", "5.1", ",", "3.", ",", "8.1", "]", "table", "[", "'y_stddev'", "]", "=", "[", "2.6", ",", "2.5", ",", "3.", ",", "4.7", "]", "table", "[", "'theta'", "]", "=", "np", ".", "array", "(", "[", "145.", ",", "20.", ",", "0.", ",", "60.", "]", ")", "*", "np", ".", "pi", "/", "180.", "shape", "=", "(", "100", ",", "200", ")", "data", "=", "make_gaussian_sources_image", "(", "shape", ",", "table", ")", "+", "5.", "if", "noise", ":", "data", "+=", "make_noise_image", "(", "shape", ",", "type", "=", "'gaussian'", ",", "mean", "=", "0.", ",", "stddev", "=", "5.", ",", "random_state", "=", "12345", ")", "return", "data" ]
Make an example image containing four 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 5 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing four 2D Gaussian sources. See Also -------- make_100gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_4gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest')
[ "Make", "an", "example", "image", "containing", "four", "2D", "Gaussians", "plus", "a", "constant", "background", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L638-L688
train
astropy/photutils
photutils/datasets/make.py
make_100gaussians_image
def make_100gaussians_image(noise=True): """ Make an example image containing 100 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 2 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing 100 2D Gaussian sources. See Also -------- make_4gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_100gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest') """ n_sources = 100 flux_range = [500, 1000] xmean_range = [0, 500] ymean_range = [0, 300] xstddev_range = [1, 5] ystddev_range = [1, 5] params = OrderedDict([('flux', flux_range), ('x_mean', xmean_range), ('y_mean', ymean_range), ('x_stddev', xstddev_range), ('y_stddev', ystddev_range), ('theta', [0, 2*np.pi])]) sources = make_random_gaussians_table(n_sources, params, random_state=12345) shape = (300, 500) data = make_gaussian_sources_image(shape, sources) + 5. if noise: data += make_noise_image(shape, type='gaussian', mean=0., stddev=2., random_state=12345) return data
python
def make_100gaussians_image(noise=True): """ Make an example image containing 100 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 2 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing 100 2D Gaussian sources. See Also -------- make_4gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_100gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest') """ n_sources = 100 flux_range = [500, 1000] xmean_range = [0, 500] ymean_range = [0, 300] xstddev_range = [1, 5] ystddev_range = [1, 5] params = OrderedDict([('flux', flux_range), ('x_mean', xmean_range), ('y_mean', ymean_range), ('x_stddev', xstddev_range), ('y_stddev', ystddev_range), ('theta', [0, 2*np.pi])]) sources = make_random_gaussians_table(n_sources, params, random_state=12345) shape = (300, 500) data = make_gaussian_sources_image(shape, sources) + 5. if noise: data += make_noise_image(shape, type='gaussian', mean=0., stddev=2., random_state=12345) return data
[ "def", "make_100gaussians_image", "(", "noise", "=", "True", ")", ":", "n_sources", "=", "100", "flux_range", "=", "[", "500", ",", "1000", "]", "xmean_range", "=", "[", "0", ",", "500", "]", "ymean_range", "=", "[", "0", ",", "300", "]", "xstddev_range", "=", "[", "1", ",", "5", "]", "ystddev_range", "=", "[", "1", ",", "5", "]", "params", "=", "OrderedDict", "(", "[", "(", "'flux'", ",", "flux_range", ")", ",", "(", "'x_mean'", ",", "xmean_range", ")", ",", "(", "'y_mean'", ",", "ymean_range", ")", ",", "(", "'x_stddev'", ",", "xstddev_range", ")", ",", "(", "'y_stddev'", ",", "ystddev_range", ")", ",", "(", "'theta'", ",", "[", "0", ",", "2", "*", "np", ".", "pi", "]", ")", "]", ")", "sources", "=", "make_random_gaussians_table", "(", "n_sources", ",", "params", ",", "random_state", "=", "12345", ")", "shape", "=", "(", "300", ",", "500", ")", "data", "=", "make_gaussian_sources_image", "(", "shape", ",", "sources", ")", "+", "5.", "if", "noise", ":", "data", "+=", "make_noise_image", "(", "shape", ",", "type", "=", "'gaussian'", ",", "mean", "=", "0.", ",", "stddev", "=", "2.", ",", "random_state", "=", "12345", ")", "return", "data" ]
Make an example image containing 100 2D Gaussians plus a constant background. The background has a mean of 5. If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a standard deviation of 2 is added to the output image. Parameters ---------- noise : bool, optional Whether to include noise in the output image (default is `True`). Returns ------- image : 2D `~numpy.ndarray` Image containing 100 2D Gaussian sources. See Also -------- make_4gaussians_image Examples -------- .. plot:: :include-source: from photutils import datasets image = datasets.make_100gaussians_image() plt.imshow(image, origin='lower', interpolation='nearest')
[ "Make", "an", "example", "image", "containing", "100", "2D", "Gaussians", "plus", "a", "constant", "background", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L691-L749
train
astropy/photutils
photutils/datasets/make.py
make_wcs
def make_wcs(shape, galactic=False): """ Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame. Parameters ---------- shape : 2-tuple of int The shape of the 2D array to be used with the output `~astropy.wcs.WCS` object. galactic : bool, optional If `True`, then the output WCS will be in the Galactic coordinate frame. If `False` (default), then the output WCS will be in the ICRS coordinate frame. Returns ------- wcs : `~astropy.wcs.WCS` object The world coordinate system (WCS) transformation. See Also -------- make_imagehdu Examples -------- >>> from photutils.datasets import make_wcs >>> shape = (100, 100) >>> wcs = make_wcs(shape) >>> print(wcs.wcs.crpix) # doctest: +FLOAT_CMP [50. 50.] >>> print(wcs.wcs.crval) # doctest: +FLOAT_CMP [197.8925 -1.36555556] """ wcs = WCS(naxis=2) rho = np.pi / 3. scale = 0.1 / 3600. if astropy_version < '3.1': wcs._naxis1 = shape[1] # nx wcs._naxis2 = shape[0] # ny else: wcs.pixel_shape = shape wcs.wcs.crpix = [shape[1] / 2, shape[0] / 2] # 1-indexed (x, y) wcs.wcs.crval = [197.8925, -1.36555556] wcs.wcs.cunit = ['deg', 'deg'] wcs.wcs.cd = [[-scale * np.cos(rho), scale * np.sin(rho)], [scale * np.sin(rho), scale * np.cos(rho)]] if not galactic: wcs.wcs.radesys = 'ICRS' wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] else: wcs.wcs.ctype = ['GLON-CAR', 'GLAT-CAR'] return wcs
python
def make_wcs(shape, galactic=False): """ Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame. Parameters ---------- shape : 2-tuple of int The shape of the 2D array to be used with the output `~astropy.wcs.WCS` object. galactic : bool, optional If `True`, then the output WCS will be in the Galactic coordinate frame. If `False` (default), then the output WCS will be in the ICRS coordinate frame. Returns ------- wcs : `~astropy.wcs.WCS` object The world coordinate system (WCS) transformation. See Also -------- make_imagehdu Examples -------- >>> from photutils.datasets import make_wcs >>> shape = (100, 100) >>> wcs = make_wcs(shape) >>> print(wcs.wcs.crpix) # doctest: +FLOAT_CMP [50. 50.] >>> print(wcs.wcs.crval) # doctest: +FLOAT_CMP [197.8925 -1.36555556] """ wcs = WCS(naxis=2) rho = np.pi / 3. scale = 0.1 / 3600. if astropy_version < '3.1': wcs._naxis1 = shape[1] # nx wcs._naxis2 = shape[0] # ny else: wcs.pixel_shape = shape wcs.wcs.crpix = [shape[1] / 2, shape[0] / 2] # 1-indexed (x, y) wcs.wcs.crval = [197.8925, -1.36555556] wcs.wcs.cunit = ['deg', 'deg'] wcs.wcs.cd = [[-scale * np.cos(rho), scale * np.sin(rho)], [scale * np.sin(rho), scale * np.cos(rho)]] if not galactic: wcs.wcs.radesys = 'ICRS' wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] else: wcs.wcs.ctype = ['GLON-CAR', 'GLAT-CAR'] return wcs
[ "def", "make_wcs", "(", "shape", ",", "galactic", "=", "False", ")", ":", "wcs", "=", "WCS", "(", "naxis", "=", "2", ")", "rho", "=", "np", ".", "pi", "/", "3.", "scale", "=", "0.1", "/", "3600.", "if", "astropy_version", "<", "'3.1'", ":", "wcs", ".", "_naxis1", "=", "shape", "[", "1", "]", "# nx", "wcs", ".", "_naxis2", "=", "shape", "[", "0", "]", "# ny", "else", ":", "wcs", ".", "pixel_shape", "=", "shape", "wcs", ".", "wcs", ".", "crpix", "=", "[", "shape", "[", "1", "]", "/", "2", ",", "shape", "[", "0", "]", "/", "2", "]", "# 1-indexed (x, y)", "wcs", ".", "wcs", ".", "crval", "=", "[", "197.8925", ",", "-", "1.36555556", "]", "wcs", ".", "wcs", ".", "cunit", "=", "[", "'deg'", ",", "'deg'", "]", "wcs", ".", "wcs", ".", "cd", "=", "[", "[", "-", "scale", "*", "np", ".", "cos", "(", "rho", ")", ",", "scale", "*", "np", ".", "sin", "(", "rho", ")", "]", ",", "[", "scale", "*", "np", ".", "sin", "(", "rho", ")", ",", "scale", "*", "np", ".", "cos", "(", "rho", ")", "]", "]", "if", "not", "galactic", ":", "wcs", ".", "wcs", ".", "radesys", "=", "'ICRS'", "wcs", ".", "wcs", ".", "ctype", "=", "[", "'RA---TAN'", ",", "'DEC--TAN'", "]", "else", ":", "wcs", ".", "wcs", ".", "ctype", "=", "[", "'GLON-CAR'", ",", "'GLAT-CAR'", "]", "return", "wcs" ]
Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame. Parameters ---------- shape : 2-tuple of int The shape of the 2D array to be used with the output `~astropy.wcs.WCS` object. galactic : bool, optional If `True`, then the output WCS will be in the Galactic coordinate frame. If `False` (default), then the output WCS will be in the ICRS coordinate frame. Returns ------- wcs : `~astropy.wcs.WCS` object The world coordinate system (WCS) transformation. See Also -------- make_imagehdu Examples -------- >>> from photutils.datasets import make_wcs >>> shape = (100, 100) >>> wcs = make_wcs(shape) >>> print(wcs.wcs.crpix) # doctest: +FLOAT_CMP [50. 50.] >>> print(wcs.wcs.crval) # doctest: +FLOAT_CMP [197.8925 -1.36555556]
[ "Create", "a", "simple", "celestial", "WCS", "object", "in", "either", "the", "ICRS", "or", "Galactic", "coordinate", "frame", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L752-L809
train
astropy/photutils
photutils/datasets/make.py
make_imagehdu
def make_imagehdu(data, wcs=None): """ Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in the output FITS header. Returns ------- image_hdu : `~astropy.io.fits.ImageHDU` The FITS `~astropy.io.fits.ImageHDU`. See Also -------- make_wcs Examples -------- >>> from photutils.datasets import make_imagehdu, make_wcs >>> shape = (100, 100) >>> data = np.ones(shape) >>> wcs = make_wcs(shape) >>> hdu = make_imagehdu(data, wcs=wcs) >>> print(hdu.data.shape) (100, 100) """ data = np.asanyarray(data) if data.ndim != 2: raise ValueError('data must be a 2D array') if wcs is not None: header = wcs.to_header() else: header = None return fits.ImageHDU(data, header=header)
python
def make_imagehdu(data, wcs=None): """ Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in the output FITS header. Returns ------- image_hdu : `~astropy.io.fits.ImageHDU` The FITS `~astropy.io.fits.ImageHDU`. See Also -------- make_wcs Examples -------- >>> from photutils.datasets import make_imagehdu, make_wcs >>> shape = (100, 100) >>> data = np.ones(shape) >>> wcs = make_wcs(shape) >>> hdu = make_imagehdu(data, wcs=wcs) >>> print(hdu.data.shape) (100, 100) """ data = np.asanyarray(data) if data.ndim != 2: raise ValueError('data must be a 2D array') if wcs is not None: header = wcs.to_header() else: header = None return fits.ImageHDU(data, header=header)
[ "def", "make_imagehdu", "(", "data", ",", "wcs", "=", "None", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'data must be a 2D array'", ")", "if", "wcs", "is", "not", "None", ":", "header", "=", "wcs", ".", "to_header", "(", ")", "else", ":", "header", "=", "None", "return", "fits", ".", "ImageHDU", "(", "data", ",", "header", "=", "header", ")" ]
Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in the output FITS header. Returns ------- image_hdu : `~astropy.io.fits.ImageHDU` The FITS `~astropy.io.fits.ImageHDU`. See Also -------- make_wcs Examples -------- >>> from photutils.datasets import make_imagehdu, make_wcs >>> shape = (100, 100) >>> data = np.ones(shape) >>> wcs = make_wcs(shape) >>> hdu = make_imagehdu(data, wcs=wcs) >>> print(hdu.data.shape) (100, 100)
[ "Create", "a", "FITS", "~astropy", ".", "io", ".", "fits", ".", "ImageHDU", "containing", "the", "input", "2D", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L812-L855
train
astropy/photutils
photutils/centroids/core.py
centroid_com
def centroid_com(data, mask=None): """ Calculate the centroid of an n-dimensional array as its "center of mass" determined from moments. Invalid values (e.g. NaNs or infs) in the ``data`` array are automatically masked. Parameters ---------- data : array_like The input n-dimensional array. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The coordinates of the centroid in pixel order (e.g. ``(x, y)`` or ``(x, y, z)``), not numpy axis order. """ data = data.astype(np.float) if mask is not None and mask is not np.ma.nomask: mask = np.asarray(mask, dtype=bool) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data[mask] = 0. badidx = ~np.isfinite(data) if np.any(badidx): warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) data[badidx] = 0. total = np.sum(data) indices = np.ogrid[[slice(0, i) for i in data.shape]] # note the output array is reversed to give (x, y) order return np.array([np.sum(indices[axis] * data) / total for axis in range(data.ndim)])[::-1]
python
def centroid_com(data, mask=None): """ Calculate the centroid of an n-dimensional array as its "center of mass" determined from moments. Invalid values (e.g. NaNs or infs) in the ``data`` array are automatically masked. Parameters ---------- data : array_like The input n-dimensional array. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The coordinates of the centroid in pixel order (e.g. ``(x, y)`` or ``(x, y, z)``), not numpy axis order. """ data = data.astype(np.float) if mask is not None and mask is not np.ma.nomask: mask = np.asarray(mask, dtype=bool) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data[mask] = 0. badidx = ~np.isfinite(data) if np.any(badidx): warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) data[badidx] = 0. total = np.sum(data) indices = np.ogrid[[slice(0, i) for i in data.shape]] # note the output array is reversed to give (x, y) order return np.array([np.sum(indices[axis] * data) / total for axis in range(data.ndim)])[::-1]
[ "def", "centroid_com", "(", "data", ",", "mask", "=", "None", ")", ":", "data", "=", "data", ".", "astype", "(", "np", ".", "float", ")", "if", "mask", "is", "not", "None", "and", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "mask", "=", "np", ".", "asarray", "(", "mask", ",", "dtype", "=", "bool", ")", "if", "data", ".", "shape", "!=", "mask", ".", "shape", ":", "raise", "ValueError", "(", "'data and mask must have the same shape.'", ")", "data", "[", "mask", "]", "=", "0.", "badidx", "=", "~", "np", ".", "isfinite", "(", "data", ")", "if", "np", ".", "any", "(", "badidx", ")", ":", "warnings", ".", "warn", "(", "'Input data contains input values (e.g. NaNs or infs), '", "'which were automatically masked.'", ",", "AstropyUserWarning", ")", "data", "[", "badidx", "]", "=", "0.", "total", "=", "np", ".", "sum", "(", "data", ")", "indices", "=", "np", ".", "ogrid", "[", "[", "slice", "(", "0", ",", "i", ")", "for", "i", "in", "data", ".", "shape", "]", "]", "# note the output array is reversed to give (x, y) order", "return", "np", ".", "array", "(", "[", "np", ".", "sum", "(", "indices", "[", "axis", "]", "*", "data", ")", "/", "total", "for", "axis", "in", "range", "(", "data", ".", "ndim", ")", "]", ")", "[", ":", ":", "-", "1", "]" ]
Calculate the centroid of an n-dimensional array as its "center of mass" determined from moments. Invalid values (e.g. NaNs or infs) in the ``data`` array are automatically masked. Parameters ---------- data : array_like The input n-dimensional array. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The coordinates of the centroid in pixel order (e.g. ``(x, y)`` or ``(x, y, z)``), not numpy axis order.
[ "Calculate", "the", "centroid", "of", "an", "n", "-", "dimensional", "array", "as", "its", "center", "of", "mass", "determined", "from", "moments", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L74-L117
train
astropy/photutils
photutils/centroids/core.py
gaussian1d_moments
def gaussian1d_moments(data, mask=None): """ Estimate 1D Gaussian parameters from the moments of 1D data. This function can be useful for providing initial parameter values when fitting a 1D Gaussian to the ``data``. Parameters ---------- data : array_like (1D) The 1D array. mask : array_like (1D bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- amplitude, mean, stddev : float The estimated parameters of a 1D Gaussian. """ if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) else: data = np.ma.array(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask data.fill_value = 0. data = data.filled() x = np.arange(data.size) x_mean = np.sum(x * data) / np.sum(data) x_stddev = np.sqrt(abs(np.sum(data * (x - x_mean)**2) / np.sum(data))) amplitude = np.ptp(data) return amplitude, x_mean, x_stddev
python
def gaussian1d_moments(data, mask=None): """ Estimate 1D Gaussian parameters from the moments of 1D data. This function can be useful for providing initial parameter values when fitting a 1D Gaussian to the ``data``. Parameters ---------- data : array_like (1D) The 1D array. mask : array_like (1D bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- amplitude, mean, stddev : float The estimated parameters of a 1D Gaussian. """ if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) else: data = np.ma.array(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask data.fill_value = 0. data = data.filled() x = np.arange(data.size) x_mean = np.sum(x * data) / np.sum(data) x_stddev = np.sqrt(abs(np.sum(data * (x - x_mean)**2) / np.sum(data))) amplitude = np.ptp(data) return amplitude, x_mean, x_stddev
[ "def", "gaussian1d_moments", "(", "data", ",", "mask", "=", "None", ")", ":", "if", "np", ".", "any", "(", "~", "np", ".", "isfinite", "(", "data", ")", ")", ":", "data", "=", "np", ".", "ma", ".", "masked_invalid", "(", "data", ")", "warnings", ".", "warn", "(", "'Input data contains input values (e.g. NaNs or infs), '", "'which were automatically masked.'", ",", "AstropyUserWarning", ")", "else", ":", "data", "=", "np", ".", "ma", ".", "array", "(", "data", ")", "if", "mask", "is", "not", "None", "and", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "mask", "=", "np", ".", "asanyarray", "(", "mask", ")", "if", "data", ".", "shape", "!=", "mask", ".", "shape", ":", "raise", "ValueError", "(", "'data and mask must have the same shape.'", ")", "data", ".", "mask", "|=", "mask", "data", ".", "fill_value", "=", "0.", "data", "=", "data", ".", "filled", "(", ")", "x", "=", "np", ".", "arange", "(", "data", ".", "size", ")", "x_mean", "=", "np", ".", "sum", "(", "x", "*", "data", ")", "/", "np", ".", "sum", "(", "data", ")", "x_stddev", "=", "np", ".", "sqrt", "(", "abs", "(", "np", ".", "sum", "(", "data", "*", "(", "x", "-", "x_mean", ")", "**", "2", ")", "/", "np", ".", "sum", "(", "data", ")", ")", ")", "amplitude", "=", "np", ".", "ptp", "(", "data", ")", "return", "amplitude", ",", "x_mean", ",", "x_stddev" ]
Estimate 1D Gaussian parameters from the moments of 1D data. This function can be useful for providing initial parameter values when fitting a 1D Gaussian to the ``data``. Parameters ---------- data : array_like (1D) The 1D array. mask : array_like (1D bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- amplitude, mean, stddev : float The estimated parameters of a 1D Gaussian.
[ "Estimate", "1D", "Gaussian", "parameters", "from", "the", "moments", "of", "1D", "data", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L120-L163
train
astropy/photutils
photutils/centroids/core.py
fit_2dgaussian
def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian plus a constant to a 2D image. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- result : A `GaussianConst2D` model instance. The best-fitting Gaussian 2D model. """ from ..morphology import data_properties # prevent circular imports data = np.ma.asanyarray(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) if error is not None: error = np.ma.masked_invalid(error) if data.shape != error.shape: raise ValueError('data and error must have the same shape.') data.mask |= error.mask weights = 1.0 / error.clip(min=1.e-30) else: weights = np.ones(data.shape) if np.ma.count(data) < 7: raise ValueError('Input data must have a least 7 unmasked values to ' 'fit a 2D Gaussian plus a constant.') # assign zero weight to masked pixels if data.mask is not np.ma.nomask: weights[data.mask] = 0. mask = data.mask data.fill_value = 0.0 data = data.filled() # Subtract the minimum of the data as a crude background estimate. # This will also make the data values positive, preventing issues with # the moment estimation in data_properties (moments from negative data # values can yield undefined Gaussian parameters, e.g. x/y_stddev). props = data_properties(data - np.min(data), mask=mask) init_const = 0. # subtracted data minimum above init_amplitude = np.ptp(data) g_init = GaussianConst2D(constant=init_const, amplitude=init_amplitude, x_mean=props.xcentroid.value, y_mean=props.ycentroid.value, x_stddev=props.semimajor_axis_sigma.value, y_stddev=props.semiminor_axis_sigma.value, theta=props.orientation.value) fitter = LevMarLSQFitter() y, x = np.indices(data.shape) gfit = fitter(g_init, x, y, data, weights=weights) return gfit
python
def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian plus a constant to a 2D image. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- result : A `GaussianConst2D` model instance. The best-fitting Gaussian 2D model. """ from ..morphology import data_properties # prevent circular imports data = np.ma.asanyarray(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) if error is not None: error = np.ma.masked_invalid(error) if data.shape != error.shape: raise ValueError('data and error must have the same shape.') data.mask |= error.mask weights = 1.0 / error.clip(min=1.e-30) else: weights = np.ones(data.shape) if np.ma.count(data) < 7: raise ValueError('Input data must have a least 7 unmasked values to ' 'fit a 2D Gaussian plus a constant.') # assign zero weight to masked pixels if data.mask is not np.ma.nomask: weights[data.mask] = 0. mask = data.mask data.fill_value = 0.0 data = data.filled() # Subtract the minimum of the data as a crude background estimate. # This will also make the data values positive, preventing issues with # the moment estimation in data_properties (moments from negative data # values can yield undefined Gaussian parameters, e.g. x/y_stddev). props = data_properties(data - np.min(data), mask=mask) init_const = 0. # subtracted data minimum above init_amplitude = np.ptp(data) g_init = GaussianConst2D(constant=init_const, amplitude=init_amplitude, x_mean=props.xcentroid.value, y_mean=props.ycentroid.value, x_stddev=props.semimajor_axis_sigma.value, y_stddev=props.semiminor_axis_sigma.value, theta=props.orientation.value) fitter = LevMarLSQFitter() y, x = np.indices(data.shape) gfit = fitter(g_init, x, y, data, weights=weights) return gfit
[ "def", "fit_2dgaussian", "(", "data", ",", "error", "=", "None", ",", "mask", "=", "None", ")", ":", "from", ".", ".", "morphology", "import", "data_properties", "# prevent circular imports", "data", "=", "np", ".", "ma", ".", "asanyarray", "(", "data", ")", "if", "mask", "is", "not", "None", "and", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "mask", "=", "np", ".", "asanyarray", "(", "mask", ")", "if", "data", ".", "shape", "!=", "mask", ".", "shape", ":", "raise", "ValueError", "(", "'data and mask must have the same shape.'", ")", "data", ".", "mask", "|=", "mask", "if", "np", ".", "any", "(", "~", "np", ".", "isfinite", "(", "data", ")", ")", ":", "data", "=", "np", ".", "ma", ".", "masked_invalid", "(", "data", ")", "warnings", ".", "warn", "(", "'Input data contains input values (e.g. NaNs or infs), '", "'which were automatically masked.'", ",", "AstropyUserWarning", ")", "if", "error", "is", "not", "None", ":", "error", "=", "np", ".", "ma", ".", "masked_invalid", "(", "error", ")", "if", "data", ".", "shape", "!=", "error", ".", "shape", ":", "raise", "ValueError", "(", "'data and error must have the same shape.'", ")", "data", ".", "mask", "|=", "error", ".", "mask", "weights", "=", "1.0", "/", "error", ".", "clip", "(", "min", "=", "1.e-30", ")", "else", ":", "weights", "=", "np", ".", "ones", "(", "data", ".", "shape", ")", "if", "np", ".", "ma", ".", "count", "(", "data", ")", "<", "7", ":", "raise", "ValueError", "(", "'Input data must have a least 7 unmasked values to '", "'fit a 2D Gaussian plus a constant.'", ")", "# assign zero weight to masked pixels", "if", "data", ".", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "weights", "[", "data", ".", "mask", "]", "=", "0.", "mask", "=", "data", ".", "mask", "data", ".", "fill_value", "=", "0.0", "data", "=", "data", ".", "filled", "(", ")", "# Subtract the minimum of the data as a crude background estimate.", "# This will also make the data values positive, preventing issues with", "# the moment estimation in data_properties (moments from negative data", "# values can yield undefined Gaussian parameters, e.g. x/y_stddev).", "props", "=", "data_properties", "(", "data", "-", "np", ".", "min", "(", "data", ")", ",", "mask", "=", "mask", ")", "init_const", "=", "0.", "# subtracted data minimum above", "init_amplitude", "=", "np", ".", "ptp", "(", "data", ")", "g_init", "=", "GaussianConst2D", "(", "constant", "=", "init_const", ",", "amplitude", "=", "init_amplitude", ",", "x_mean", "=", "props", ".", "xcentroid", ".", "value", ",", "y_mean", "=", "props", ".", "ycentroid", ".", "value", ",", "x_stddev", "=", "props", ".", "semimajor_axis_sigma", ".", "value", ",", "y_stddev", "=", "props", ".", "semiminor_axis_sigma", ".", "value", ",", "theta", "=", "props", ".", "orientation", ".", "value", ")", "fitter", "=", "LevMarLSQFitter", "(", ")", "y", ",", "x", "=", "np", ".", "indices", "(", "data", ".", "shape", ")", "gfit", "=", "fitter", "(", "g_init", ",", "x", ",", "y", ",", "data", ",", "weights", "=", "weights", ")", "return", "gfit" ]
Fit a 2D Gaussian plus a constant to a 2D image. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- result : A `GaussianConst2D` model instance. The best-fitting Gaussian 2D model.
[ "Fit", "a", "2D", "Gaussian", "plus", "a", "constant", "to", "a", "2D", "image", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L166-L247
train
astropy/photutils
photutils/centroids/core.py
centroid_1dg
def centroid_1dg(data, error=None, mask=None): """ Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal ``x`` and ``y`` distributions of the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D data array. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The ``x, y`` coordinates of the centroid. """ data = np.ma.asanyarray(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) if error is not None: error = np.ma.masked_invalid(error) if data.shape != error.shape: raise ValueError('data and error must have the same shape.') data.mask |= error.mask error.mask = data.mask xy_error = np.array([np.sqrt(np.ma.sum(error**2, axis=i)) for i in [0, 1]]) xy_weights = [(1.0 / xy_error[i].clip(min=1.e-30)) for i in [0, 1]] else: xy_weights = [np.ones(data.shape[i]) for i in [1, 0]] # assign zero weight to masked pixels if data.mask is not np.ma.nomask: bad_idx = [np.all(data.mask, axis=i) for i in [0, 1]] for i in [0, 1]: xy_weights[i][bad_idx[i]] = 0. xy_data = np.array([np.ma.sum(data, axis=i) for i in [0, 1]]) constant_init = np.ma.min(data) centroid = [] for (data_i, weights_i) in zip(xy_data, xy_weights): params_init = gaussian1d_moments(data_i) g_init = Const1D(constant_init) + Gaussian1D(*params_init) fitter = LevMarLSQFitter() x = np.arange(data_i.size) g_fit = fitter(g_init, x, data_i, weights=weights_i) centroid.append(g_fit.mean_1.value) return np.array(centroid)
python
def centroid_1dg(data, error=None, mask=None): """ Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal ``x`` and ``y`` distributions of the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D data array. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The ``x, y`` coordinates of the centroid. """ data = np.ma.asanyarray(data) if mask is not None and mask is not np.ma.nomask: mask = np.asanyarray(mask) if data.shape != mask.shape: raise ValueError('data and mask must have the same shape.') data.mask |= mask if np.any(~np.isfinite(data)): data = np.ma.masked_invalid(data) warnings.warn('Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.', AstropyUserWarning) if error is not None: error = np.ma.masked_invalid(error) if data.shape != error.shape: raise ValueError('data and error must have the same shape.') data.mask |= error.mask error.mask = data.mask xy_error = np.array([np.sqrt(np.ma.sum(error**2, axis=i)) for i in [0, 1]]) xy_weights = [(1.0 / xy_error[i].clip(min=1.e-30)) for i in [0, 1]] else: xy_weights = [np.ones(data.shape[i]) for i in [1, 0]] # assign zero weight to masked pixels if data.mask is not np.ma.nomask: bad_idx = [np.all(data.mask, axis=i) for i in [0, 1]] for i in [0, 1]: xy_weights[i][bad_idx[i]] = 0. xy_data = np.array([np.ma.sum(data, axis=i) for i in [0, 1]]) constant_init = np.ma.min(data) centroid = [] for (data_i, weights_i) in zip(xy_data, xy_weights): params_init = gaussian1d_moments(data_i) g_init = Const1D(constant_init) + Gaussian1D(*params_init) fitter = LevMarLSQFitter() x = np.arange(data_i.size) g_fit = fitter(g_init, x, data_i, weights=weights_i) centroid.append(g_fit.mean_1.value) return np.array(centroid)
[ "def", "centroid_1dg", "(", "data", ",", "error", "=", "None", ",", "mask", "=", "None", ")", ":", "data", "=", "np", ".", "ma", ".", "asanyarray", "(", "data", ")", "if", "mask", "is", "not", "None", "and", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "mask", "=", "np", ".", "asanyarray", "(", "mask", ")", "if", "data", ".", "shape", "!=", "mask", ".", "shape", ":", "raise", "ValueError", "(", "'data and mask must have the same shape.'", ")", "data", ".", "mask", "|=", "mask", "if", "np", ".", "any", "(", "~", "np", ".", "isfinite", "(", "data", ")", ")", ":", "data", "=", "np", ".", "ma", ".", "masked_invalid", "(", "data", ")", "warnings", ".", "warn", "(", "'Input data contains input values (e.g. NaNs or infs), '", "'which were automatically masked.'", ",", "AstropyUserWarning", ")", "if", "error", "is", "not", "None", ":", "error", "=", "np", ".", "ma", ".", "masked_invalid", "(", "error", ")", "if", "data", ".", "shape", "!=", "error", ".", "shape", ":", "raise", "ValueError", "(", "'data and error must have the same shape.'", ")", "data", ".", "mask", "|=", "error", ".", "mask", "error", ".", "mask", "=", "data", ".", "mask", "xy_error", "=", "np", ".", "array", "(", "[", "np", ".", "sqrt", "(", "np", ".", "ma", ".", "sum", "(", "error", "**", "2", ",", "axis", "=", "i", ")", ")", "for", "i", "in", "[", "0", ",", "1", "]", "]", ")", "xy_weights", "=", "[", "(", "1.0", "/", "xy_error", "[", "i", "]", ".", "clip", "(", "min", "=", "1.e-30", ")", ")", "for", "i", "in", "[", "0", ",", "1", "]", "]", "else", ":", "xy_weights", "=", "[", "np", ".", "ones", "(", "data", ".", "shape", "[", "i", "]", ")", "for", "i", "in", "[", "1", ",", "0", "]", "]", "# assign zero weight to masked pixels", "if", "data", ".", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "bad_idx", "=", "[", "np", ".", "all", "(", "data", ".", "mask", ",", "axis", "=", "i", ")", "for", "i", "in", "[", "0", ",", "1", "]", "]", "for", "i", "in", "[", "0", ",", "1", "]", ":", "xy_weights", "[", "i", "]", "[", "bad_idx", "[", "i", "]", "]", "=", "0.", "xy_data", "=", "np", ".", "array", "(", "[", "np", ".", "ma", ".", "sum", "(", "data", ",", "axis", "=", "i", ")", "for", "i", "in", "[", "0", ",", "1", "]", "]", ")", "constant_init", "=", "np", ".", "ma", ".", "min", "(", "data", ")", "centroid", "=", "[", "]", "for", "(", "data_i", ",", "weights_i", ")", "in", "zip", "(", "xy_data", ",", "xy_weights", ")", ":", "params_init", "=", "gaussian1d_moments", "(", "data_i", ")", "g_init", "=", "Const1D", "(", "constant_init", ")", "+", "Gaussian1D", "(", "*", "params_init", ")", "fitter", "=", "LevMarLSQFitter", "(", ")", "x", "=", "np", ".", "arange", "(", "data_i", ".", "size", ")", "g_fit", "=", "fitter", "(", "g_init", ",", "x", ",", "data_i", ",", "weights", "=", "weights_i", ")", "centroid", ".", "append", "(", "g_fit", ".", "mean_1", ".", "value", ")", "return", "np", ".", "array", "(", "centroid", ")" ]
Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal ``x`` and ``y`` distributions of the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``error`` arrays. Parameters ---------- data : array_like The 2D data array. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optional A boolean mask, with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Returns ------- centroid : `~numpy.ndarray` The ``x, y`` coordinates of the centroid.
[ "Calculate", "the", "centroid", "of", "a", "2D", "array", "by", "fitting", "1D", "Gaussians", "to", "the", "marginal", "x", "and", "y", "distributions", "of", "the", "array", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L250-L322
train
astropy/photutils
photutils/centroids/core.py
centroid_sources
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None, error=None, mask=None, centroid_func=centroid_com): """ Calculate the centroid of sources at the defined positions. A cutout image centered on each input position will be used to calculate the centroid position. The cutout image is defined either using the ``box_size`` or ``footprint`` keyword. The ``footprint`` keyword can be used to create a non-rectangular cutout image. Parameters ---------- data : array_like The 2D array of the image. xpos, ypos : float or array-like of float The initial ``x`` and ``y`` pixel position(s) of the center position. A cutout image centered on this position be used to calculate the centroid. box_size : int or array-like of int, optional The size of the cutout image along each axis. If ``box_size`` is a number, then a square cutout of ``box_size`` will be created. If ``box_size`` has two elements, they should be in ``(ny, nx)`` order. footprint : `~numpy.ndarray` of bools, optional A 2D boolean array where `True` values describe the local footprint region to cutout. ``footprint`` can be used to create a non-rectangular cutout image, in which case the input ``xpos`` and ``ypos`` represent the center of the minimal bounding box for the input ``footprint``. ``box_size=(n, m)`` is equivalent to ``footprint=np.ones((n, m))``. Either ``box_size`` or ``footprint`` must be defined. If they are both defined, then ``footprint`` overrides ``box_size``. mask : array_like, bool, optional A 2D boolean array with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. ``error`` must have the same shape as ``data``. ``error`` will be used only if supported by the input ``centroid_func``. centroid_func : callable, optional A callable object (e.g. function or class) that is used to calculate the centroid of a 2D array. The ``centroid_func`` must accept a 2D `~numpy.ndarray`, have a ``mask`` keyword and optionally an ``error`` keyword. The callable object must return a tuple of two 1D `~numpy.ndarray`\\s, representing the x and y centroids. The default is `~photutils.centroids.centroid_com`. Returns ------- xcentroid, ycentroid : `~numpy.ndarray` The ``x`` and ``y`` pixel position(s) of the centroids. """ xpos = np.atleast_1d(xpos) ypos = np.atleast_1d(ypos) if xpos.ndim != 1: raise ValueError('xpos must be a 1D array.') if ypos.ndim != 1: raise ValueError('ypos must be a 1D array.') if footprint is None: if box_size is None: raise ValueError('box_size or footprint must be defined.') else: box_size = np.atleast_1d(box_size) if len(box_size) == 1: box_size = np.repeat(box_size, 2) if len(box_size) != 2: raise ValueError('box_size must have 1 or 2 elements.') footprint = np.ones(box_size, dtype=bool) else: footprint = np.asanyarray(footprint, dtype=bool) if footprint.ndim != 2: raise ValueError('footprint must be a 2D array.') use_error = False spec = inspect.getfullargspec(centroid_func) if 'mask' not in spec.args: raise ValueError('The input "centroid_func" must have a "mask" ' 'keyword.') if 'error' in spec.args: use_error = True xcentroids = [] ycentroids = [] for xp, yp in zip(xpos, ypos): slices_large, slices_small = overlap_slices(data.shape, footprint.shape, (yp, xp)) data_cutout = data[slices_large] mask_cutout = None if mask is not None: mask_cutout = mask[slices_large] footprint_mask = ~footprint # trim footprint mask if partial overlap on the data footprint_mask = footprint_mask[slices_small] if mask_cutout is None: mask_cutout = footprint_mask else: # combine the input mask and footprint mask mask_cutout = np.logical_or(mask_cutout, footprint_mask) if error is not None and use_error: error_cutout = error[slices_large] xcen, ycen = centroid_func(data_cutout, mask=mask_cutout, error=error_cutout) else: xcen, ycen = centroid_func(data_cutout, mask=mask_cutout) xcentroids.append(xcen + slices_large[1].start) ycentroids.append(ycen + slices_large[0].start) return np.array(xcentroids), np.array(ycentroids)
python
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None, error=None, mask=None, centroid_func=centroid_com): """ Calculate the centroid of sources at the defined positions. A cutout image centered on each input position will be used to calculate the centroid position. The cutout image is defined either using the ``box_size`` or ``footprint`` keyword. The ``footprint`` keyword can be used to create a non-rectangular cutout image. Parameters ---------- data : array_like The 2D array of the image. xpos, ypos : float or array-like of float The initial ``x`` and ``y`` pixel position(s) of the center position. A cutout image centered on this position be used to calculate the centroid. box_size : int or array-like of int, optional The size of the cutout image along each axis. If ``box_size`` is a number, then a square cutout of ``box_size`` will be created. If ``box_size`` has two elements, they should be in ``(ny, nx)`` order. footprint : `~numpy.ndarray` of bools, optional A 2D boolean array where `True` values describe the local footprint region to cutout. ``footprint`` can be used to create a non-rectangular cutout image, in which case the input ``xpos`` and ``ypos`` represent the center of the minimal bounding box for the input ``footprint``. ``box_size=(n, m)`` is equivalent to ``footprint=np.ones((n, m))``. Either ``box_size`` or ``footprint`` must be defined. If they are both defined, then ``footprint`` overrides ``box_size``. mask : array_like, bool, optional A 2D boolean array with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. ``error`` must have the same shape as ``data``. ``error`` will be used only if supported by the input ``centroid_func``. centroid_func : callable, optional A callable object (e.g. function or class) that is used to calculate the centroid of a 2D array. The ``centroid_func`` must accept a 2D `~numpy.ndarray`, have a ``mask`` keyword and optionally an ``error`` keyword. The callable object must return a tuple of two 1D `~numpy.ndarray`\\s, representing the x and y centroids. The default is `~photutils.centroids.centroid_com`. Returns ------- xcentroid, ycentroid : `~numpy.ndarray` The ``x`` and ``y`` pixel position(s) of the centroids. """ xpos = np.atleast_1d(xpos) ypos = np.atleast_1d(ypos) if xpos.ndim != 1: raise ValueError('xpos must be a 1D array.') if ypos.ndim != 1: raise ValueError('ypos must be a 1D array.') if footprint is None: if box_size is None: raise ValueError('box_size or footprint must be defined.') else: box_size = np.atleast_1d(box_size) if len(box_size) == 1: box_size = np.repeat(box_size, 2) if len(box_size) != 2: raise ValueError('box_size must have 1 or 2 elements.') footprint = np.ones(box_size, dtype=bool) else: footprint = np.asanyarray(footprint, dtype=bool) if footprint.ndim != 2: raise ValueError('footprint must be a 2D array.') use_error = False spec = inspect.getfullargspec(centroid_func) if 'mask' not in spec.args: raise ValueError('The input "centroid_func" must have a "mask" ' 'keyword.') if 'error' in spec.args: use_error = True xcentroids = [] ycentroids = [] for xp, yp in zip(xpos, ypos): slices_large, slices_small = overlap_slices(data.shape, footprint.shape, (yp, xp)) data_cutout = data[slices_large] mask_cutout = None if mask is not None: mask_cutout = mask[slices_large] footprint_mask = ~footprint # trim footprint mask if partial overlap on the data footprint_mask = footprint_mask[slices_small] if mask_cutout is None: mask_cutout = footprint_mask else: # combine the input mask and footprint mask mask_cutout = np.logical_or(mask_cutout, footprint_mask) if error is not None and use_error: error_cutout = error[slices_large] xcen, ycen = centroid_func(data_cutout, mask=mask_cutout, error=error_cutout) else: xcen, ycen = centroid_func(data_cutout, mask=mask_cutout) xcentroids.append(xcen + slices_large[1].start) ycentroids.append(ycen + slices_large[0].start) return np.array(xcentroids), np.array(ycentroids)
[ "def", "centroid_sources", "(", "data", ",", "xpos", ",", "ypos", ",", "box_size", "=", "11", ",", "footprint", "=", "None", ",", "error", "=", "None", ",", "mask", "=", "None", ",", "centroid_func", "=", "centroid_com", ")", ":", "xpos", "=", "np", ".", "atleast_1d", "(", "xpos", ")", "ypos", "=", "np", ".", "atleast_1d", "(", "ypos", ")", "if", "xpos", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "'xpos must be a 1D array.'", ")", "if", "ypos", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "'ypos must be a 1D array.'", ")", "if", "footprint", "is", "None", ":", "if", "box_size", "is", "None", ":", "raise", "ValueError", "(", "'box_size or footprint must be defined.'", ")", "else", ":", "box_size", "=", "np", ".", "atleast_1d", "(", "box_size", ")", "if", "len", "(", "box_size", ")", "==", "1", ":", "box_size", "=", "np", ".", "repeat", "(", "box_size", ",", "2", ")", "if", "len", "(", "box_size", ")", "!=", "2", ":", "raise", "ValueError", "(", "'box_size must have 1 or 2 elements.'", ")", "footprint", "=", "np", ".", "ones", "(", "box_size", ",", "dtype", "=", "bool", ")", "else", ":", "footprint", "=", "np", ".", "asanyarray", "(", "footprint", ",", "dtype", "=", "bool", ")", "if", "footprint", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'footprint must be a 2D array.'", ")", "use_error", "=", "False", "spec", "=", "inspect", ".", "getfullargspec", "(", "centroid_func", ")", "if", "'mask'", "not", "in", "spec", ".", "args", ":", "raise", "ValueError", "(", "'The input \"centroid_func\" must have a \"mask\" '", "'keyword.'", ")", "if", "'error'", "in", "spec", ".", "args", ":", "use_error", "=", "True", "xcentroids", "=", "[", "]", "ycentroids", "=", "[", "]", "for", "xp", ",", "yp", "in", "zip", "(", "xpos", ",", "ypos", ")", ":", "slices_large", ",", "slices_small", "=", "overlap_slices", "(", "data", ".", "shape", ",", "footprint", ".", "shape", ",", "(", "yp", ",", "xp", ")", ")", "data_cutout", "=", "data", "[", "slices_large", "]", "mask_cutout", "=", "None", "if", "mask", "is", "not", "None", ":", "mask_cutout", "=", "mask", "[", "slices_large", "]", "footprint_mask", "=", "~", "footprint", "# trim footprint mask if partial overlap on the data", "footprint_mask", "=", "footprint_mask", "[", "slices_small", "]", "if", "mask_cutout", "is", "None", ":", "mask_cutout", "=", "footprint_mask", "else", ":", "# combine the input mask and footprint mask", "mask_cutout", "=", "np", ".", "logical_or", "(", "mask_cutout", ",", "footprint_mask", ")", "if", "error", "is", "not", "None", "and", "use_error", ":", "error_cutout", "=", "error", "[", "slices_large", "]", "xcen", ",", "ycen", "=", "centroid_func", "(", "data_cutout", ",", "mask", "=", "mask_cutout", ",", "error", "=", "error_cutout", ")", "else", ":", "xcen", ",", "ycen", "=", "centroid_func", "(", "data_cutout", ",", "mask", "=", "mask_cutout", ")", "xcentroids", ".", "append", "(", "xcen", "+", "slices_large", "[", "1", "]", ".", "start", ")", "ycentroids", ".", "append", "(", "ycen", "+", "slices_large", "[", "0", "]", ".", "start", ")", "return", "np", ".", "array", "(", "xcentroids", ")", ",", "np", ".", "array", "(", "ycentroids", ")" ]
Calculate the centroid of sources at the defined positions. A cutout image centered on each input position will be used to calculate the centroid position. The cutout image is defined either using the ``box_size`` or ``footprint`` keyword. The ``footprint`` keyword can be used to create a non-rectangular cutout image. Parameters ---------- data : array_like The 2D array of the image. xpos, ypos : float or array-like of float The initial ``x`` and ``y`` pixel position(s) of the center position. A cutout image centered on this position be used to calculate the centroid. box_size : int or array-like of int, optional The size of the cutout image along each axis. If ``box_size`` is a number, then a square cutout of ``box_size`` will be created. If ``box_size`` has two elements, they should be in ``(ny, nx)`` order. footprint : `~numpy.ndarray` of bools, optional A 2D boolean array where `True` values describe the local footprint region to cutout. ``footprint`` can be used to create a non-rectangular cutout image, in which case the input ``xpos`` and ``ypos`` represent the center of the minimal bounding box for the input ``footprint``. ``box_size=(n, m)`` is equivalent to ``footprint=np.ones((n, m))``. Either ``box_size`` or ``footprint`` must be defined. If they are both defined, then ``footprint`` overrides ``box_size``. mask : array_like, bool, optional A 2D boolean array with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. ``error`` must have the same shape as ``data``. ``error`` will be used only if supported by the input ``centroid_func``. centroid_func : callable, optional A callable object (e.g. function or class) that is used to calculate the centroid of a 2D array. The ``centroid_func`` must accept a 2D `~numpy.ndarray`, have a ``mask`` keyword and optionally an ``error`` keyword. The callable object must return a tuple of two 1D `~numpy.ndarray`\\s, representing the x and y centroids. The default is `~photutils.centroids.centroid_com`. Returns ------- xcentroid, ycentroid : `~numpy.ndarray` The ``x`` and ``y`` pixel position(s) of the centroids.
[ "Calculate", "the", "centroid", "of", "sources", "at", "the", "defined", "positions", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L358-L481
train
astropy/photutils
photutils/centroids/core.py
GaussianConst2D.evaluate
def evaluate(x, y, constant, amplitude, x_mean, y_mean, x_stddev, y_stddev, theta): """Two dimensional Gaussian plus constant function.""" model = Const2D(constant)(x, y) + Gaussian2D(amplitude, x_mean, y_mean, x_stddev, y_stddev, theta)(x, y) return model
python
def evaluate(x, y, constant, amplitude, x_mean, y_mean, x_stddev, y_stddev, theta): """Two dimensional Gaussian plus constant function.""" model = Const2D(constant)(x, y) + Gaussian2D(amplitude, x_mean, y_mean, x_stddev, y_stddev, theta)(x, y) return model
[ "def", "evaluate", "(", "x", ",", "y", ",", "constant", ",", "amplitude", ",", "x_mean", ",", "y_mean", ",", "x_stddev", ",", "y_stddev", ",", "theta", ")", ":", "model", "=", "Const2D", "(", "constant", ")", "(", "x", ",", "y", ")", "+", "Gaussian2D", "(", "amplitude", ",", "x_mean", ",", "y_mean", ",", "x_stddev", ",", "y_stddev", ",", "theta", ")", "(", "x", ",", "y", ")", "return", "model" ]
Two dimensional Gaussian plus constant function.
[ "Two", "dimensional", "Gaussian", "plus", "constant", "function", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/centroids/core.py#L61-L68
train
astropy/photutils
photutils/psf/sandbox.py
DiscretePRF.evaluate
def evaluate(self, x, y, flux, x_0, y_0): """ Discrete PRF model evaluation. Given a certain position and flux the corresponding image of the PSF is chosen and scaled to the flux. If x and y are outside the boundaries of the image, zero will be returned. Parameters ---------- x : float x coordinate array in pixel coordinates. y : float y coordinate array in pixel coordinates. flux : float Model flux. x_0 : float x position of the center of the PRF. y_0 : float y position of the center of the PRF. """ # Convert x and y to index arrays x = (x - x_0 + 0.5 + self.prf_shape[1] // 2).astype('int') y = (y - y_0 + 0.5 + self.prf_shape[0] // 2).astype('int') # Get subpixel indices y_sub, x_sub = subpixel_indices((y_0, x_0), self.subsampling) # Out of boundary masks x_bound = np.logical_or(x < 0, x >= self.prf_shape[1]) y_bound = np.logical_or(y < 0, y >= self.prf_shape[0]) out_of_bounds = np.logical_or(x_bound, y_bound) # Set out of boundary indices to zero x[x_bound] = 0 y[y_bound] = 0 result = flux * self._prf_array[int(y_sub), int(x_sub)][y, x] # Set out of boundary values to zero result[out_of_bounds] = 0 return result
python
def evaluate(self, x, y, flux, x_0, y_0): """ Discrete PRF model evaluation. Given a certain position and flux the corresponding image of the PSF is chosen and scaled to the flux. If x and y are outside the boundaries of the image, zero will be returned. Parameters ---------- x : float x coordinate array in pixel coordinates. y : float y coordinate array in pixel coordinates. flux : float Model flux. x_0 : float x position of the center of the PRF. y_0 : float y position of the center of the PRF. """ # Convert x and y to index arrays x = (x - x_0 + 0.5 + self.prf_shape[1] // 2).astype('int') y = (y - y_0 + 0.5 + self.prf_shape[0] // 2).astype('int') # Get subpixel indices y_sub, x_sub = subpixel_indices((y_0, x_0), self.subsampling) # Out of boundary masks x_bound = np.logical_or(x < 0, x >= self.prf_shape[1]) y_bound = np.logical_or(y < 0, y >= self.prf_shape[0]) out_of_bounds = np.logical_or(x_bound, y_bound) # Set out of boundary indices to zero x[x_bound] = 0 y[y_bound] = 0 result = flux * self._prf_array[int(y_sub), int(x_sub)][y, x] # Set out of boundary values to zero result[out_of_bounds] = 0 return result
[ "def", "evaluate", "(", "self", ",", "x", ",", "y", ",", "flux", ",", "x_0", ",", "y_0", ")", ":", "# Convert x and y to index arrays", "x", "=", "(", "x", "-", "x_0", "+", "0.5", "+", "self", ".", "prf_shape", "[", "1", "]", "//", "2", ")", ".", "astype", "(", "'int'", ")", "y", "=", "(", "y", "-", "y_0", "+", "0.5", "+", "self", ".", "prf_shape", "[", "0", "]", "//", "2", ")", ".", "astype", "(", "'int'", ")", "# Get subpixel indices", "y_sub", ",", "x_sub", "=", "subpixel_indices", "(", "(", "y_0", ",", "x_0", ")", ",", "self", ".", "subsampling", ")", "# Out of boundary masks", "x_bound", "=", "np", ".", "logical_or", "(", "x", "<", "0", ",", "x", ">=", "self", ".", "prf_shape", "[", "1", "]", ")", "y_bound", "=", "np", ".", "logical_or", "(", "y", "<", "0", ",", "y", ">=", "self", ".", "prf_shape", "[", "0", "]", ")", "out_of_bounds", "=", "np", ".", "logical_or", "(", "x_bound", ",", "y_bound", ")", "# Set out of boundary indices to zero", "x", "[", "x_bound", "]", "=", "0", "y", "[", "y_bound", "]", "=", "0", "result", "=", "flux", "*", "self", ".", "_prf_array", "[", "int", "(", "y_sub", ")", ",", "int", "(", "x_sub", ")", "]", "[", "y", ",", "x", "]", "# Set out of boundary values to zero", "result", "[", "out_of_bounds", "]", "=", "0", "return", "result" ]
Discrete PRF model evaluation. Given a certain position and flux the corresponding image of the PSF is chosen and scaled to the flux. If x and y are outside the boundaries of the image, zero will be returned. Parameters ---------- x : float x coordinate array in pixel coordinates. y : float y coordinate array in pixel coordinates. flux : float Model flux. x_0 : float x position of the center of the PRF. y_0 : float y position of the center of the PRF.
[ "Discrete", "PRF", "model", "evaluation", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/sandbox.py#L104-L145
train
astropy/photutils
photutils/psf/sandbox.py
Reproject._reproject
def _reproject(wcs1, wcs2): """ Perform the forward transformation of ``wcs1`` followed by the inverse transformation of ``wcs2``. Parameters ---------- wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS` The WCS objects. Returns ------- result : func Function to compute the transformations. It takes x, y positions in ``wcs1`` and returns x, y positions in ``wcs2``. The input and output x, y positions are zero indexed. """ import gwcs forward_origin = [] if isinstance(wcs1, fitswcs.WCS): forward = wcs1.all_pix2world forward_origin = [0] elif isinstance(wcs2, gwcs.wcs.WCS): forward = wcs1.forward_transform else: raise ValueError('wcs1 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS object.') inverse_origin = [] if isinstance(wcs2, fitswcs.WCS): inverse = wcs2.all_world2pix inverse_origin = [0] elif isinstance(wcs2, gwcs.wcs.WCS): inverse = wcs2.forward_transform.inverse else: raise ValueError('wcs2 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS object.') def _reproject_func(x, y): forward_args = [x, y] + forward_origin sky = forward(*forward_args) inverse_args = sky + inverse_origin return inverse(*inverse_args) return _reproject_func
python
def _reproject(wcs1, wcs2): """ Perform the forward transformation of ``wcs1`` followed by the inverse transformation of ``wcs2``. Parameters ---------- wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS` The WCS objects. Returns ------- result : func Function to compute the transformations. It takes x, y positions in ``wcs1`` and returns x, y positions in ``wcs2``. The input and output x, y positions are zero indexed. """ import gwcs forward_origin = [] if isinstance(wcs1, fitswcs.WCS): forward = wcs1.all_pix2world forward_origin = [0] elif isinstance(wcs2, gwcs.wcs.WCS): forward = wcs1.forward_transform else: raise ValueError('wcs1 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS object.') inverse_origin = [] if isinstance(wcs2, fitswcs.WCS): inverse = wcs2.all_world2pix inverse_origin = [0] elif isinstance(wcs2, gwcs.wcs.WCS): inverse = wcs2.forward_transform.inverse else: raise ValueError('wcs2 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS object.') def _reproject_func(x, y): forward_args = [x, y] + forward_origin sky = forward(*forward_args) inverse_args = sky + inverse_origin return inverse(*inverse_args) return _reproject_func
[ "def", "_reproject", "(", "wcs1", ",", "wcs2", ")", ":", "import", "gwcs", "forward_origin", "=", "[", "]", "if", "isinstance", "(", "wcs1", ",", "fitswcs", ".", "WCS", ")", ":", "forward", "=", "wcs1", ".", "all_pix2world", "forward_origin", "=", "[", "0", "]", "elif", "isinstance", "(", "wcs2", ",", "gwcs", ".", "wcs", ".", "WCS", ")", ":", "forward", "=", "wcs1", ".", "forward_transform", "else", ":", "raise", "ValueError", "(", "'wcs1 must be an astropy.wcs.WCS or '", "'gwcs.wcs.WCS object.'", ")", "inverse_origin", "=", "[", "]", "if", "isinstance", "(", "wcs2", ",", "fitswcs", ".", "WCS", ")", ":", "inverse", "=", "wcs2", ".", "all_world2pix", "inverse_origin", "=", "[", "0", "]", "elif", "isinstance", "(", "wcs2", ",", "gwcs", ".", "wcs", ".", "WCS", ")", ":", "inverse", "=", "wcs2", ".", "forward_transform", ".", "inverse", "else", ":", "raise", "ValueError", "(", "'wcs2 must be an astropy.wcs.WCS or '", "'gwcs.wcs.WCS object.'", ")", "def", "_reproject_func", "(", "x", ",", "y", ")", ":", "forward_args", "=", "[", "x", ",", "y", "]", "+", "forward_origin", "sky", "=", "forward", "(", "*", "forward_args", ")", "inverse_args", "=", "sky", "+", "inverse_origin", "return", "inverse", "(", "*", "inverse_args", ")", "return", "_reproject_func" ]
Perform the forward transformation of ``wcs1`` followed by the inverse transformation of ``wcs2``. Parameters ---------- wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS` The WCS objects. Returns ------- result : func Function to compute the transformations. It takes x, y positions in ``wcs1`` and returns x, y positions in ``wcs2``. The input and output x, y positions are zero indexed.
[ "Perform", "the", "forward", "transformation", "of", "wcs1", "followed", "by", "the", "inverse", "transformation", "of", "wcs2", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/sandbox.py#L316-L363
train
astropy/photutils
photutils/utils/misc.py
get_version_info
def get_version_info(): """ Return astropy and photutils versions. Returns ------- result : str The astropy and photutils versions. """ from astropy import __version__ astropy_version = __version__ from photutils import __version__ photutils_version = __version__ return 'astropy: {0}, photutils: {1}'.format(astropy_version, photutils_version)
python
def get_version_info(): """ Return astropy and photutils versions. Returns ------- result : str The astropy and photutils versions. """ from astropy import __version__ astropy_version = __version__ from photutils import __version__ photutils_version = __version__ return 'astropy: {0}, photutils: {1}'.format(astropy_version, photutils_version)
[ "def", "get_version_info", "(", ")", ":", "from", "astropy", "import", "__version__", "astropy_version", "=", "__version__", "from", "photutils", "import", "__version__", "photutils_version", "=", "__version__", "return", "'astropy: {0}, photutils: {1}'", ".", "format", "(", "astropy_version", ",", "photutils_version", ")" ]
Return astropy and photutils versions. Returns ------- result : str The astropy and photutils versions.
[ "Return", "astropy", "and", "photutils", "versions", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/misc.py#L15-L32
train
astropy/photutils
photutils/utils/errors.py
calc_total_error
def calc_total_error(data, bkg_error, effective_gain): """ Calculate a total error array, combining a background-only error array with the Poisson noise of sources. Parameters ---------- data : array_like or `~astropy.units.Quantity` The data array. bkg_error : array_like or `~astropy.units.Quantity` The pixel-wise Gaussian 1-sigma background-only errors of the input ``data``. ``bkg_error`` should include all sources of "background" error but *exclude* the Poisson error of the sources. ``bkg_error`` must have the same shape as ``data``. If ``data`` and ``bkg_error`` are `~astropy.units.Quantity` objects, then they must have the same units. effective_gain : float, array-like, or `~astropy.units.Quantity` Ratio of counts (e.g., electrons or photons) to the units of ``data`` used to calculate the Poisson error of the sources. Returns ------- total_error : `~numpy.ndarray` or `~astropy.units.Quantity` The total error array. If ``data``, ``bkg_error``, and ``effective_gain`` are all `~astropy.units.Quantity` objects, then ``total_error`` will also be returned as a `~astropy.units.Quantity` object with the same units as the input ``data``. Otherwise, a `~numpy.ndarray` will be returned. Notes ----- To use units, ``data``, ``bkg_error``, and ``effective_gain`` must *all* be `~astropy.units.Quantity` objects. ``data`` and ``bkg_error`` must have the same units. A `ValueError` will be raised if only some of the inputs are `~astropy.units.Quantity` objects or if the ``data`` and ``bkg_error`` units differ. The total error array, :math:`\\sigma_{\\mathrm{tot}}` is: .. math:: \\sigma_{\\mathrm{tot}} = \\sqrt{\\sigma_{\\mathrm{b}}^2 + \\frac{I}{g}} where :math:`\\sigma_b`, :math:`I`, and :math:`g` are the background ``bkg_error`` image, ``data`` image, and ``effective_gain``, respectively. Pixels where ``data`` (:math:`I_i)` is negative do not contribute additional Poisson noise to the total error, i.e. :math:`\\sigma_{\\mathrm{tot}, i} = \\sigma_{\\mathrm{b}, i}`. Note that this is different from `SExtractor`_, which sums the total variance in the segment, including pixels where :math:`I_i` is negative. In such cases, `SExtractor`_ underestimates the total errors. Also note that SExtractor computes Poisson errors from background-subtracted data, which also results in an underestimation of the Poisson noise. ``effective_gain`` can either be a scalar value or a 2D image with the same shape as the ``data``. A 2D image is useful with mosaic images that have variable depths (i.e., exposure times) across the field. For example, one should use an exposure-time map as the ``effective_gain`` for a variable depth mosaic image in count-rate units. As an example, if your input ``data`` are in units of ADU, then ``effective_gain`` should be in units of electrons/ADU (or photons/ADU). If your input ``data`` are in units of electrons/s then ``effective_gain`` should be the exposure time or an exposure time map (e.g., for mosaics with non-uniform exposure times). .. _SExtractor: http://www.astromatic.net/software/sextractor """ data = np.asanyarray(data) bkg_error = np.asanyarray(bkg_error) inputs = [data, bkg_error, effective_gain] has_unit = [hasattr(x, 'unit') for x in inputs] use_units = all(has_unit) if any(has_unit) and not use_units: raise ValueError('If any of data, bkg_error, or effective_gain has ' 'units, then they all must all have units.') if use_units: if data.unit != bkg_error.unit: raise ValueError('data and bkg_error must have the same units.') count_units = [u.electron, u.photon] datagain_unit = data.unit * effective_gain.unit if datagain_unit not in count_units: raise u.UnitsError('(data * effective_gain) has units of "{0}", ' 'but it must have count units (e.g. ' 'u.electron or u.photon).' .format(datagain_unit)) if not isiterable(effective_gain): effective_gain = np.zeros(data.shape) + effective_gain else: effective_gain = np.asanyarray(effective_gain) if effective_gain.shape != data.shape: raise ValueError('If input effective_gain is 2D, then it must ' 'have the same shape as the input data.') if np.any(effective_gain <= 0): raise ValueError('effective_gain must be strictly positive ' 'everywhere.') # This calculation assumes that data and bkg_error have the same # units. source_variance is calculated to have units of # (data.unit)**2 so that it can be added with bkg_error**2 below. The # final returned error will have units of data.unit. np.maximum is # used to ensure that negative data values do not contribute to the # Poisson noise. if use_units: unit = data.unit data = data.value effective_gain = effective_gain.value source_variance = np.maximum(data / effective_gain, 0) * unit**2 else: source_variance = np.maximum(data / effective_gain, 0) return np.sqrt(bkg_error**2 + source_variance)
python
def calc_total_error(data, bkg_error, effective_gain): """ Calculate a total error array, combining a background-only error array with the Poisson noise of sources. Parameters ---------- data : array_like or `~astropy.units.Quantity` The data array. bkg_error : array_like or `~astropy.units.Quantity` The pixel-wise Gaussian 1-sigma background-only errors of the input ``data``. ``bkg_error`` should include all sources of "background" error but *exclude* the Poisson error of the sources. ``bkg_error`` must have the same shape as ``data``. If ``data`` and ``bkg_error`` are `~astropy.units.Quantity` objects, then they must have the same units. effective_gain : float, array-like, or `~astropy.units.Quantity` Ratio of counts (e.g., electrons or photons) to the units of ``data`` used to calculate the Poisson error of the sources. Returns ------- total_error : `~numpy.ndarray` or `~astropy.units.Quantity` The total error array. If ``data``, ``bkg_error``, and ``effective_gain`` are all `~astropy.units.Quantity` objects, then ``total_error`` will also be returned as a `~astropy.units.Quantity` object with the same units as the input ``data``. Otherwise, a `~numpy.ndarray` will be returned. Notes ----- To use units, ``data``, ``bkg_error``, and ``effective_gain`` must *all* be `~astropy.units.Quantity` objects. ``data`` and ``bkg_error`` must have the same units. A `ValueError` will be raised if only some of the inputs are `~astropy.units.Quantity` objects or if the ``data`` and ``bkg_error`` units differ. The total error array, :math:`\\sigma_{\\mathrm{tot}}` is: .. math:: \\sigma_{\\mathrm{tot}} = \\sqrt{\\sigma_{\\mathrm{b}}^2 + \\frac{I}{g}} where :math:`\\sigma_b`, :math:`I`, and :math:`g` are the background ``bkg_error`` image, ``data`` image, and ``effective_gain``, respectively. Pixels where ``data`` (:math:`I_i)` is negative do not contribute additional Poisson noise to the total error, i.e. :math:`\\sigma_{\\mathrm{tot}, i} = \\sigma_{\\mathrm{b}, i}`. Note that this is different from `SExtractor`_, which sums the total variance in the segment, including pixels where :math:`I_i` is negative. In such cases, `SExtractor`_ underestimates the total errors. Also note that SExtractor computes Poisson errors from background-subtracted data, which also results in an underestimation of the Poisson noise. ``effective_gain`` can either be a scalar value or a 2D image with the same shape as the ``data``. A 2D image is useful with mosaic images that have variable depths (i.e., exposure times) across the field. For example, one should use an exposure-time map as the ``effective_gain`` for a variable depth mosaic image in count-rate units. As an example, if your input ``data`` are in units of ADU, then ``effective_gain`` should be in units of electrons/ADU (or photons/ADU). If your input ``data`` are in units of electrons/s then ``effective_gain`` should be the exposure time or an exposure time map (e.g., for mosaics with non-uniform exposure times). .. _SExtractor: http://www.astromatic.net/software/sextractor """ data = np.asanyarray(data) bkg_error = np.asanyarray(bkg_error) inputs = [data, bkg_error, effective_gain] has_unit = [hasattr(x, 'unit') for x in inputs] use_units = all(has_unit) if any(has_unit) and not use_units: raise ValueError('If any of data, bkg_error, or effective_gain has ' 'units, then they all must all have units.') if use_units: if data.unit != bkg_error.unit: raise ValueError('data and bkg_error must have the same units.') count_units = [u.electron, u.photon] datagain_unit = data.unit * effective_gain.unit if datagain_unit not in count_units: raise u.UnitsError('(data * effective_gain) has units of "{0}", ' 'but it must have count units (e.g. ' 'u.electron or u.photon).' .format(datagain_unit)) if not isiterable(effective_gain): effective_gain = np.zeros(data.shape) + effective_gain else: effective_gain = np.asanyarray(effective_gain) if effective_gain.shape != data.shape: raise ValueError('If input effective_gain is 2D, then it must ' 'have the same shape as the input data.') if np.any(effective_gain <= 0): raise ValueError('effective_gain must be strictly positive ' 'everywhere.') # This calculation assumes that data and bkg_error have the same # units. source_variance is calculated to have units of # (data.unit)**2 so that it can be added with bkg_error**2 below. The # final returned error will have units of data.unit. np.maximum is # used to ensure that negative data values do not contribute to the # Poisson noise. if use_units: unit = data.unit data = data.value effective_gain = effective_gain.value source_variance = np.maximum(data / effective_gain, 0) * unit**2 else: source_variance = np.maximum(data / effective_gain, 0) return np.sqrt(bkg_error**2 + source_variance)
[ "def", "calc_total_error", "(", "data", ",", "bkg_error", ",", "effective_gain", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "bkg_error", "=", "np", ".", "asanyarray", "(", "bkg_error", ")", "inputs", "=", "[", "data", ",", "bkg_error", ",", "effective_gain", "]", "has_unit", "=", "[", "hasattr", "(", "x", ",", "'unit'", ")", "for", "x", "in", "inputs", "]", "use_units", "=", "all", "(", "has_unit", ")", "if", "any", "(", "has_unit", ")", "and", "not", "use_units", ":", "raise", "ValueError", "(", "'If any of data, bkg_error, or effective_gain has '", "'units, then they all must all have units.'", ")", "if", "use_units", ":", "if", "data", ".", "unit", "!=", "bkg_error", ".", "unit", ":", "raise", "ValueError", "(", "'data and bkg_error must have the same units.'", ")", "count_units", "=", "[", "u", ".", "electron", ",", "u", ".", "photon", "]", "datagain_unit", "=", "data", ".", "unit", "*", "effective_gain", ".", "unit", "if", "datagain_unit", "not", "in", "count_units", ":", "raise", "u", ".", "UnitsError", "(", "'(data * effective_gain) has units of \"{0}\", '", "'but it must have count units (e.g. '", "'u.electron or u.photon).'", ".", "format", "(", "datagain_unit", ")", ")", "if", "not", "isiterable", "(", "effective_gain", ")", ":", "effective_gain", "=", "np", ".", "zeros", "(", "data", ".", "shape", ")", "+", "effective_gain", "else", ":", "effective_gain", "=", "np", ".", "asanyarray", "(", "effective_gain", ")", "if", "effective_gain", ".", "shape", "!=", "data", ".", "shape", ":", "raise", "ValueError", "(", "'If input effective_gain is 2D, then it must '", "'have the same shape as the input data.'", ")", "if", "np", ".", "any", "(", "effective_gain", "<=", "0", ")", ":", "raise", "ValueError", "(", "'effective_gain must be strictly positive '", "'everywhere.'", ")", "# This calculation assumes that data and bkg_error have the same", "# units. source_variance is calculated to have units of", "# (data.unit)**2 so that it can be added with bkg_error**2 below. The", "# final returned error will have units of data.unit. np.maximum is", "# used to ensure that negative data values do not contribute to the", "# Poisson noise.", "if", "use_units", ":", "unit", "=", "data", ".", "unit", "data", "=", "data", ".", "value", "effective_gain", "=", "effective_gain", ".", "value", "source_variance", "=", "np", ".", "maximum", "(", "data", "/", "effective_gain", ",", "0", ")", "*", "unit", "**", "2", "else", ":", "source_variance", "=", "np", ".", "maximum", "(", "data", "/", "effective_gain", ",", "0", ")", "return", "np", ".", "sqrt", "(", "bkg_error", "**", "2", "+", "source_variance", ")" ]
Calculate a total error array, combining a background-only error array with the Poisson noise of sources. Parameters ---------- data : array_like or `~astropy.units.Quantity` The data array. bkg_error : array_like or `~astropy.units.Quantity` The pixel-wise Gaussian 1-sigma background-only errors of the input ``data``. ``bkg_error`` should include all sources of "background" error but *exclude* the Poisson error of the sources. ``bkg_error`` must have the same shape as ``data``. If ``data`` and ``bkg_error`` are `~astropy.units.Quantity` objects, then they must have the same units. effective_gain : float, array-like, or `~astropy.units.Quantity` Ratio of counts (e.g., electrons or photons) to the units of ``data`` used to calculate the Poisson error of the sources. Returns ------- total_error : `~numpy.ndarray` or `~astropy.units.Quantity` The total error array. If ``data``, ``bkg_error``, and ``effective_gain`` are all `~astropy.units.Quantity` objects, then ``total_error`` will also be returned as a `~astropy.units.Quantity` object with the same units as the input ``data``. Otherwise, a `~numpy.ndarray` will be returned. Notes ----- To use units, ``data``, ``bkg_error``, and ``effective_gain`` must *all* be `~astropy.units.Quantity` objects. ``data`` and ``bkg_error`` must have the same units. A `ValueError` will be raised if only some of the inputs are `~astropy.units.Quantity` objects or if the ``data`` and ``bkg_error`` units differ. The total error array, :math:`\\sigma_{\\mathrm{tot}}` is: .. math:: \\sigma_{\\mathrm{tot}} = \\sqrt{\\sigma_{\\mathrm{b}}^2 + \\frac{I}{g}} where :math:`\\sigma_b`, :math:`I`, and :math:`g` are the background ``bkg_error`` image, ``data`` image, and ``effective_gain``, respectively. Pixels where ``data`` (:math:`I_i)` is negative do not contribute additional Poisson noise to the total error, i.e. :math:`\\sigma_{\\mathrm{tot}, i} = \\sigma_{\\mathrm{b}, i}`. Note that this is different from `SExtractor`_, which sums the total variance in the segment, including pixels where :math:`I_i` is negative. In such cases, `SExtractor`_ underestimates the total errors. Also note that SExtractor computes Poisson errors from background-subtracted data, which also results in an underestimation of the Poisson noise. ``effective_gain`` can either be a scalar value or a 2D image with the same shape as the ``data``. A 2D image is useful with mosaic images that have variable depths (i.e., exposure times) across the field. For example, one should use an exposure-time map as the ``effective_gain`` for a variable depth mosaic image in count-rate units. As an example, if your input ``data`` are in units of ADU, then ``effective_gain`` should be in units of electrons/ADU (or photons/ADU). If your input ``data`` are in units of electrons/s then ``effective_gain`` should be the exposure time or an exposure time map (e.g., for mosaics with non-uniform exposure times). .. _SExtractor: http://www.astromatic.net/software/sextractor
[ "Calculate", "a", "total", "error", "array", "combining", "a", "background", "-", "only", "error", "array", "with", "the", "Poisson", "noise", "of", "sources", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/errors.py#L11-L132
train
astropy/photutils
photutils/aperture/rectangle.py
RectangularAperture.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyRectangularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAperture` object A `SkyRectangularAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyRectangularAperture(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyRectangularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAperture` object A `SkyRectangularAperture` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyRectangularAperture(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyRectangularAperture", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyRectangularAperture` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAperture` object A `SkyRectangularAperture` object.
[ "Convert", "the", "aperture", "to", "a", "SkyRectangularAperture", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/rectangle.py#L200-L222
train
astropy/photutils
photutils/aperture/rectangle.py
RectangularAnnulus.to_sky
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyRectangularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAnnulus` object A `SkyRectangularAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyRectangularAnnulus(**sky_params)
python
def to_sky(self, wcs, mode='all'): """ Convert the aperture to a `SkyRectangularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAnnulus` object A `SkyRectangularAnnulus` object. """ sky_params = self._to_sky_params(wcs, mode=mode) return SkyRectangularAnnulus(**sky_params)
[ "def", "to_sky", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "sky_params", "=", "self", ".", "_to_sky_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "SkyRectangularAnnulus", "(", "*", "*", "sky_params", ")" ]
Convert the aperture to a `SkyRectangularAnnulus` object defined in celestial coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `SkyRectangularAnnulus` object A `SkyRectangularAnnulus` object.
[ "Convert", "the", "aperture", "to", "a", "SkyRectangularAnnulus", "object", "defined", "in", "celestial", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/rectangle.py#L354-L376
train
astropy/photutils
photutils/aperture/rectangle.py
SkyRectangularAperture.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `RectangularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAperture` object A `RectangularAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return RectangularAperture(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `RectangularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAperture` object A `RectangularAperture` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return RectangularAperture(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "RectangularAperture", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to a `RectangularAperture` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAperture` object A `RectangularAperture` object.
[ "Convert", "the", "aperture", "to", "a", "RectangularAperture", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/rectangle.py#L425-L447
train
astropy/photutils
photutils/aperture/rectangle.py
SkyRectangularAnnulus.to_pixel
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `RectangularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAnnulus` object A `RectangularAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return RectangularAnnulus(**pixel_params)
python
def to_pixel(self, wcs, mode='all'): """ Convert the aperture to a `RectangularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAnnulus` object A `RectangularAnnulus` object. """ pixel_params = self._to_pixel_params(wcs, mode=mode) return RectangularAnnulus(**pixel_params)
[ "def", "to_pixel", "(", "self", ",", "wcs", ",", "mode", "=", "'all'", ")", ":", "pixel_params", "=", "self", ".", "_to_pixel_params", "(", "wcs", ",", "mode", "=", "mode", ")", "return", "RectangularAnnulus", "(", "*", "*", "pixel_params", ")" ]
Convert the aperture to a `RectangularAnnulus` object defined in pixel coordinates. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distortions (``'all'``; default) or only including only the core WCS transformation (``'wcs'``). Returns ------- aperture : `RectangularAnnulus` object A `RectangularAnnulus` object.
[ "Convert", "the", "aperture", "to", "a", "RectangularAnnulus", "object", "defined", "in", "pixel", "coordinates", "." ]
cc9bb4534ab76bac98cb5f374a348a2573d10401
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/rectangle.py#L511-L533
train