Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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...
[ "\n Construct a joint PSF model which consists of a sum of PSF's templated on\n a specific model, but whose parameters are given by a table of objects.\n\n Parameters\n ----------\n template_psf_model : `astropy.modeling.Fittable2DModel` instance\n The model to use for *individual* objects. M...
Please provide a description of the function:def _extract_psf_fitting_names(psf): if hasattr(psf, 'xname'): xname = psf.xname elif 'x_0' in psf.param_names: xname = 'x_0' else: raise ValueError('Could not determine x coordinate name for ' 'psf_photometr...
[ "\n Determine the names of the x coordinate, y coordinate, and flux from\n a model. Returns (xname, yname, fluxname)\n " ]
Please provide a description of the function: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)
[ "\n Not all fitters have to support a weight array. This function\n includes the weight in the fitter call only if really needed.\n " ]
Please provide a description of the function:def subtract_psf(data, psf, posflux, subshape=None): if data.ndim != 2: raise ValueError('{0}-d array not supported. Only 2-d arrays can be ' 'passed to subtract_psf.'.format(data.ndim)) # translate array input into table ...
[ "\n Subtract PSF/PRFs from an image.\n\n Parameters\n ----------\n data : `~astropy.nddata.NDData` or array (must be 2D)\n Image data.\n psf : `astropy.modeling.Fittable2DModel` instance\n PSF/PRF model to be substracted from the data.\n posflux : Array-like of shape (3, N) or `~astr...
Please provide a description of the function: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, dat...
[ "\n Calculate a pixel-wise threshold image that can be used to detect\n sources.\n\n Parameters\n ----------\n data : array_like\n The 2D array of the image.\n\n snr : float\n The signal-to-noise ratio per pixel above the ``background`` for\n which to consider a pixel as possi...
Please provide a description of the function:def find_peaks(data, threshold, box_size=3, footprint=None, mask=None, border_width=None, npeaks=np.inf, centroid_func=None, subpixel=False, error=None, wcs=None): from scipy.ndimage import maximum_filter data = np.asanyarray(data...
[ "\n Find local peaks in an image that are above above a specified\n threshold value.\n\n Peaks are the maxima above the ``threshold`` within a local region.\n The local regions are defined by either the ``box_size`` or\n ``footprint`` parameters. ``box_size`` defines the local region\n around eac...
Please provide a description of the function: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 ...
[ "\n Run a command in a subprocess, given as a list of command-line\n arguments.\n\n Returns a ``(returncode, stdout, stderr)`` tuple.\n " ]
Please provide a description of the function:def to_mask(self, method='exact', subpixels=5): use_exact, subpixels = self._translate_mask_mode(method, subpixels) if hasattr(self, 'a'): a = self.a b = self.b elif hasattr(self, 'a_in'): # annulus a ...
[ "\n Return a list of `~photutils.ApertureMask` objects, one for each\n aperture position.\n\n Parameters\n ----------\n method : {'exact', 'center', 'subpixel'}, optional\n The method used to determine the overlap of the aperture on\n the pixel grid. Not all...
Please provide a description of the function:def to_sky(self, wcs, mode='all'): sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAperture(**sky_params)
[ "\n Convert the aperture to a `SkyEllipticalAperture` object defined\n in celestial coordinates.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whe...
Please provide a description of the function:def bounding_boxes(self): cos_theta = np.cos(self.theta) sin_theta = np.sin(self.theta) ax = self.a_out * cos_theta ay = self.a_out * sin_theta bx = self.b_out * -sin_theta by = self.b_out * cos_theta dx = np....
[ "\n A list of minimal bounding boxes (`~photutils.BoundingBox`), one\n for each position, enclosing the exact elliptical apertures.\n " ]
Please provide a description of the function:def to_sky(self, wcs, mode='all'): sky_params = self._to_sky_params(wcs, mode=mode) return SkyEllipticalAnnulus(**sky_params)
[ "\n Convert the aperture to a `SkyEllipticalAnnulus` object defined\n in celestial coordinates.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whet...
Please provide a description of the function:def to_pixel(self, wcs, mode='all'): pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAperture(**pixel_params)
[ "\n Convert the aperture to an `EllipticalAperture` object defined\n in pixel coordinates.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whether t...
Please provide a description of the function:def to_pixel(self, wcs, mode='all'): pixel_params = self._to_pixel_params(wcs, mode=mode) return EllipticalAnnulus(**pixel_params)
[ "\n Convert the aperture to an `EllipticalAnnulus` object defined in\n pixel coordinates.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whether to...
Please provide a description of the function: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))
[ "\n Compute elliptical sector area.\n " ]
Please provide a description of the function: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...
[ "\n Find the center of a galaxy.\n\n If the algorithm is successful the (x, y) coordinates in this\n `~photutils.isophote.EllipseGeometry` (i.e. the ``x0`` and\n ``y0`` attributes) instance will be modified.\n\n The isophote fit algorithm requires an initial guess for the\n ...
Please provide a description of the function:def radius(self, angle): return (self.sma * (1. - self.eps) / np.sqrt(((1. - self.eps) * np.cos(angle))**2 + (np.sin(angle))**2))
[ "\n Calculate the polar radius for a given polar angle.\n\n Parameters\n ----------\n angle : float\n The polar angle (radians).\n\n Returns\n -------\n radius : float\n The polar radius (pixels).\n " ]
Please provide a description of the function: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 ...
[ "\n Initialize geometry attributes associated with an elliptical\n sector at the given polar angle ``phi``.\n\n This function computes:\n\n * the four vertices that define the elliptical sector on the\n pixel array.\n * the sector area (saved in the ``sector_area`` attrib...
Please provide a description of the function: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.)...
[ "\n Compute the semimajor axis of the two ellipses that bound the\n annulus where integrations take place.\n\n Returns\n -------\n sma1, sma2 : float\n The smaller and larger values of semimajor axis length that\n define the annulus bounding ellipses.\n ...
Please provide a description of the function:def to_polar(self, x, y): # We split in between a scalar version and a # vectorized version. This is necessary for # now so we don't pay a heavy speed penalty # that is incurred when using vectorized code. # The split in two ...
[ "\n Return the radius and polar angle in the ellipse coordinate\n system given (x, y) pixel image coordinates.\n\n This function takes care of the different definitions for\n position angle (PA) and polar angle (phi):\n\n .. math::\n -\\\\pi < PA < \\\\pi\n\n ...
Please provide a description of the function:def update_sma(self, step): if self.linear_growth: sma = self.sma + step else: sma = self.sma * (1. + step) return sma
[ "\n Calculate an updated value for the semimajor axis, given the\n current value and the step value.\n\n The step value must be managed by the caller to support both\n modes: grow outwards and shrink inwards.\n\n Parameters\n ----------\n step : float\n Th...
Please provide a description of the function: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
[ "\n Change the direction of semimajor axis growth, from outwards to\n inwards.\n\n Parameters\n ----------\n step : float\n The current step value.\n\n Returns\n -------\n sma, new_step : float\n The new semimajor axis length and the new ...
Please provide a description of the function: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
[ "\n Resize a PSF using spline interpolation of the requested order.\n\n Parameters\n ----------\n psf : 2D `~numpy.ndarray`\n The 2D data array of the PSF.\n\n input_pixel_scale : float\n The pixel scale of the input ``psf``. The units must\n match ``output_pixel_scale``.\n\n ...
Please provide a description of the function:def create_matching_kernel(source_psf, target_psf, window=None): # inputs are copied so that they are not changed when normalizing source_psf = np.copy(np.asanyarray(source_psf)) target_psf = np.copy(np.asanyarray(target_psf)) if source_psf.shape != ta...
[ "\n Create a kernel to match 2D point spread functions (PSF) using the\n ratio of Fourier transforms.\n\n Parameters\n ----------\n source_psf : 2D `~numpy.ndarray`\n The source PSF. The source PSF should have higher resolution\n (i.e. narrower) than the target PSF. ``source_psf`` and...
Please provide a description of the function:def _pad_data(self, yextra, xextra): ypad = 0 xpad = 0 if yextra > 0: ypad = self.box_size[0] - yextra if xextra > 0: xpad = self.box_size[1] - xextra pad_width = ((0, ypad), (0, xpad)) # mode...
[ "\n Pad the ``data`` and ``mask`` to have an integer number of\n background meshes of size ``box_size`` in both dimensions. The\n padding is added on the top and/or right edges (this is the best\n option for the \"zoom\" interpolator).\n\n Parameters\n ----------\n ...
Please provide a description of the function:def _crop_data(self): ny_crop = self.nyboxes * self.box_size[1] nx_crop = self.nxboxes * self.box_size[0] crop_slc = index_exp[0:ny_crop, 0:nx_crop] if self.mask is not None: mask = self.mask[crop_slc] else: ...
[ "\n Crop the ``data`` and ``mask`` to have an integer number of\n background meshes of size ``box_size`` in both dimensions. The\n data are cropped on the top and/or right edges (this is the best\n option for the \"zoom\" interpolator).\n\n Returns\n -------\n resul...
Please provide a description of the function: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 exc...
[ "\n Define the x and y indices with respect to the low-resolution\n mesh image of the meshes to use for the background\n interpolation.\n\n The ``exclude_percentile`` keyword determines which meshes are\n not used for the background interpolation.\n\n Parameters\n --...
Please provide a description of the function: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] ...
[ "\n Prepare the data.\n\n First, pad or crop the 2D data array so that there are an\n integer number of meshes in both dimensions, creating a masked\n array.\n\n Then reshape into a different 2D masked array where each row\n represents the data in a single mesh. This metho...
Please provide a description of the function: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') data...
[ "\n Convert a 1D array of mesh values to a masked 2D mesh array\n given the 1D mesh indices ``mesh_idx``.\n\n Parameters\n ----------\n data : 1D `~numpy.ndarray`\n A 1D array of mesh values.\n\n Returns\n -------\n result : 2D `~numpy.ma.MaskedArra...
Please provide a description of the function: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), ...
[ "\n Use IDW interpolation to fill in any masked pixels in the\n low-resolution 2D mesh background and background RMS images.\n\n This is required to use a regular-grid interpolator to expand\n the low-resolution image to the full size image.\n\n Parameters\n ----------\n ...
Please provide a description of the function: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...
[ "\n Selectively filter only pixels above ``filter_threshold`` in the\n background mesh.\n\n The same pixels are filtered in both the background and\n background RMS meshes.\n\n Parameters\n ----------\n data : 2D `~numpy.ndarray`\n A 2D array of mesh value...
Please provide a description of the function: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 nanmed...
[ "\n Apply a 2D median filter to the low-resolution 2D mesh,\n including only pixels inside the image at the borders.\n " ]
Please provide a description of the function: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-c...
[ "\n Calculate the background and background RMS estimate in each of\n the meshes.\n\n Both meshes are computed at the same time here method because\n the filtering of both depends on the background mesh.\n\n The ``background_mesh`` and ``background_rms_mesh`` images are\n e...
Please provide a description of the function: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] + ...
[ "\n Calculate the coordinates to use when calling an interpolator.\n\n These are needed for `Background2D` and `BackgroundIDW2D`.\n\n Regular-grid interpolators require a 2D array of values. Some\n require a 2D meshgrid of x and y. Other require a strictly\n increasing 1D array ...
Please provide a description of the function:def mesh_nmasked(self): return self._make_2d_array( np.ma.count_masked(self._data_sigclip, axis=1))
[ "\n A 2D (masked) array of the number of masked pixels in each mesh.\n Only meshes included in the background estimation are included.\n The array is masked only if meshes were excluded.\n " ]
Please provide a description of the function:def background_mesh_ma(self): if len(self._bkg1d) == self.nboxes: return self.background_mesh else: return self._make_2d_array(self._bkg1d)
[ "\n The background 2D (masked) array mesh prior to any\n interpolation. The array is masked only if meshes were\n excluded.\n " ]
Please provide a description of the function:def background_rms_mesh_ma(self): if len(self._bkgrms1d) == self.nboxes: return self.background_rms_mesh else: return self._make_2d_array(self._bkgrms1d)
[ "\n The background RMS 2D (masked) array mesh prior to any\n interpolation. The array is masked only if meshes were\n excluded.\n " ]
Please provide a description of the function: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, mar...
[ "\n Plot the low-resolution mesh boxes on a matplotlib Axes\n instance.\n\n Parameters\n ----------\n ax : `matplotlib.axes.Axes` instance, optional\n If `None`, then the current ``Axes`` instance is used.\n\n marker : str, optional\n The marker to use...
Please provide a description of the function: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.v...
[ "\n Extract sample data by scanning an elliptical path over the\n image array.\n\n Returns\n -------\n result : 2D `~numpy.ndarray`\n The rows of the array contain the angles, radii, and\n extracted intensity values, respectively.\n " ]
Please provide a description of the function: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 ...
[ "\n Update this `~photutils.isophote.EllipseSample` instance.\n\n This method calls the\n :meth:`~photutils.isophote.EllipseSample.extract` method to get\n the values that match the current ``geometry`` attribute, and\n then computes the the mean intensity, local gradient, and oth...
Please provide a description of the function:def coordinates(self): angles = self.values[0] radii = self.values[1] x = np.zeros(len(angles)) y = np.zeros(len(angles)) for i in range(len(x)): x[i] = (radii[i] * np.cos(angles[i] + self.geometry.pa) + ...
[ "\n Return the (x, y) coordinates associated with each sampled\n point.\n\n Returns\n -------\n x, y : 1D `~numpy.ndarray`\n The x and y coordinate arrays.\n " ]
Please provide a description of the function:def update(self): s = self.extract() self.mean = s[2][0] self.gradient = None self.gradient_error = None self.gradient_relative_error = None
[ "\n Update this `~photutils.isophote.EllipseSample` instance with\n the intensity integrated at the (x0, y0) center position using\n bilinear integration. The local gradient is set to `None`.\n " ]
Please provide a description of the function: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 (...
[ "\n Fit an elliptical isophote.\n\n Parameters\n ----------\n conver : float, optional\n The main convergence criterion. Iterations stop when the\n largest harmonic amplitude becomes smaller (in absolute\n value) than ``conver`` times the harmonic fit rms...
Please provide a description of the function:def fit(self, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, going_inwards=False): self._sample.update() return CentralPixel(self._sample)
[ "\n Perform just a simple 1-pixel extraction at the current (x0, y0)\n position using bilinear interpolation.\n\n The input parameters are ignored, but included simple to match\n the calling signature of the parent class.\n\n Returns\n -------\n result : `~photutils....
Please provide a description of the function:def extract_stars(data, catalogs, size=(11, 11)): if isinstance(data, NDData): data = [data] if isinstance(catalogs, Table): catalogs = [catalogs] for img in data: if not isinstance(img, NDData): raise ValueError('data ...
[ "\n Extract cutout images centered on stars defined in the input\n catalog(s).\n\n Stars where the cutout array bounds partially or completely lie\n outside of the input ``data`` image will not be extracted.\n\n Parameters\n ----------\n data : `~astropy.nddata.NDData` or list of `~astropy.ndda...
Please provide a description of the function: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, ...
[ "\n Extract cutout images from a single image centered on stars defined\n in the single input catalog.\n\n Parameters\n ----------\n data : `~astropy.nddata.NDData`\n A `~astropy.nddata.NDData` object containing the 2D image from\n which to extract the stars. If the input ``catalog`` c...
Please provide a description of the function:def slices(self): return (slice(self.origin[1], self.origin[1] + self.shape[1]), slice(self.origin[0], self.origin[0] + self.shape[0]))
[ "\n A tuple of two slices representing the cutout region with\n respect to the original (large) image.\n " ]
Please provide a description of the function:def bbox(self): return BoundingBox(self.slices[1].start, self.slices[1].stop, self.slices[0].start, self.slices[0].stop)
[ "\n The minimal `~photutils.aperture.BoundingBox` for the cutout\n region with respect to the original (large) image.\n " ]
Please provide a description of the function: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) ...
[ "\n Estimate the star's flux by summing values in the input cutout\n array.\n\n Missing data is filled in by interpolation to better estimate\n the total flux.\n " ]
Please provide a description of the function:def register_epsf(self, epsf): yy, xx = np.indices(self.shape, dtype=np.float) xx = epsf._oversampling[0] * (xx - self.cutout_center[0]) yy = epsf._oversampling[1] * (yy - self.cutout_center[1]) return (self.flux * np.prod(epsf._ove...
[ "\n Register and scale (in flux) the input ``epsf`` to the star.\n\n Parameters\n ----------\n epsf : `EPSFModel`\n The ePSF to register.\n\n Returns\n -------\n data : `~numpy.ndarray`\n A 2D array of the registered/scaled ePSF.\n " ]
Please provide a description of the function:def _xy_idx(self): yidx, xidx = np.indices(self._data.shape) return xidx[~self.mask].ravel(), yidx[~self.mask].ravel()
[ "\n 1D arrays of x and y indices of unmasked pixels in the cutout\n reference frame.\n " ]
Please provide a description of the function:def all_stars(self): stars = [] for item in self._data: if isinstance(item, LinkedEPSFStar): stars.extend(item.all_stars) else: stars.append(item) return stars
[ "\n A list of all `EPSFStar` objects stored in this object,\n including those that comprise linked stars (i.e.\n `LinkedEPSFStar`), as a flat list.\n " ]
Please provide a description of the function:def all_good_stars(self): stars = [] for star in self.all_stars: if star._excluded_from_fit: continue else: stars.append(star) return stars
[ "\n A list of all `EPSFStar` objects stored in this object that have\n not been excluded from fitting, including those that comprise\n linked stars (i.e. `LinkedEPSFStar`), as a flat list.\n " ]
Please provide a description of the function:def _max_shape(self): return np.max([star.shape for star in self.all_stars], axis=0)
[ "\n The maximum x and y shapes of all the `EPSFStar`\\\\s (including\n linked stars).\n " ]
Please provide a description of the function:def constrain_centers(self): if len(self._data) < 2: # no linked stars return idx = np.logical_not(self._excluded_from_fit).nonzero()[0] if len(idx) == 0: warnings.warn('Cannot constrain centers of linked stars bec...
[ "\n Constrain the centers of linked `EPSFStar` objects (i.e. the\n same physical star) to have the same sky coordinate.\n\n Only `EPSFStar` objects that have not been excluded during the\n ePSF build process will be used to constrain the centers.\n\n The single sky coordinate is c...
Please provide a description of the function: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...
[ "\n Find the ids of those stars in ``starlist`` which are at a\n distance less than ``crit_separation`` from ``star``.\n\n Parameters\n ----------\n star : `~astropy.table.Row`\n Star which will be either the head of a cluster or an\n isolated one.\n s...
Please provide a description of the function: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)
[ "\n Return the smallest bounding box that fully contains a given\n rectangle defined by float coordinate values.\n\n Following the pixel index convention, an integer index\n corresponds to the center of a pixel and the pixel edges span\n from (index - 0.5) to (index + 0.5). For e...
Please provide a description of the function:def shape(self): return self.iymax - self.iymin, self.ixmax - self.ixmin
[ "\n The ``(ny, nx)`` shape of the bounding box.\n " ]
Please provide a description of the function:def slices(self): return (slice(self.iymin, self.iymax), slice(self.ixmin, self.ixmax))
[ "\n The bounding box as a tuple of `slice` objects.\n\n The slice tuple is in numpy axis order (i.e. ``(y, x)``) and\n therefore can be used to slice numpy arrays.\n " ]
Please provide a description of the function:def extent(self): return ( self.ixmin - 0.5, self.ixmax - 0.5, self.iymin - 0.5, self.iymax - 0.5, )
[ "\n The extent of the mask, defined as the ``(xmin, xmax, ymin,\n ymax)`` bounding box from the bottom-left corner of the\n lower-left pixel to the upper-right corner of the upper-right\n pixel.\n\n The upper edges here are the actual pixel positions of the\n edges, i.e. th...
Please provide a description of the function: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)
[ "\n Return a `matplotlib.patches.Rectangle` that represents the\n bounding box.\n\n Parameters\n ----------\n kwargs\n Any keyword arguments accepted by\n `matplotlib.patches.Patch`.\n\n Returns\n -------\n result : `matplotlib.patches.Re...
Please provide a description of the function: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 Rectangular...
[ "\n Return a `~photutils.aperture.RectangularAperture` that\n represents the bounding box.\n " ]
Please provide a description of the function:def plot(self, origin=(0, 0), ax=None, fill=False, **kwargs): aper = self.to_aperture() aper.plot(origin=origin, ax=ax, fill=fill, **kwargs)
[ "\n Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes`\n instance.\n\n Parameters\n ----------\n origin : array_like, optional\n The ``(x, y)`` position of the origin of the displayed\n image.\n\n ax : `matplotlib.axes.Axes` instance, optio...
Please provide a description of the function:def build_ellipse_model(shape, isolist, fill=0., high_harmonics=False): from scipy.interpolate import LSQUnivariateSpline # the target grid is spaced in 0.1 pixel intervals so as # to ensure no gaps will result on the output array. finely_spaced_sma = ...
[ "\n Build an elliptical model galaxy image from a list of isophotes.\n\n For each ellipse in the input isophote list the algorithm fills the\n output image array with the corresponding isophotal intensity.\n Pixels in the output array are in general only partially covered by\n the isophote \"pixel\"....
Please provide a description of the function: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) # d...
[ "\n Find stars in an image.\n\n Parameters\n ----------\n data : 2D array_like\n The 2D array of the image.\n\n kernel : `_StarFinderKernel`\n The convolution kernel.\n\n threshold_eff : float\n The absolute image value above which to select sources. This\n threshold s...
Please provide a description of the function:def daofind_marginal_fit(self, axis=0): # define triangular weighting functions along each axis, peaked # in the middle and equal to one at the edge x = self.xcenter - np.abs(np.arange(self.nx) - self.xcenter) + 1 y = self.ycenter - ...
[ "\n Fit 1D Gaussians, defined from the marginal x/y kernel\n distributions, to the marginal x/y distributions of the original\n (unconvolved) image.\n\n These fits are used calculate the star centroid and roundness\n (\"GROUND\") properties.\n\n Parameters\n --------...
Please provide a description of the function: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)
[ "\n The star roundness.\n\n This roundness parameter represents the ratio of the difference\n in the height of the best fitting Gaussian function in x minus\n the best fitting Gaussian function in y, divided by the average\n of the best fitting Gaussian functions in x and y. A ci...
Please provide a description of the function:def find_stars(self, data, mask=None): star_cutouts = _find_stars(data, self.kernel, self.threshold_eff, mask=mask, exclude_border=self.exclude_border) if star_cutouts is None: ...
[ "\n Find stars in an astronomical image.\n\n Parameters\n ----------\n data : 2D array_like\n The 2D image array.\n\n mask : 2D bool array, optional\n A boolean mask with the same shape as ``data``, where a\n `True` value indicates the correspondin...
Please provide a description of the function:def find_stars(self, data, mask=None): star_cutouts = _find_stars(data, self.kernel, self.threshold, min_separation=self.min_separation, mask=mask, excl...
[ "\n Find stars in an astronomical image.\n\n Parameters\n ----------\n data : 2D array_like\n The 2D image array.\n\n mask : 2D bool array, optional\n A boolean mask with the same shape as ``data``, where a\n `True` value indicates the correspondin...
Please provide a description of the function: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 ' ...
[ "\n Detect sources above a specified threshold value in an image and\n return a `~photutils.segmentation.SegmentationImage` object.\n\n Detected sources must have ``npixels`` connected pixels that are\n each greater than the ``threshold`` value. If the filtering option\n is used, then the ``threshol...
Please provide a description of the function: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 = detec...
[ "\n Make a source mask using source segmentation and binary dilation.\n\n Parameters\n ----------\n data : array_like\n The 2D array of the image.\n\n snr : float\n The signal-to-noise ratio per pixel above the ``background`` for\n which to consider a pixel as possibly being part...
Please provide a description of the function:def data(self): cutout = np.copy(self._segment_img[self.slices]) cutout[cutout != self.label] = 0 return cutout
[ "\n A 2D cutout image of the segment using the minimal bounding box,\n where pixels outside of the labeled region are set to zero (i.e.\n neighboring segments within the rectangular cutout image are not\n shown).\n " ]
Please provide a description of the function:def data_ma(self): mask = (self._segment_img[self.slices] != self.label) return np.ma.masked_array(self._segment_img[self.slices], mask=mask)
[ "\n A 2D `~numpy.ma.MaskedArray` cutout image of the segment using\n the minimal bounding box.\n\n The mask is `True` for pixels outside of the source segment\n (i.e. neighboring segments within the rectangular cutout image\n are masked).\n " ]
Please provide a description of the function:def make_cutout(self, data, masked_array=False): data = np.asanyarray(data) if data.shape != self._segment_img.shape: raise ValueError('data must have the same shape as the ' 'segmentation image.') i...
[ "\n Create a (masked) cutout array from the input ``data`` using the\n minimal bounding box of the segment (labeled region).\n\n If ``masked_array`` is `False` (default), then the returned\n cutout array is simply a `~numpy.ndarray`. The returned cutout\n is a view (not a copy) o...
Please provide a description of the function: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." ]
Please provide a description of the function: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
[ "\n A list of `Segment` objects.\n\n The list starts with the *non-zero* label. The returned list\n has a length equal to the number of labels and matches the order\n of the ``labels`` attribute.\n " ]
Please provide a description of the function:def get_index(self, label): self.check_labels(label) return np.searchsorted(self.labels, label)
[ "\n Find the index of the input ``label``.\n\n Parameters\n ----------\n labels : int\n The label numbers to find.\n\n Returns\n -------\n index : int\n The array index.\n\n Raises\n ------\n ValueError\n If ``lab...
Please provide a description of the function:def get_indices(self, labels): self.check_labels(labels) return np.searchsorted(self.labels, labels)
[ "\n Find the indices of the input ``labels``.\n\n Parameters\n ----------\n labels : int, array-like (1D, int)\n The label numbers(s) to find.\n\n Returns\n -------\n indices : int `~numpy.ndarray`\n An integer array of indices with the same sha...
Please provide a description of the function:def slices(self): from scipy.ndimage import find_objects return [slc for slc in find_objects(self._data) if slc is not None]
[ "\n A list of tuples, where each tuple contains two slices\n representing the minimal box that contains the labeled region.\n\n The list starts with the *non-zero* label. The returned list\n has a length equal to the number of labels and matches the order\n of the ``labels`` attr...
Please provide a description of the function:def areas(self): return np.array([area for area in np.bincount(self.data.ravel())[1:] if area != 0])
[ "\n A 1D array of areas (in pixel**2) of the non-zero labeled\n regions.\n\n The `~numpy.ndarray` starts with the *non-zero* label. The\n returned array has a length equal to the number of labels and\n matches the order of the ``labels`` attribute.\n " ]
Please provide a description of the function:def get_areas(self, labels): idx = self.get_indices(labels) return self.areas[idx]
[ "\n The areas (in pixel**2) of the regions for the input labels.\n\n Parameters\n ----------\n labels : int, 1D array-like (int)\n The label(s) for which to return areas. Label must be\n non-zero.\n\n Returns\n -------\n areas : `~numpy.ndarray...
Please provide a description of the function:def is_consecutive(self): if (self.labels[-1] - self.labels[0] + 1) == self.nlabels: return True else: return False
[ "\n Determine whether or not the non-zero labels in the segmentation\n image are consecutive (i.e. no missing values).\n " ]
Please provide a description of the function:def missing_labels(self): return np.array(sorted(set(range(0, self.max_label + 1)). difference(np.insert(self.labels, 0, 0))))
[ "\n A 1D `~numpy.ndarray` of the sorted non-zero labels that are\n missing in the consecutive sequence from zero to the maximum\n label number.\n " ]
Please provide a description of the function:def check_labels(self, labels): labels = np.atleast_1d(labels) bad_labels = set() # check for positive label numbers idx = np.where(labels <= 0)[0] if len(idx) > 0: bad_labels.update(labels[idx]) # check...
[ "\n Check that the input label(s) are valid label numbers within the\n segmentation image.\n\n Parameters\n ----------\n labels : int, 1D array-like (int)\n The label(s) to check.\n\n Raises\n ------\n ValueError\n If any input ``labels``...
Please provide a description of the function:def cmap(self, background_color='#000000', random_state=None): return self.make_cmap(background_color=background_color, random_state=random_state)
[ "\n Define a matplotlib colormap consisting of (random) muted\n colors.\n\n This is very useful for plotting the segmentation image.\n\n Parameters\n ----------\n background_color : str or `None`, optional\n A hex string in the \"#rrggbb\" format defining the fir...
Please provide a description of the function:def make_cmap(self, background_color='#000000', random_state=None): from matplotlib import colors cmap = make_random_cmap(self.max_label + 1, random_state=random_state) if background_color is not None: cmap.colors[0] = colors.h...
[ "\n Define a matplotlib colormap consisting of (random) muted\n colors.\n\n This is very useful for plotting the segmentation image.\n\n Parameters\n ----------\n background_color : str or `None`, optional\n A hex string in the \"#rrggbb\" format defining the fir...
Please provide a description of the function:def reassign_label(self, label, new_label, relabel=False): self.reassign_labels(label, new_label, relabel=relabel)
[ "\n Reassign a label number to a new number.\n\n If ``new_label`` is already present in the segmentation image,\n then it will be combined with the input ``label`` number.\n\n Parameters\n ----------\n labels : int\n The label number to reassign.\n\n new_l...
Please provide a description of the function: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] = ...
[ "\n Reassign one or more label numbers.\n\n Multiple input ``labels`` will all be reassigned to the same\n ``new_label`` number. If ``new_label`` is already present in\n the segmentation image, then it will be combined with the input\n ``labels``.\n\n Parameters\n -...
Please provide a description of the function: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...
[ "\n Reassign the label numbers consecutively, such that there are no\n missing label numbers.\n\n Parameters\n ----------\n start_label : int, optional\n The starting label number, which should be a positive\n integer. The default is 1.\n\n Examples\n...
Please provide a description of the function:def keep_label(self, label, relabel=False): self.keep_labels(label, relabel=relabel)
[ "\n Keep only the specified label.\n\n Parameters\n ----------\n label : int\n The label number to keep.\n\n relabel : bool, optional\n If `True`, then the single segment will be assigned a label\n value of 1.\n\n Examples\n --------\...
Please provide a description of the function: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)
[ "\n Keep only the specified labels.\n\n Parameters\n ----------\n labels : int, array-like (1D, int)\n The label number(s) to keep.\n\n relabel : bool, optional\n If `True`, then the segmentation image will be relabeled\n such that the labels are i...
Please provide a description of the function:def remove_label(self, label, relabel=False): self.remove_labels(label, relabel=relabel)
[ "\n Remove the label number.\n\n The removed label is assigned a value of zero (i.e.,\n background).\n\n Parameters\n ----------\n label : int\n The label number to remove.\n\n relabel : bool, optional\n If `True`, then the segmentation image wi...
Please provide a description of the function:def remove_labels(self, labels, relabel=False): self.check_labels(labels) self.reassign_label(labels, new_label=0) if relabel: self.relabel_consecutive()
[ "\n Remove one or more labels.\n\n Removed labels are assigned a value of zero (i.e., background).\n\n Parameters\n ----------\n labels : int, array-like (1D, int)\n The label number(s) to remove.\n\n relabel : bool, optional\n If `True`, then the segm...
Please provide a description of the function: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 ' '...
[ "\n Remove labeled segments near the image border.\n\n Labels within the defined border region will be removed.\n\n Parameters\n ----------\n border_width : int\n The width of the border region in pixels.\n\n partial_overlap : bool, optional\n If this ...
Please provide a description of the function: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') ...
[ "\n Remove labeled segments located within a masked region.\n\n Parameters\n ----------\n mask : array_like (bool)\n A boolean mask, with the same shape as the segmentation\n image, where `True` values indicate masked pixels.\n\n partial_overlap : bool, optio...
Please provide a description of the function: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 =...
[ "\n Outline the labeled segments.\n\n The \"outlines\" represent the pixels *just inside* the segments,\n leaving the background pixels unmodified.\n\n Parameters\n ----------\n mask_background : bool, optional\n Set to `True` to mask the background pixels (label...
Please provide a description of the function:def gini(data): flattened = np.sort(np.ravel(data)) N = np.size(flattened) normalization = 1. / (np.abs(np.mean(flattened)) * N * (N - 1)) kernel = (2 * np.arange(1, N + 1) - N - 1) * np.abs(flattened) G = normalization * np.sum(kernel) return ...
[ "\n Calculate the `Gini coefficient\n <https://en.wikipedia.org/wiki/Gini_coefficient>`_ of a 2D array.\n\n The Gini coefficient is calculated using the prescription from `Lotz\n et al. 2004 <http://adsabs.harvard.edu/abs/2004AJ....128..163L>`_\n as:\n\n .. math::\n G = \\\\frac{1}{\\\\left...
Please provide a description of the function: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 ...
[ "\n Calculate the slices for the overlapping part of the bounding\n box and an array of the given shape.\n\n Parameters\n ----------\n shape : tuple of int\n The ``(ny, nx)`` shape of array where the slices are to be\n applied.\n\n Returns\n ---...
Please provide a description of the function:def _to_image_partial_overlap(self, image): # find the overlap of the mask on the output image shape slices_large, slices_small = self._overlap_slices(image.shape) if slices_small is None: return None # no overlap # ...
[ "\n Return an image of the mask in a 2D array, where the mask\n is not fully within the image (i.e. partial or no overlap).\n " ]
Please provide a description of the function: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...
[ "\n Return an image of the mask in a 2D array of the given shape,\n taking any edge effects into account.\n\n Parameters\n ----------\n shape : tuple of int\n The ``(ny, nx)`` shape of the output array.\n\n Returns\n -------\n result : `~numpy.ndarr...
Please provide a description of the function: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: ...
[ "\n Create a cutout from the input data over the mask bounding box,\n taking any edge effects into account.\n\n Parameters\n ----------\n data : array_like\n A 2D array on which to apply the aperture mask.\n\n fill_value : float, optional\n The value i...