idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
242,400
def background_at_centroid ( self ) : from scipy . ndimage import map_coordinates if self . _background is not None : # centroid can still be NaN if all data values are <= 0 if ( self . _is_completely_masked or np . any ( ~ np . isfinite ( self . centroid ) ) ) : return np . nan * self . _background_unit # unit for tab...
The value of the background at the position of the source centroid .
157
14
242,401
def perimeter ( self ) : if self . _is_completely_masked : return np . nan * u . pix # unit for table 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 .
59
23
242,402
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 .
67
16
242,403
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 .
120
23
242,404
def covariance_eigvals ( self ) : if not np . isnan ( np . sum ( self . covariance ) ) : eigvals = np . linalg . eigvals ( self . covariance ) if np . any ( eigvals < 0 ) : # negative variance return ( np . nan , np . nan ) * u . pix ** 2 # pragma: no cover return ( np . max ( eigvals ) , np . min ( eigvals ) ) * u . p...
The two eigenvalues of the covariance matrix in decreasing order .
132
14
242,405
def eccentricity ( self ) : l1 , l2 = self . covariance_eigvals if l1 == 0 : return 0. # pragma: no cover return np . sqrt ( 1. - ( l2 / l1 ) )
The eccentricity of the 2D Gaussian function that has the same second - order moments as the source .
53
22
242,406
def orientation ( self ) : a , b , b , c = self . covariance . flat if a < 0 or c < 0 : # negative variance return np . nan * u . rad # pragma: no cover 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 .
69
43
242,407
def _mesh_values ( data , box_size ) : data = np . ma . asanyarray ( data ) ny , nx = data . shape nyboxes = ny // box_size nxboxes = nx // box_size # include only complete boxes ny_crop = nyboxes * box_size nx_crop = nxboxes * box_size data = data [ 0 : ny_crop , 0 : nx_crop ] # a reshaped 2D masked array with mesh da...
Extract all the data values in boxes of size box_size .
212
14
242,408
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 .
176
20
242,409
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 .
565
40
242,410
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 .
221
12
242,411
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 .
218
9
242,412
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 .
617
12
242,413
def pixel_scale_angle_at_skycoord ( skycoord , wcs , offset = 1. * u . arcsec ) : # We take a point directly "above" (in latitude) the input position # and convert it to pixel coordinates, then we use the pixel deltas # between the input and offset point to calculate the pixel scale and # angle. # Find the coordinates ...
Calculate the pixel scale and WCS rotation angle at the position of a SkyCoord coordinate .
298
20
242,414
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 .
88
13
242,415
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 .
223
13
242,416
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 .
536
24
242,417
def get_grouped_psf_model ( template_psf_model , star_group , pars_to_set ) : group_psf = None for star in star_group : psf_to_add = template_psf_model . copy ( ) for param_tab_name , param_name in pars_to_set . items ( ) : setattr ( psf_to_add , param_name , star [ param_tab_name ] ) if group_psf is None : # this is t...
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 .
147
33
242,418
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 .
65
26
242,419
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 .
385
17
242,420
def run_cmd ( cmd ) : try : p = sp . Popen ( cmd , stdout = sp . PIPE , stderr = sp . PIPE ) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout , stderr = p . communicate ( ) except OSError ...
Run a command in a subprocess given as a list of command - line arguments .
418
17
242,421
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 .
51
18
242,422
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 .
51
18
242,423
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 .
50
17
242,424
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 .
50
17
242,425
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 .
77
7
242,426
def find_center ( self , image , threshold = 0.1 , verbose = True ) : self . _centerer_mask_half_size = len ( IN_MASK ) / 2 self . centerer_threshold = threshold # number of pixels in each mask sz = len ( IN_MASK ) self . _centerer_ones_in = np . ma . masked_array ( np . ones ( shape = ( sz , sz ) ) , mask = IN_MASK ) ...
Find the center of a galaxy .
840
7
242,427
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 .
63
12
242,428
def initialize_sector_geometry ( self , phi ) : # These polar radii bound the region between the inner # and outer ellipses that define the sector. sma1 , sma2 = self . bounding_ellipses ( ) eps_ = 1. - self . eps # polar vector at one side of the elliptical sector self . _phi1 = phi - self . sector_angular_width / 2. ...
Initialize geometry attributes associated with an elliptical sector at the given polar angle phi .
757
18
242,429
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 .
98
24
242,430
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 .
46
21
242,431
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 .
64
16
242,432
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 .
65
15
242,433
def _select_meshes ( self , data ) : # the number of masked pixels in each mesh nmasked = np . ma . count_masked ( data , axis = 1 ) # meshes that contain more than ``exclude_percentile`` percent # masked pixels are excluded: # - for exclude_percentile=0, good meshes will be only where # nmasked=0 # - meshes where nmas...
Define the x and y indices with respect to the low - resolution mesh image of the meshes to use for the background interpolation .
247
27
242,434
def _prepare_data ( self ) : self . nyboxes = self . data . shape [ 0 ] // self . box_size [ 0 ] self . nxboxes = self . data . shape [ 1 ] // self . box_size [ 1 ] yextra = self . data . shape [ 0 ] % self . box_size [ 0 ] xextra = self . data . shape [ 1 ] % self . box_size [ 1 ] if ( xextra + yextra ) == 0 : # no re...
Prepare the data .
419
5
242,435
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 .
216
27
242,436
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 .
161
26
242,437
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 .
162
15
242,438
def _filter_meshes ( self ) : from scipy . ndimage import generic_filter try : nanmedian_func = np . nanmedian # numpy >= 1.9 except AttributeError : # pragma: no cover from scipy . stats import nanmedian nanmedian_func = nanmedian if self . filter_threshold is None : # filter the entire arrays self . background_mesh =...
Apply a 2D median filter to the low - resolution 2D mesh including only pixels inside the image at the borders .
266
24
242,439
def _calc_bkg_bkgrms ( self ) : if self . sigma_clip is not None : data_sigclip = self . sigma_clip ( self . _mesh_data , axis = 1 ) else : data_sigclip = self . _mesh_data del self . _mesh_data # preform mesh rejection on sigma-clipped data (i.e. for any # newly-masked pixels) idx = self . _select_meshes ( data_sigcli...
Calculate the background and background RMS estimate in each of the meshes .
564
16
242,440
def _calc_coordinates ( self ) : # the position coordinates used to initialize an interpolation self . y = ( self . mesh_yidx * self . box_size [ 0 ] + ( self . box_size [ 0 ] - 1 ) / 2. ) self . x = ( self . mesh_xidx * self . box_size [ 1 ] + ( self . box_size [ 1 ] - 1 ) / 2. ) self . yx = np . column_stack ( [ self...
Calculate the coordinates to use when calling an interpolator .
168
13
242,441
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 Rectangular...
Plot the low - resolution mesh boxes on a matplotlib Axes instance .
168
16
242,442
def extract ( self ) : # the sample values themselves are kept cached to prevent # multiple calls to the integrator code. if self . values is not None : return self . values else : s = self . _extract ( ) self . values = s return s
Extract sample data by scanning an elliptical path over the image array .
55
15
242,443
def update ( self ) : step = self . geometry . astep # Update the mean value first, using extraction from main sample. s = self . extract ( ) self . mean = np . mean ( s [ 2 ] ) # Get sample with same geometry but at a different distance from # center. Estimate gradient from there. gradient , gradient_error = self . _g...
Update this ~photutils . isophote . EllipseSample instance .
359
16
242,444
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 .
527
19
242,445
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 .
138
17
242,446
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 .
59
20
242,447
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 .
94
24
242,448
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 .
116
18
242,449
def slices ( self ) : return ( slice ( self . iymin , self . iymax ) , slice ( self . ixmin , self . ixmax ) )
The bounding box as a tuple of slice objects .
38
11
242,450
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 .
70
17
242,451
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 .
102
19
242,452
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 .
63
21
242,453
def _find_stars ( data , kernel , threshold_eff , min_separation = None , mask = None , exclude_border = False ) : convolved_data = filter_data ( data , kernel . data , mode = 'constant' , fill_value = 0.0 , check_normalization = False ) # define a local footprint for the peak finder if min_separation is None : # daofi...
Find stars in an image .
775
6
242,454
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 .
62
5
242,455
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 .
442
26
242,456
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 .
284
13
242,457
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
25
242,458
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 .
53
6
242,459
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 .
55
7
242,460
def get_index ( self , label ) : self . check_labels ( label ) return np . searchsorted ( self . labels , label )
Find the index of the input label .
32
8
242,461
def get_indices ( self , labels ) : self . check_labels ( labels ) return np . searchsorted ( self . labels , labels )
Find the indices of the input labels .
33
8
242,462
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 .
42
21
242,463
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 .
49
32
242,464
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 .
40
11
242,465
def reassign_labels ( self , labels , new_label , relabel = False ) : self . check_labels ( labels ) labels = np . atleast_1d ( labels ) if len ( labels ) == 0 : return idx = np . zeros ( self . max_label + 1 , dtype = int ) idx [ self . labels ] = self . labels idx [ labels ] = new_label # calling the data setter rese...
Reassign one or more label numbers .
129
9
242,466
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 .
124
17
242,467
def keep_label ( self , label , relabel = False ) : self . keep_labels ( label , relabel = relabel )
Keep only the specified label .
30
6
242,468
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 .
73
6
242,469
def remove_label ( self , label , relabel = False ) : self . remove_labels ( label , relabel = relabel )
Remove the label number .
30
5
242,470
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
6
242,471
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 .
156
8
242,472
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 .
145
9
242,473
def outline_segments ( self , mask_background = False ) : from scipy . ndimage import grey_erosion , grey_dilation # mode='constant' ensures outline is included on the image borders selem = np . array ( [ [ 0 , 1 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 1 , 0 ] ] ) eroded = grey_erosion ( self . data , footprint = selem , mode = ...
Outline the labeled segments .
192
6
242,474
def _overlap_slices ( self , shape ) : if len ( shape ) != 2 : raise ValueError ( 'input shape must have 2 elements.' ) xmin = self . bbox . ixmin xmax = self . bbox . ixmax ymin = self . bbox . iymin ymax = self . bbox . iymax if xmin >= shape [ 1 ] or ymin >= shape [ 0 ] or xmax <= 0 or ymax <= 0 : # no overlap of th...
Calculate the slices for the overlapping part of the bounding box and an array of the given shape .
239
22
242,475
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 : #...
Return an image of the mask in a 2D array of the given shape taking any edge effects into account .
120
22
242,476
def cutout ( self , data , fill_value = 0. , copy = False ) : data = np . asanyarray ( data ) if data . ndim != 2 : raise ValueError ( 'data must be a 2D array.' ) partial_overlap = False if self . bbox . ixmin < 0 or self . bbox . iymin < 0 : partial_overlap = True if not partial_overlap : # try this for speed -- the ...
Create a cutout from the input data over the mask bounding box taking any edge effects into account .
283
21
242,477
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 .
50
17
242,478
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 .
567
12
242,479
def _moments_central ( data , center = None , order = 1 ) : data = np . asarray ( data ) . astype ( float ) if data . ndim != 2 : raise ValueError ( 'data must be a 2D array.' ) if center is None : from . . centroids import centroid_com center = centroid_com ( data ) indices = np . ogrid [ [ slice ( 0 , i ) for i in da...
Calculate the central image moments up to the specified order .
178
13
242,480
def first_and_second_harmonic_function ( phi , c ) : return ( c [ 0 ] + c [ 1 ] * np . sin ( phi ) + c [ 2 ] * np . cos ( phi ) + c [ 3 ] * np . sin ( 2 * phi ) + c [ 4 ] * np . cos ( 2 * phi ) )
Compute the harmonic function value used to calculate the corrections for ellipse fitting .
81
17
242,481
def _radial_distance ( shape ) : if len ( shape ) != 2 : raise ValueError ( 'shape must have only 2 elements' ) position = ( np . asarray ( shape ) - 1 ) / 2. x = np . arange ( shape [ 1 ] ) - position [ 1 ] y = np . arange ( shape [ 0 ] ) - position [ 0 ] xx , yy = np . meshgrid ( x , y ) return np . sqrt ( xx ** 2 + ...
Return an array where each value is the Euclidean distance from the array center .
110
17
242,482
def load_spitzer_image ( show_progress = False ) : # pragma: no cover path = get_path ( 'spitzer_example_image.fits' , location = 'remote' , show_progress = show_progress ) hdu = fits . open ( path ) [ 0 ] return hdu
Load a 4 . 5 micron Spitzer image .
67
11
242,483
def load_spitzer_catalog ( show_progress = False ) : # pragma: no cover path = get_path ( 'spitzer_example_catalog.xml' , location = 'remote' , show_progress = show_progress ) table = Table . read ( path ) return table
Load a 4 . 5 micron Spitzer catalog .
64
11
242,484
def load_irac_psf ( channel , show_progress = False ) : # pragma: no cover channel = int ( channel ) if channel < 1 or channel > 4 : raise ValueError ( 'channel must be 1, 2, 3, or 4' ) fn = 'irac_ch{0}_flight.fits' . format ( channel ) path = get_path ( fn , location = 'remote' , show_progress = show_progress ) hdu = ...
Load a Spitzer IRAC PSF image .
114
10
242,485
def fit_isophote ( self , sma , step = 0.1 , conver = DEFAULT_CONVERGENCE , minit = DEFAULT_MINIT , maxit = DEFAULT_MAXIT , fflag = DEFAULT_FFLAG , maxgerr = DEFAULT_MAXGERR , sclip = 3. , nclip = 0 , integrmode = BILINEAR , linear = False , maxrit = None , noniterate = False , going_inwards = False , isophote_list = N...
Fit a single isophote with a given semimajor axis length .
323
15
242,486
def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyCircularAperture ( * * sky_params )
Convert the aperture to a SkyCircularAperture object defined in celestial coordinates .
50
17
242,487
def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyCircularAnnulus ( * * sky_params )
Convert the aperture to a SkyCircularAnnulus object defined in celestial coordinates .
50
17
242,488
def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return CircularAperture ( * * pixel_params )
Convert the aperture to a CircularAperture object defined in pixel coordinates .
49
16
242,489
def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return CircularAnnulus ( * * pixel_params )
Convert the aperture to a CircularAnnulus object defined in pixel coordinates .
49
16
242,490
def apply_poisson_noise ( data , random_state = None ) : data = np . asanyarray ( data ) if np . any ( data < 0 ) : raise ValueError ( 'data must not contain any negative values' ) prng = check_random_state ( random_state ) return prng . poisson ( data )
Apply Poisson noise to an array where the value of each element in the input array represents the expected number of counts .
74
24
242,491
def make_noise_image ( shape , type = 'gaussian' , mean = None , stddev = None , random_state = None ) : if mean is None : raise ValueError ( '"mean" must be input' ) prng = check_random_state ( random_state ) if type == 'gaussian' : if stddev is None : raise ValueError ( '"stddev" must be input for Gaussian noise' ) i...
Make a noise image containing Gaussian or Poisson noise .
180
12
242,492
def make_random_models_table ( n_sources , param_ranges , random_state = None ) : prng = check_random_state ( random_state ) sources = Table ( ) for param_name , ( lower , upper ) in param_ranges . items ( ) : # Generate a column for every item in param_ranges, even if it # is not in the model (e.g. flux). However, suc...
Make a ~astropy . table . Table containing randomly generated parameters for an Astropy model to simulate a set of sources .
130
25
242,493
def make_random_gaussians_table ( n_sources , param_ranges , random_state = None ) : sources = make_random_models_table ( n_sources , param_ranges , random_state = random_state ) # convert Gaussian2D flux to amplitude if 'flux' in param_ranges and 'amplitude' not in param_ranges : model = Gaussian2D ( x_stddev = 1 , y_...
Make a ~astropy . table . Table containing randomly generated parameters for 2D Gaussian sources .
237
20
242,494
def make_model_sources_image ( shape , model , source_table , oversample = 1 ) : image = np . zeros ( shape , dtype = np . float64 ) y , x = np . indices ( shape ) params_to_set = [ ] for param in source_table . colnames : if param in model . param_names : params_to_set . append ( param ) # Save the initial parameter v...
Make an image containing sources generated from a user - specified model .
280
13
242,495
def make_4gaussians_image ( noise = True ) : table = Table ( ) table [ 'amplitude' ] = [ 50 , 70 , 150 , 210 ] table [ 'x_mean' ] = [ 160 , 25 , 150 , 90 ] table [ 'y_mean' ] = [ 70 , 40 , 25 , 60 ] table [ 'x_stddev' ] = [ 15.2 , 5.1 , 3. , 8.1 ] table [ 'y_stddev' ] = [ 2.6 , 2.5 , 3. , 4.7 ] table [ 'theta' ] = np ....
Make an example image containing four 2D Gaussians plus a constant background .
229
16
242,496
def make_100gaussians_image ( noise = True ) : n_sources = 100 flux_range = [ 500 , 1000 ] xmean_range = [ 0 , 500 ] ymean_range = [ 0 , 300 ] xstddev_range = [ 1 , 5 ] ystddev_range = [ 1 , 5 ] params = OrderedDict ( [ ( 'flux' , flux_range ) , ( 'x_mean' , xmean_range ) , ( 'y_mean' , ymean_range ) , ( 'x_stddev' , x...
Make an example image containing 100 2D Gaussians plus a constant background .
265
16
242,497
def make_wcs ( shape , galactic = False ) : wcs = WCS ( naxis = 2 ) rho = np . pi / 3. scale = 0.1 / 3600. if astropy_version < '3.1' : wcs . _naxis1 = shape [ 1 ] # nx wcs . _naxis2 = shape [ 0 ] # ny else : wcs . pixel_shape = shape wcs . wcs . crpix = [ shape [ 1 ] / 2 , shape [ 0 ] / 2 ] # 1-indexed (x, y) wcs . wc...
Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame .
293
16
242,498
def make_imagehdu ( data , wcs = None ) : data = np . asanyarray ( data ) if data . ndim != 2 : raise ValueError ( 'data must be a 2D array' ) if wcs is not None : header = wcs . to_header ( ) else : header = None return fits . ImageHDU ( data , header = header )
Create a FITS ~astropy . io . fits . ImageHDU containing the input 2D image .
82
22
242,499
def centroid_com ( data , mask = None ) : data = data . astype ( np . float ) if mask is not None and mask is not np . ma . nomask : mask = np . asarray ( mask , dtype = bool ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.' ) data [ mask ] = 0. badidx = ~ np . isfinite ( ...
Calculate the centroid of an n - dimensional array as its center of mass determined from moments .
233
21