idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
54,500
def _to_pixel_params ( self , wcs , mode = 'all' ) : pixel_params = { } x , y = skycoord_to_pixel ( self . positions , wcs , mode = mode ) pixel_params [ 'positions' ] = np . array ( [ x , y ] ) . transpose ( ) crval = SkyCoord ( [ wcs . wcs . crval ] , frame = wcs_to_celestial_frame ( wcs ) , unit = wcs . wcs . cunit ...
Convert the sky aperture parameters to those for a pixel aperture .
54,501
def source_properties ( data , segment_img , error = None , mask = None , background = None , filter_kernel = None , wcs = None , labels = None ) : if not isinstance ( segment_img , SegmentationImage ) : segment_img = SegmentationImage ( segment_img ) if segment_img . shape != data . shape : raise ValueError ( 'segment...
Calculate photometry and morphological properties of sources defined by a labeled segmentation image .
54,502
def _properties_table ( obj , columns = None , exclude_columns = None ) : columns_all = [ 'id' , 'xcentroid' , 'ycentroid' , 'sky_centroid' , 'sky_centroid_icrs' , 'source_sum' , 'source_sum_err' , 'background_sum' , 'background_mean' , 'background_at_centroid' , 'xmin' , 'xmax' , 'ymin' , 'ymax' , 'min_value' , 'max_v...
Construct a ~astropy . table . QTable of source properties from a SourceProperties or SourceCatalog object .
54,503
def _total_mask ( self ) : mask = self . _segment_mask | self . _data_mask if self . _input_mask is not None : mask |= self . _input_mask return mask
Combination of the _segment_mask _input_mask and _data_mask .
54,504
def to_table ( self , columns = None , exclude_columns = None ) : return _properties_table ( self , columns = columns , exclude_columns = exclude_columns )
Create a ~astropy . table . QTable of properties .
54,505
def data_cutout_ma ( self ) : return np . ma . masked_array ( self . _data [ self . _slice ] , mask = self . _total_mask )
A 2D ~numpy . ma . MaskedArray cutout from the data .
54,506
def error_cutout_ma ( self ) : if self . _error is None : return None else : return np . ma . masked_array ( self . _error [ self . _slice ] , mask = self . _total_mask )
A 2D ~numpy . ma . MaskedArray cutout from the input error image .
54,507
def background_cutout_ma ( self ) : if self . _background is None : return None else : return np . ma . masked_array ( self . _background [ self . _slice ] , mask = self . _total_mask )
A 2D ~numpy . ma . MaskedArray cutout from the input background .
54,508
def coords ( self ) : yy , xx = np . nonzero ( self . data_cutout_ma ) return ( yy + self . _slice [ 0 ] . start , xx + self . _slice [ 1 ] . start )
A tuple of two ~numpy . ndarray containing the y and x pixel coordinates of unmasked pixels within the source segment .
54,509
def sky_centroid ( self ) : if self . _wcs is not None : return pixel_to_skycoord ( self . xcentroid . value , self . ycentroid . value , self . _wcs , origin = 0 ) else : return None
The sky coordinates of the centroid within the source segment returned as a ~astropy . coordinates . SkyCoord object .
54,510
def sky_bbox_ll ( self ) : if self . _wcs is not None : return pixel_to_skycoord ( self . xmin . value - 0.5 , self . ymin . value - 0.5 , self . _wcs , origin = 0 ) else : return None
The sky coordinates of the lower - left vertex of the minimal bounding box of the source segment returned as a ~astropy . coordinates . SkyCoord object .
54,511
def sky_bbox_ul ( self ) : if self . _wcs is not None : return pixel_to_skycoord ( self . xmin . value - 0.5 , self . ymax . value + 0.5 , self . _wcs , origin = 0 ) else : return None
The sky coordinates of the upper - left vertex of the minimal bounding box of the source segment returned as a ~astropy . coordinates . SkyCoord object .
54,512
def sky_bbox_lr ( self ) : if self . _wcs is not None : return pixel_to_skycoord ( self . xmax . value + 0.5 , self . ymin . value - 0.5 , self . _wcs , origin = 0 ) else : return None
The sky coordinates of the lower - right vertex of the minimal bounding box of the source segment returned as a ~astropy . coordinates . SkyCoord object .
54,513
def sky_bbox_ur ( self ) : if self . _wcs is not None : return pixel_to_skycoord ( self . xmax . value + 0.5 , self . ymax . value + 0.5 , self . _wcs , origin = 0 ) else : return None
The sky coordinates of the upper - right vertex of the minimal bounding box of the source segment returned as a ~astropy . coordinates . SkyCoord object .
54,514
def min_value ( self ) : if self . _is_completely_masked : return np . nan * self . _data_unit else : return np . min ( self . values )
The minimum pixel value of the data within the source segment .
54,515
def max_value ( self ) : if self . _is_completely_masked : return np . nan * self . _data_unit else : return np . max ( self . values )
The maximum pixel value of the data within the source segment .
54,516
def source_sum ( self ) : if self . _is_completely_masked : return np . nan * self . _data_unit else : return np . sum ( self . values )
The sum of the unmasked data values within the source segment .
54,517
def source_sum_err ( self ) : if self . _error is not None : if self . _is_completely_masked : return np . nan * self . _error_unit else : return np . sqrt ( np . sum ( self . _error_values ** 2 ) ) else : return None
The uncertainty of ~photutils . SourceProperties . source_sum propagated from the input error array .
54,518
def background_sum ( self ) : if self . _background is not None : if self . _is_completely_masked : return np . nan * self . _background_unit else : return np . sum ( self . _background_values ) else : return None
The sum of background values within the source segment .
54,519
def background_mean ( self ) : if self . _background is not None : if self . _is_completely_masked : return np . nan * self . _background_unit else : return np . mean ( self . _background_values ) else : return None
The mean of background values within the source segment .
54,520
def background_at_centroid ( self ) : from scipy . ndimage import map_coordinates if self . _background is not None : if ( self . _is_completely_masked or np . any ( ~ np . isfinite ( self . centroid ) ) ) : return np . nan * self . _background_unit else : value = map_coordinates ( self . _background , [ [ self . ycent...
The value of the background at the position of the source centroid .
54,521
def perimeter ( self ) : if self . _is_completely_masked : return np . nan * u . pix else : from skimage . measure import perimeter return perimeter ( ~ self . _total_mask , neighbourhood = 4 ) * u . pix
The total perimeter of the source segment approximated lines through the centers of the border pixels using a 4 - connectivity .
54,522
def inertia_tensor ( self ) : mu = self . moments_central a = mu [ 0 , 2 ] b = - mu [ 1 , 1 ] c = mu [ 2 , 0 ] return np . array ( [ [ a , b ] , [ b , c ] ] ) * u . pix ** 2
The inertia tensor of the source for the rotation around its center of mass .
54,523
def covariance ( self ) : mu = self . moments_central if mu [ 0 , 0 ] != 0 : m = mu / mu [ 0 , 0 ] covariance = self . _check_covariance ( np . array ( [ [ m [ 0 , 2 ] , m [ 1 , 1 ] ] , [ m [ 1 , 1 ] , m [ 2 , 0 ] ] ] ) ) return covariance * u . pix ** 2 else : return np . empty ( ( 2 , 2 ) ) * np . nan * u . pix ** 2
The covariance matrix of the 2D Gaussian function that has the same second - order moments as the source .
54,524
def covariance_eigvals ( self ) : if not np . isnan ( np . sum ( self . covariance ) ) : eigvals = np . linalg . eigvals ( self . covariance ) if np . any ( eigvals < 0 ) : return ( np . nan , np . nan ) * u . pix ** 2 return ( np . max ( eigvals ) , np . min ( eigvals ) ) * u . pix ** 2 else : return ( np . nan , np ....
The two eigenvalues of the covariance matrix in decreasing order .
54,525
def eccentricity ( self ) : l1 , l2 = self . covariance_eigvals if l1 == 0 : return 0. return np . sqrt ( 1. - ( l2 / l1 ) )
The eccentricity of the 2D Gaussian function that has the same second - order moments as the source .
54,526
def orientation ( self ) : a , b , b , c = self . covariance . flat if a < 0 or c < 0 : return np . nan * u . rad return 0.5 * np . arctan2 ( 2. * b , ( a - c ) )
The angle in radians between the x axis and the major axis of the 2D Gaussian function that has the same second - order moments as the source . The angle increases in the counter - clockwise direction .
54,527
def _mesh_values ( data , box_size ) : data = np . ma . asanyarray ( data ) ny , nx = data . shape nyboxes = ny // box_size nxboxes = nx // box_size ny_crop = nyboxes * box_size nx_crop = nxboxes * box_size data = data [ 0 : ny_crop , 0 : nx_crop ] data = np . ma . swapaxes ( data . reshape ( nyboxes , box_size , nxbox...
Extract all the data values in boxes of size box_size .
54,528
def std_blocksum ( data , block_sizes , 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 stds = [ ] block_sizes ...
Calculate the standard deviation of block - summed data values at sizes of block_sizes .
54,529
def nstar ( self , image , star_groups ) : result_tab = Table ( ) for param_tab_name in self . _pars_to_output . keys ( ) : result_tab . add_column ( Column ( name = param_tab_name ) ) unc_tab = Table ( ) for param , isfixed in self . psf_model . fixed . items ( ) : if not isfixed : unc_tab . add_column ( Column ( name...
Fit as appropriate a compound or single model to the given star_groups . Groups are fitted sequentially from the smallest to the biggest . In each iteration image is subtracted by the previous fitted group .
54,530
def _get_uncertainties ( self , star_group_size ) : unc_tab = Table ( ) for param_name in self . psf_model . param_names : if not self . psf_model . fixed [ param_name ] : unc_tab . add_column ( Column ( name = param_name + "_unc" , data = np . empty ( star_group_size ) ) ) if 'param_cov' in self . fitter . fit_info . ...
Retrieve uncertainties on fitted parameters from the fitter object .
54,531
def _model_params2table ( self , fit_model , star_group_size ) : param_tab = Table ( ) for param_tab_name in self . _pars_to_output . keys ( ) : param_tab . add_column ( Column ( name = param_tab_name , data = np . empty ( star_group_size ) ) ) if star_group_size > 1 : for i in range ( star_group_size ) : for param_tab...
Place fitted parameters into an astropy table .
54,532
def _do_photometry ( self , param_tab , n_start = 1 ) : output_table = Table ( ) self . _define_fit_param_names ( ) for ( init_parname , fit_parname ) in zip ( self . _pars_to_set . keys ( ) , self . _pars_to_output . keys ( ) ) : output_table . add_column ( Column ( name = init_parname ) ) output_table . add_column ( ...
Helper function which performs the iterations of the photometry process .
54,533
def pixel_scale_angle_at_skycoord ( skycoord , wcs , offset = 1. * u . arcsec ) : coord = skycoord . represent_as ( 'unitspherical' ) coord_new = UnitSphericalRepresentation ( coord . lon , coord . lat + offset ) coord_offset = skycoord . realize_frame ( coord_new ) x_offset , y_offset = skycoord_to_pixel ( coord_offse...
Calculate the pixel scale and WCS rotation angle at the position of a SkyCoord coordinate .
54,534
def pixel_to_icrs_coords ( x , y , wcs ) : icrs_coords = pixel_to_skycoord ( x , y , wcs ) . icrs icrs_ra = icrs_coords . ra . degree * u . deg icrs_dec = icrs_coords . dec . degree * u . deg return icrs_ra , icrs_dec
Convert pixel coordinates to ICRS Right Ascension and Declination .
54,535
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_ar...
Convolve a 2D image with a 2D kernel .
54,536
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 ....
Convert a 2D PSF model to one suitable for use with BasicPSFPhotometry or its subclasses .
54,537
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 : 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 .
54,538
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 .
54,539
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_...
Calculate a pixel - wise threshold image that can be used to detect sources .
54,540
def run_cmd ( cmd ) : try : p = sp . Popen ( cmd , stdout = sp . PIPE , stderr = sp . PIPE ) 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 _A...
Run a command in a subprocess given as a list of command - line arguments .
54,541
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 .
54,542
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 .
54,543
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 .
54,544
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 .
54,545
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 .
54,546
def find_center ( self , image , threshold = 0.1 , verbose = True ) : self . _centerer_mask_half_size = len ( IN_MASK ) / 2 self . centerer_threshold = threshold 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 ....
Find the center of a galaxy .
54,547
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 .
54,548
def initialize_sector_geometry ( self , phi ) : sma1 , sma2 = self . bounding_ellipses ( ) eps_ = 1. - self . eps 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 . sq...
Initialize geometry attributes associated with an elliptical sector at the given polar angle phi .
54,549
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 .
54,550
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 .
54,551
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 .
54,552
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 .
54,553
def _select_meshes ( self , data ) : nmasked = np . ma . count_masked ( data , axis = 1 ) threshold_npixels = self . exclude_percentile / 100. * self . box_npixels mesh_idx = np . where ( ( nmasked <= threshold_npixels ) & ( nmasked != self . box_npixels ) ) [ 0 ] if len ( mesh_idx ) == 0 : raise ValueError ( 'All mesh...
Define the x and y indices with respect to the low - resolution mesh image of the meshes to use for the background interpolation .
54,554
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 : data_ma...
Prepare the data .
54,555
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 ...
Convert a 1D array of mesh values to a masked 2D mesh array given the 1D mesh indices mesh_idx .
54,556
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 ...
Use IDW interpolation to fill in any masked pixels in the low - resolution 2D mesh background and background RMS images .
54,557
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 . sh...
Selectively filter only pixels above filter_threshold in the background mesh .
54,558
def _filter_meshes ( self ) : from scipy . ndimage import generic_filter try : nanmedian_func = np . nanmedian except AttributeError : from scipy . stats import nanmedian nanmedian_func = nanmedian if self . filter_threshold is None : self . background_mesh = generic_filter ( self . background_mesh , nanmedian_func , s...
Apply a 2D median filter to the low - resolution 2D mesh including only pixels inside the image at the borders .
54,559
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 idx = self . _select_meshes ( data_sigclip ) self . mesh_idx = self . mesh_idx [ idx ] self . _data_sigclip = data_sigclip [ ...
Calculate the background and background RMS estimate in each of the meshes .
54,560
def _calc_coordinates ( self ) : 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 ] ) nx , ny = self . data . shape self . data_c...
Calculate the coordinates to use when calling an interpolator .
54,561
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 RectangularA...
Plot the low - resolution mesh boxes on a matplotlib Axes instance .
54,562
def extract ( self ) : 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 .
54,563
def update ( self ) : step = self . geometry . astep s = self . extract ( ) self . mean = np . mean ( s [ 2 ] ) gradient , gradient_error = self . _get_gradient ( step ) previous_gradient = self . gradient if not previous_gradient : previous_gradient = - 0.05 if gradient >= ( previous_gradient / 3. ) : gradient , gradi...
Update this ~photutils . isophote . EllipseSample instance .
54,564
def fit ( self , conver = DEFAULT_CONVERGENCE , minit = DEFAULT_MINIT , maxit = DEFAULT_MAXIT , fflag = DEFAULT_FFLAG , maxgerr = DEFAULT_MAXGERR , going_inwards = False ) : sample = self . _sample lexceed = False minimum_amplitude_value = np . Inf minimum_amplitude_sample = None for iter in range ( maxit ) : sample . ...
Fit an elliptical isophote .
54,565
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' ] . dat...
Extract cutout images from a single image centered on stars defined in the single input catalog .
54,566
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...
Estimate the star s flux by summing values in the input cutout array .
54,567
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 .
54,568
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 .
54,569
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 .
54,570
def slices ( self ) : return ( slice ( self . iymin , self . iymax ) , slice ( self . ixmin , self . ixmax ) )
The bounding box as a tuple of slice objects .
54,571
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 .
54,572
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 .
54,573
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 .
54,574
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 ) if min_separation is None : footprint = kernel . mask . astype ( np . bool ) else ...
Find stars in an image .
54,575
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 .
54,576
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...
Detect sources above a specified threshold value in an image and return a ~photutils . segmentation . SegmentationImage object .
54,577
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 = mas...
Make a source mask using source segmentation and binary dilation .
54,578
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 .
54,579
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 .
54,580
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 .
54,581
def get_index ( self , label ) : self . check_labels ( label ) return np . searchsorted ( self . labels , label )
Find the index of the input label .
54,582
def get_indices ( self , labels ) : self . check_labels ( labels ) return np . searchsorted ( self . labels , labels )
Find the indices of the input labels .
54,583
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 .
54,584
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 .
54,585
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 .
54,586
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 self . data = idx [ self . dat...
Reassign one or more label numbers .
54,587
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 . ...
Reassign the label numbers consecutively such that there are no missing label numbers .
54,588
def keep_label ( self , label , relabel = False ) : self . keep_labels ( label , relabel = relabel )
Keep only the specified label .
54,589
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 .
54,590
def remove_label ( self , label , relabel = False ) : self . remove_labels ( label , relabel = relabel )
Remove the label number .
54,591
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 .
54,592
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...
Remove labeled segments near the image border .
54,593
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_lab...
Remove labeled segments located within a masked region .
54,594
def outline_segments ( self , mask_background = False ) : from scipy . ndimage import grey_erosion , grey_dilation 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 , fo...
Outline the labeled segments .
54,595
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 : return None , None...
Calculate the slices for the overlapping part of the bounding box and an array of the given shape .
54,596
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 : i...
Return an image of the mask in a 2D array of the given shape taking any edge effects into account .
54,597
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 : if copy : cutout = np . copy...
Create a cutout from the input data over the mask bounding box taking any edge effects into account .
54,598
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 .
54,599
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 != dat...
Deblend overlapping sources labeled in a segmentation image .