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 ) scale , angle = pixel_scale_angle_at_skycoord ( crval , wcs ) params = self . _params [ : ] theta_key = 'theta' if theta_key in self . _params : pixel_params [ theta_key ] = ( self . theta + angle ) . to ( u . radian ) . value params . remove ( theta_key ) param_vals = [ getattr ( self , param ) for param in params ] if param_vals [ 0 ] . unit . physical_type == 'angle' : for param , param_val in zip ( params , param_vals ) : pixel_params [ param ] = ( param_val / scale ) . to ( u . pixel ) . value else : for param , param_val in zip ( params , param_vals ) : pixel_params [ param ] = param_val . value return pixel_params
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_img and data must have the same shape.' ) if filter_kernel is not None : filtered_data = filter_data ( data , filter_kernel , mode = 'constant' , fill_value = 0.0 , check_normalization = True ) else : filtered_data = None if labels is None : labels = segment_img . labels labels = np . atleast_1d ( labels ) sources_props = [ ] for label in labels : if label not in segment_img . labels : warnings . warn ( 'label {} is not in the segmentation image.' . format ( label ) , AstropyUserWarning ) continue sources_props . append ( SourceProperties ( data , segment_img , label , filtered_data = filtered_data , error = error , mask = mask , background = background , wcs = wcs ) ) if len ( sources_props ) == 0 : raise ValueError ( 'No sources are defined.' ) return SourceCatalog ( sources_props , wcs = wcs )
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_value' , 'minval_xpos' , 'minval_ypos' , 'maxval_xpos' , 'maxval_ypos' , 'area' , 'equivalent_radius' , 'perimeter' , 'semimajor_axis_sigma' , 'semiminor_axis_sigma' , 'eccentricity' , 'orientation' , 'ellipticity' , 'elongation' , 'covar_sigx2' , 'covar_sigxy' , 'covar_sigy2' , 'cxx' , 'cxy' , 'cyy' ] table_columns = None if exclude_columns is not None : table_columns = [ s for s in columns_all if s not in exclude_columns ] if columns is not None : table_columns = np . atleast_1d ( columns ) if table_columns is None : table_columns = columns_all tbl = QTable ( ) for column in table_columns : values = getattr ( obj , column ) if isinstance ( obj , SourceProperties ) : values = np . atleast_1d ( values ) if isinstance ( values [ 0 ] , SkyCoord ) : values = SkyCoord ( values ) tbl [ column ] = values return tbl
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 . ycentroid . value ] , [ self . xcentroid . value ] ] , order = 1 , mode = 'nearest' ) [ 0 ] return value * self . _background_unit else : return None
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 . nan ) * u . pix ** 2
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 , nxboxes , box_size ) , 1 , 2 ) . reshape ( nyboxes * nxboxes , box_size * box_size ) idx = np . where ( np . ma . count_masked ( data , axis = 1 ) == 0 ) return data [ idx ]
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 = np . atleast_1d ( block_sizes ) for block_size in block_sizes : mesh_values = _mesh_values ( data , block_size ) block_sums = np . sum ( mesh_values , axis = 1 ) stds . append ( np . std ( block_sums ) ) return np . array ( stds )
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 = param + "_unc" ) ) y , x = np . indices ( image . shape ) star_groups = star_groups . group_by ( 'group_id' ) for n in range ( len ( star_groups . groups ) ) : group_psf = get_grouped_psf_model ( self . psf_model , star_groups . groups [ n ] , self . _pars_to_set ) usepixel = np . zeros_like ( image , dtype = np . bool ) for row in star_groups . groups [ n ] : usepixel [ overlap_slices ( large_array_shape = image . shape , small_array_shape = self . fitshape , position = ( row [ 'y_0' ] , row [ 'x_0' ] ) , mode = 'trim' ) [ 0 ] ] = True fit_model = self . fitter ( group_psf , x [ usepixel ] , y [ usepixel ] , image [ usepixel ] ) param_table = self . _model_params2table ( fit_model , len ( star_groups . groups [ n ] ) ) result_tab = vstack ( [ result_tab , param_table ] ) if 'param_cov' in self . fitter . fit_info . keys ( ) : unc_tab = vstack ( [ unc_tab , self . _get_uncertainties ( len ( star_groups . groups [ n ] ) ) ] ) try : from astropy . nddata . utils import NoOverlapError except ImportError : raise ImportError ( "astropy 1.1 or greater is required in " "order to use this class." ) try : image = subtract_psf ( image , self . psf_model , param_table , subshape = self . fitshape ) except NoOverlapError : pass if 'param_cov' in self . fitter . fit_info . keys ( ) : result_tab = hstack ( [ result_tab , unc_tab ] ) return result_tab , image
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 . keys ( ) : if self . fitter . fit_info [ 'param_cov' ] is not None : k = 0 n_fit_params = len ( unc_tab . colnames ) for i in range ( star_group_size ) : unc_tab [ i ] = np . sqrt ( np . diag ( self . fitter . fit_info [ 'param_cov' ] ) ) [ k : k + n_fit_params ] k = k + n_fit_params return unc_tab
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_name , param_name in self . _pars_to_output . items ( ) : param_tab [ param_tab_name ] [ i ] = getattr ( fit_model , param_name + '_' + str ( i ) ) . value else : for param_tab_name , param_name in self . _pars_to_output . items ( ) : param_tab [ param_tab_name ] = getattr ( fit_model , param_name ) . value return 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 ( Column ( name = fit_parname ) ) sources = self . finder ( self . _residual_image ) n = n_start while ( sources is not None and ( self . niters is None or n <= self . niters ) ) : apertures = CircularAperture ( ( sources [ 'xcentroid' ] , sources [ 'ycentroid' ] ) , r = self . aperture_radius ) sources [ 'aperture_flux' ] = aperture_photometry ( self . _residual_image , apertures ) [ 'aperture_sum' ] init_guess_tab = Table ( names = [ 'id' , 'x_0' , 'y_0' , 'flux_0' ] , data = [ sources [ 'id' ] , sources [ 'xcentroid' ] , sources [ 'ycentroid' ] , sources [ 'aperture_flux' ] ] ) for param_tab_name , param_name in self . _pars_to_set . items ( ) : if param_tab_name not in ( [ 'x_0' , 'y_0' , 'flux_0' ] ) : init_guess_tab . add_column ( Column ( name = param_tab_name , data = ( getattr ( self . psf_model , param_name ) * np . ones ( len ( sources ) ) ) ) ) star_groups = self . group_maker ( init_guess_tab ) table , self . _residual_image = super ( ) . nstar ( self . _residual_image , star_groups ) star_groups = star_groups . group_by ( 'group_id' ) table = hstack ( [ star_groups , table ] ) table [ 'iter_detected' ] = n * np . ones ( table [ 'x_fit' ] . shape , dtype = np . int32 ) output_table = vstack ( [ output_table , table ] ) with warnings . catch_warnings ( ) : warnings . simplefilter ( 'ignore' , NoDetectionsWarning ) sources = self . finder ( self . _residual_image ) n += 1 return output_table
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_offset , wcs , mode = 'all' ) x , y = skycoord_to_pixel ( skycoord , wcs , mode = 'all' ) dx = x_offset - x dy = y_offset - y scale = offset . to ( u . arcsec ) / ( np . hypot ( dx , dy ) * u . pixel ) angle = ( np . arctan2 ( dy , dx ) * u . radian ) . to ( u . deg ) return scale , angle
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_array ) , 1.0 ) : warnings . warn ( 'The kernel is not normalized.' , AstropyUserWarning ) return ndimage . convolve ( data . astype ( float ) , kernel_array , mode = mode , cval = fill_value ) else : return data
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 . 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 : 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 for pnm in outmod . param_names : outmod . fixed [ pnm ] = pnm not in ( xname , yname , fluxname ) outmod . xname = xname outmod . yname = yname outmod . fluxname = fluxname 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 .
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 = 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 .
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_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 .
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 _AHBootstrapSystemExit ( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}' . format ( ' ' . join ( cmd ) , str ( e ) ) ) try : stdio_encoding = locale . getdefaultlocale ( ) [ 1 ] or 'latin1' except ValueError : stdio_encoding = 'latin1' 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 .
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 . 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 ) 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 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 ) : 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 ] 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 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 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 .
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 . sqrt ( ( eps_ * math . cos ( self . _phi1 ) ) ** 2 + ( math . sin ( self . _phi1 ) ) ** 2 ) ) 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 ) ) 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 ) ) self . sector_angular_width = max ( min ( ( self . _area_factor / ( r3 - r4 ) / r4 ) , self . _phi_max ) , self . _phi_min ) vertex_x = np . zeros ( shape = 4 , dtype = float ) vertex_y = np . zeros ( shape = 4 , dtype = float ) 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 .
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 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 .
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 = np . ma . masked_array ( self . data , mask = self . mask ) else : 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 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 ) self . mesh_idx = self . _select_meshes ( mesh_data ) self . _mesh_data = mesh_data [ self . mesh_idx , : ] return
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 . mesh_yidx , self . mesh_xidx ] = data if len ( self . mesh_idx ) == self . nboxes : return data2d else : 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 .
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 , 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 .
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 . 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 .
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 , 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 : 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 .
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 [ idx ] self . _mesh_shape = ( self . nyboxes , self . nxboxes ) self . mesh_yidx , self . mesh_xidx = np . unravel_index ( self . mesh_idx , self . _mesh_shape ) self . _bkg1d = self . bkg_estimator ( self . _data_sigclip , axis = 1 ) self . _bkgrms1d = self . bkgrms_estimator ( self . _data_sigclip , axis = 1 ) 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 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 .
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_coords = np . array ( list ( product ( range ( ny ) , range ( nx ) ) ) )
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 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 .
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 , gradient_error = self . _get_gradient ( 2 * step ) 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 .
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 . update ( ) values = sample . extract ( ) 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_index = np . argmax ( np . abs ( coeffs [ 1 : ] ) ) largest_harmonic = coeffs [ 1 : ] [ largest_harmonic_index ] if abs ( largest_harmonic ) < minimum_amplitude_value : minimum_amplitude_value = abs ( largest_harmonic ) minimum_amplitude_sample = sample 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 ) ) : if iter >= minit - 1 : sample . update ( ) return Isophote ( sample , iter + 1 , True , 0 ) if sample . actual_points < ( sample . total_points * fflag ) : minimum_amplitude_sample . update ( ) return Isophote ( minimum_amplitude_sample , iter + 1 , True , 1 ) corrector = _correctors [ largest_harmonic_index ] sample = corrector . correct ( sample , largest_harmonic ) sample . update ( ) proceed , lexceed = self . _check_conditions ( sample , maxgerr , going_inwards , lexceed ) if not proceed : sample . update ( ) return Isophote ( sample , iter + 1 , True , - 1 ) minimum_amplitude_sample . update ( ) return Isophote ( minimum_amplitude_sample , maxit , True , 2 )
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' ] . 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 .
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_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 .
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 : 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 ) if not exclude_border : ypad = kernel . yradius xpad = kernel . xradius pad = ( ( ypad , ypad ) , ( xpad , xpad ) ) 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. ] ) with warnings . catch_warnings ( ) : 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 : 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 if y0 < 0 or y1 > data . shape [ 0 ] : continue slices = ( slice ( y0 , y1 ) , slice ( x0 , x1 ) ) data_cutout = data [ slices ] convdata_cutout = convolved_data [ slices ] 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 .
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_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 ) 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 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 .
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 = 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 .
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 . data ] if relabel : self . relabel_consecutive ( )
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 . nlabels ) + start_label self . data = new_labels [ self . data ]
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 , : ] = 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 .
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_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 .
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 , 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 .
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 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 .
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 : 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 .
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 ( 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 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 .
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 != 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 ) 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 : 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 last_label += source_deblended . nlabels if relabel : segm_deblended . relabel_consecutive ( ) return segm_deblended
Deblend overlapping sources labeled in a segmentation image .