idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
243,300
def get_mark ( self ) : if self . is_leaf : char = self . icon_chars [ 2 ] else : char = self . icon_chars [ int ( self . expanded ) ] return urwid . SelectableIcon ( ( 'mark' , char ) , 0 )
Gets an expanded collapsed or leaf icon .
243,301
def get_path ( self ) : path = deque ( ) __ , node = self . get_focus ( ) while not node . is_root ( ) : stats = node . get_value ( ) path . appendleft ( hash ( stats ) ) node = node . get_parent ( ) return path
Gets the path to the focused statistics . Each step is a hash of statistics object .
243,302
def find_node ( self , node , path ) : for hash_value in path : if isinstance ( node , LeafStatisticsNode ) : break for stats in node . get_child_keys ( ) : if hash ( stats ) == hash_value : node = node . get_child_node ( stats ) break else : break return node
Finds a node by the given path from the given node .
243,303
def update_result ( self ) : try : if self . paused : result = self . _paused_result else : result = self . _final_result except AttributeError : self . table . update_frame ( ) return stats , cpu_time , wall_time , title , at = result self . table . set_result ( stats , cpu_time , wall_time , title , at )
Updates the result on the table .
243,304
def option_getter ( type ) : option_getters = { None : ConfigParser . get , int : ConfigParser . getint , float : ConfigParser . getfloat , bool : ConfigParser . getboolean } return option_getters . get ( type , option_getters [ None ] )
Gets an unbound method to get a configuration option as the given type .
243,305
def config_default ( option , default = None , type = None , section = cli . name ) : def f ( option = option , default = default , type = type , section = section ) : config = read_config ( ) if type is None and default is not None : type = builtins . type ( default ) get_option = option_getter ( type ) try : return g...
Guesses a default value of a CLI option from the configuration .
243,306
def config_flag ( option , value , default = False , section = cli . name ) : class x ( object ) : def __bool__ ( self , option = option , value = value , default = default , section = section ) : config = read_config ( ) type = builtins . type ( value ) get_option = option_getter ( type ) try : return get_option ( con...
Guesses whether a CLI flag should be turned on or off from the configuration . If the configuration option value is same with the given value it returns True .
243,307
def get_title ( src_name , src_type = None ) : if src_type == 'tcp' : return '{0}:{1}' . format ( * src_name ) return os . path . basename ( src_name )
Normalizes a source name as a string to be used for viewer s title .
243,308
def spawn_thread ( func , * args , ** kwargs ) : thread = threading . Thread ( target = func , args = args , kwargs = kwargs ) thread . daemon = True thread . start ( ) return thread
Spawns a daemon thread .
243,309
def spawn ( mode , func , * args , ** kwargs ) : if mode is None : mode = 'threading' elif mode not in spawn . modes : raise ValueError ( 'Invalid spawn mode: %s' % mode ) if mode == 'threading' : return spawn_thread ( func , * args , ** kwargs ) elif mode == 'gevent' : import gevent import gevent . monkey gevent . mon...
Spawns a thread - like object which runs the given function concurrently .
243,310
def profile ( script , argv , profiler_factory , pickle_protocol , dump_filename , mono ) : filename , code , globals_ = script sys . argv [ : ] = [ filename ] + list ( argv ) __profile__ ( filename , code , globals_ , profiler_factory , pickle_protocol = pickle_protocol , dump_filename = dump_filename , mono = mono )
Profile a Python script .
243,311
def live_profile ( script , argv , profiler_factory , interval , spawn , signum , pickle_protocol , mono ) : filename , code , globals_ = script sys . argv [ : ] = [ filename ] + list ( argv ) parent_sock , child_sock = socket . socketpair ( ) stderr_r_fd , stderr_w_fd = os . pipe ( ) pid = os . fork ( ) if pid : os . ...
Profile a Python script continuously .
243,312
def view ( src , mono ) : src_type , src_name = src title = get_title ( src_name , src_type ) viewer , loop = make_viewer ( mono ) if src_type == 'dump' : time = datetime . fromtimestamp ( os . path . getmtime ( src_name ) ) with open ( src_name , 'rb' ) as f : profiler_class , ( stats , cpu_time , wall_time ) = pickle...
Inspect statistics by TUI view .
243,313
def timeit_profile ( stmt , number , repeat , setup , profiler_factory , pickle_protocol , dump_filename , mono , ** _ignored ) : del _ignored globals_ = { } exec_ ( setup , globals_ ) if number is None : dummy_profiler = profiler_factory ( ) dummy_profiler . start ( ) for x in range ( 1 , 10 ) : number = 10 ** x t = t...
Profile a Python statement like timeit .
243,314
def spread_stats ( stats , spreader = False ) : spread = spread_t ( ) if spreader else True descendants = deque ( stats ) while descendants : _stats = descendants . popleft ( ) if spreader : spread . clear ( ) yield _stats , spread else : yield _stats if spread : descendants . extend ( _stats )
Iterates all descendant statistics under the given root statistics .
243,315
def own_time ( self ) : sub_time = sum ( stats . deep_time for stats in self ) return max ( 0. , self . deep_time - sub_time )
The exclusive execution time .
243,316
def flatten ( cls , stats ) : flat_children = { } for _stats in spread_stats ( stats ) : key = ( _stats . name , _stats . filename , _stats . lineno , _stats . module ) try : flat_stats = flat_children [ key ] except KeyError : flat_stats = flat_children [ key ] = cls ( * key ) flat_stats . own_hits += _stats . own_hit...
Makes a flat statistics from the given statistics .
243,317
def requirements ( filename ) : with open ( filename ) as f : return [ x . strip ( ) for x in f . readlines ( ) if x . strip ( ) ]
Reads requirements from a file .
243,318
def sample ( self , frame ) : frames = self . frame_stack ( frame ) if frames : frames . pop ( ) parent_stats = self . stats for f in frames : parent_stats = parent_stats . ensure_child ( f . f_code , void ) stats = parent_stats . ensure_child ( frame . f_code , RecordingStatistics ) stats . own_hits += 1
Samples the given frame .
243,319
def deferral ( ) : deferred = [ ] defer = lambda f , * a , ** k : deferred . append ( ( f , a , k ) ) try : yield defer finally : while deferred : f , a , k = deferred . pop ( ) f ( * a , ** k )
Defers a function call when it is being required like Go .
243,320
def start ( self , * args , ** kwargs ) : if self . is_running ( ) : raise RuntimeError ( 'Already started' ) self . _running = self . run ( * args , ** kwargs ) try : yielded = next ( self . _running ) except StopIteration : raise TypeError ( 'run() must yield just one time' ) if yielded is not None : raise TypeError ...
Starts the instance .
243,321
def stop ( self ) : if not self . is_running ( ) : raise RuntimeError ( 'Not started' ) running , self . _running = self . _running , None try : next ( running ) except StopIteration : pass else : raise TypeError ( 'run() must yield just one time' )
Stops the instance .
243,322
def sockets ( self ) : if self . listener is None : return self . clients else : return self . clients . union ( [ self . listener ] )
Returns the set of the sockets .
243,323
def select_sockets ( self , timeout = None ) : if timeout is not None : t = time . time ( ) while True : try : ready , __ , __ = select . select ( self . sockets ( ) , ( ) , ( ) , timeout ) except ValueError : pass except select . error as exc : if exc . args [ 0 ] != EINTR : raise else : return ready if timeout is Non...
EINTR safe version of select . It focuses on just incoming sockets .
243,324
def dispatch_sockets ( self , timeout = None ) : for sock in self . select_sockets ( timeout = timeout ) : if sock is self . listener : listener = sock sock , addr = listener . accept ( ) self . connected ( sock ) else : try : sock . recv ( 1 ) except socket . error as exc : if exc . errno != ECONNRESET : raise self . ...
Dispatches incoming sockets .
243,325
def record_entering ( self , time , code , frame_key , parent_stats ) : stats = parent_stats . ensure_child ( code , RecordingStatistics ) self . _times_entered [ ( code , frame_key ) ] = time stats . own_hits += 1
Entered to a function call .
243,326
def record_leaving ( self , time , code , frame_key , parent_stats ) : try : stats = parent_stats . get_child ( code ) time_entered = self . _times_entered . pop ( ( code , frame_key ) ) except KeyError : return time_elapsed = time - time_entered stats . deep_time += max ( 0 , time_elapsed )
Left from a function call .
243,327
def build_sink ( function : Callable [ ... , None ] = None , * , unpack : bool = False ) : def _build_sink ( function : Callable [ ... , None ] ) : @ wraps ( function ) def _wrapper ( * args , ** kwargs ) -> Sink : if 'unpack' in kwargs : raise TypeError ( '"unpack" has to be defined by decorator' ) return Sink ( funct...
Decorator to wrap a function to return a Sink subscriber .
243,328
def build_map ( function : Callable [ [ Any ] , Any ] = None , unpack : bool = False ) : def _build_map ( function : Callable [ [ Any ] , Any ] ) : @ wraps ( function ) def _wrapper ( * args , ** kwargs ) -> Map : if 'unpack' in kwargs : raise TypeError ( '"unpack" has to be defined by decorator' ) return Map ( functio...
Decorator to wrap a function to return a Map operator .
243,329
def _trace_handler ( publisher , value , label = None ) : line = '--- %8.3f: ' % ( time ( ) - Trace . _timestamp_start ) line += repr ( publisher ) if label is None else label line += ' %r' % ( value , ) print ( line )
Default trace handler is printing the timestamp the publisher name and the emitted value
243,330
def build_sink_async ( coro = None , * , mode = None , unpack : bool = False ) : _mode = mode def _build_sink_async ( coro ) : @ wraps ( coro ) def _wrapper ( * args , mode = None , ** kwargs ) -> SinkAsync : if 'unpack' in kwargs : raise TypeError ( '"unpack" has to be defined by decorator' ) if mode is None : mode = ...
Decorator to wrap a coroutine to return a SinkAsync subscriber .
243,331
def build_accumulate ( function : Callable [ [ Any , Any ] , Tuple [ Any , Any ] ] = None , * , init : Any = NONE ) : _init = init def _build_accumulate ( function : Callable [ [ Any , Any ] , Tuple [ Any , Any ] ] ) : @ wraps ( function ) def _wrapper ( init = NONE ) -> Accumulate : init = _init if init is NONE else i...
Decorator to wrap a function to return an Accumulate operator .
243,332
def resolve_meta_key ( hub , key , meta ) : if key not in meta : return None value = meta [ key ] if isinstance ( value , str ) and value [ 0 ] == '>' : topic = value [ 1 : ] if topic not in hub : raise KeyError ( 'topic %s not found in hub' % topic ) return hub [ topic ] . get ( ) return value
Resolve a value when it s a string and starts with >
243,333
def checked_emit ( self , value : Any ) -> asyncio . Future : if not isinstance ( self . _subject , Subscriber ) : raise TypeError ( 'Topic %r has to be a subscriber' % self . _path ) value = self . cast ( value ) self . check ( value ) return self . _subject . emit ( value , who = self )
Casting and checking in one call
243,334
def add_datatype ( self , name : str , datatype : DT ) : self . _datatypes [ name ] = datatype
Register the datatype with it s name
243,335
def cast ( self , topic , value ) : datatype_key = topic . meta . get ( 'datatype' , 'none' ) result = self . _datatypes [ datatype_key ] . cast ( topic , value ) validate_dt = topic . meta . get ( 'validate' , None ) if validate_dt : result = self . _datatypes [ validate_dt ] . cast ( topic , result ) return result
Cast a string to the value based on the datatype
243,336
def check ( self , topic , value ) : datatype_key = topic . meta . get ( 'datatype' , 'none' ) self . _datatypes [ datatype_key ] . check ( topic , value ) validate_dt = topic . meta . get ( 'validate' , None ) if validate_dt : self . _datatypes [ validate_dt ] . check ( topic , value )
Checking the value if it fits into the given specification
243,337
def flush ( self ) : self . notify ( tuple ( self . _queue ) ) self . _queue . clear ( )
Emits the current queue and clears the queue
243,338
def _periodic_callback ( self ) : try : self . notify ( self . _state ) except Exception : self . _error_callback ( * sys . exc_info ( ) ) if self . _subscriptions : self . _call_later_handle = self . _loop . call_later ( self . _interval , self . _periodic_callback ) else : self . _state = NONE self . _call_later_hand...
Will be started on first emit
243,339
def build_reduce ( function : Callable [ [ Any , Any ] , Any ] = None , * , init : Any = NONE ) : _init = init def _build_reduce ( function : Callable [ [ Any , Any ] , Any ] ) : @ wraps ( function ) def _wrapper ( init = NONE ) -> Reduce : init = _init if init is NONE else init if init is NONE : raise TypeError ( 'ini...
Decorator to wrap a function to return a Reduce operator .
243,340
def flush ( self ) : if not self . _emit_partial and len ( self . _state ) != self . _state . maxlen : self . notify ( tuple ( self . _state ) ) self . _state . clear ( )
Flush the queue - this will emit the current queue
243,341
def build_map_async ( coro = None , * , mode = None , unpack : bool = False ) : _mode = mode def _build_map_async ( coro ) : @ wraps ( coro ) def _wrapper ( * args , mode = None , ** kwargs ) -> MapAsync : if 'unpack' in kwargs : raise TypeError ( '"unpack" has to be defined by decorator' ) if mode is None : mode = MOD...
Decorator to wrap a coroutine to return a MapAsync operator .
243,342
def _future_done ( self , future ) : try : result = future . result ( ) if result is not NONE : self . notify ( result ) except asyncio . CancelledError : return except Exception : self . _options . error_callback ( * sys . exc_info ( ) ) if self . _queue : value = self . _queue . popleft ( ) self . _run_coro ( value )...
Will be called when the coroutine is done
243,343
def _run_coro ( self , value ) : if self . _options . mode is MODE . LAST_DISTINCT and value == self . _last_emit : self . _future = None return self . _last_emit = value self . scheduled . notify ( value ) values = value if self . _options . unpack else ( value , ) coro = self . _options . coro ( * values , * self . _...
Start the coroutine as task
243,344
def build_filter ( predicate : Callable [ [ Any ] , bool ] = None , * , unpack : bool = False ) : def _build_filter ( predicate : Callable [ [ Any ] , bool ] ) : @ wraps ( predicate ) def _wrapper ( * args , ** kwargs ) -> Filter : if 'unpack' in kwargs : raise TypeError ( '"unpack" has to be defined by decorator' ) re...
Decorator to wrap a function to return a Filter operator .
243,345
def apply_operator_overloading ( ) : for method in ( '__lt__' , '__le__' , '__eq__' , '__ne__' , '__ge__' , '__gt__' , '__add__' , '__and__' , '__lshift__' , '__mod__' , '__mul__' , '__pow__' , '__rshift__' , '__sub__' , '__xor__' , '__concat__' , '__getitem__' , '__floordiv__' , '__truediv__' ) : def _op ( operand_lef...
Function to apply operator overloading to Publisher class
243,346
def assign ( self , subject ) : if not isinstance ( subject , ( Publisher , Subscriber ) ) : raise TypeError ( 'Assignee has to be Publisher or Subscriber' ) if self . _subject is not None : raise SubscriptionError ( 'Topic %r already assigned' % self . _path ) self . _subject = subject if self . _subscriptions : self ...
Assigns the given subject to the topic
243,347
def freeze ( self , freeze : bool = True ) : for topic in self . _topics . values ( ) : topic . freeze ( ) self . _frozen = freeze
Freezing the hub means that each topic has to be assigned and no new topics can be created after this point .
243,348
def reset ( self ) : if self . _call_later_handler is not None : self . _call_later_handler . cancel ( ) self . _call_later_handler = None self . _wait_done_cb ( )
Reseting duration for throttling
243,349
def build_map_threaded ( function : Callable [ [ Any ] , Any ] = None , mode = MODE . CONCURRENT , unpack : bool = False ) : _mode = mode def _build_map_threaded ( function : Callable [ [ Any ] , Any ] ) : @ wraps ( function ) def _wrapper ( * args , mode = None , ** kwargs ) -> MapThreaded : if 'unpack' in kwargs : ra...
Decorator to wrap a function to return a MapThreaded operator .
243,350
async def _thread_coro ( self , * args ) : return await self . _loop . run_in_executor ( self . _executor , self . _function , * args )
Coroutine called by MapAsync . It s wrapping the call of run_in_executor to run the synchronous function as thread
243,351
def reset ( self ) : if self . _retrigger_value is not NONE : self . notify ( self . _retrigger_value ) self . _state = self . _retrigger_value self . _next_state = self . _retrigger_value if self . _call_later_handler : self . _call_later_handler . cancel ( ) self . _call_later_handler = None
Reset the debounce time
243,352
def subscribe ( self , subscriber : 'Subscriber' , prepend : bool = False ) -> SubscriptionDisposable : if any ( subscriber is s for s in self . _subscriptions ) : raise SubscriptionError ( 'Subscriber already registered' ) if prepend : self . _subscriptions . insert ( 0 , subscriber ) else : self . _subscriptions . ap...
Subscribing the given subscriber .
243,353
def unsubscribe ( self , subscriber : 'Subscriber' ) -> None : for i , _s in enumerate ( self . _subscriptions ) : if _s is subscriber : self . _subscriptions . pop ( i ) return raise SubscriptionError ( 'Subscriber is not registered' )
Unsubscribe the given subscriber
243,354
def inherit_type ( self , type_cls : Type [ TInherit ] ) -> Union [ TInherit , 'Publisher' ] : self . _inherited_type = type_cls return self
enables the usage of method and attribute overloading for this publisher .
243,355
def _move_tuple_axes_first ( array , axis ) : naxis = len ( axis ) axis += tuple ( i for i in range ( array . ndim ) if i not in axis ) destination = tuple ( range ( array . ndim ) ) array_new = np . moveaxis ( array , axis , destination ) first = np . prod ( array_new . shape [ : naxis ] ) array_new = array_new . resh...
Bottleneck can only take integer axis not tuple so this function takes all the axes to be operated on and combines them into the first dimension of the array so that we can then use axis = 0
243,356
def _nanmean ( array , axis = None ) : if isinstance ( axis , tuple ) : array = _move_tuple_axes_first ( array , axis = axis ) axis = 0 return bottleneck . nanmean ( array , axis = axis )
Bottleneck nanmean function that handle tuple axis .
243,357
def _nanmedian ( array , axis = None ) : if isinstance ( axis , tuple ) : array = _move_tuple_axes_first ( array , axis = axis ) axis = 0 return bottleneck . nanmedian ( array , axis = axis )
Bottleneck nanmedian function that handle tuple axis .
243,358
def _nanstd ( array , axis = None , ddof = 0 ) : if isinstance ( axis , tuple ) : array = _move_tuple_axes_first ( array , axis = axis ) axis = 0 return bottleneck . nanstd ( array , axis = axis , ddof = ddof )
Bottleneck nanstd function that handle tuple axis .
243,359
def sigma_clip ( data , sigma = 3 , sigma_lower = None , sigma_upper = None , maxiters = 5 , cenfunc = 'median' , stdfunc = 'std' , axis = None , masked = True , return_bounds = False , copy = True ) : sigclip = SigmaClip ( sigma = sigma , sigma_lower = sigma_lower , sigma_upper = sigma_upper , maxiters = maxiters , ce...
Perform sigma - clipping on the provided data .
243,360
def sigma_clipped_stats ( data , mask = None , mask_value = None , sigma = 3.0 , sigma_lower = None , sigma_upper = None , maxiters = 5 , cenfunc = 'median' , stdfunc = 'std' , std_ddof = 0 , axis = None ) : if mask is not None : data = np . ma . MaskedArray ( data , mask ) if mask_value is not None : data = np . ma . ...
Calculate sigma - clipped statistics on the provided data .
243,361
def _sigmaclip_noaxis ( self , data , masked = True , return_bounds = False , copy = True ) : filtered_data = data . ravel ( ) if isinstance ( filtered_data , np . ma . MaskedArray ) : filtered_data = filtered_data . data [ ~ filtered_data . mask ] good_mask = np . isfinite ( filtered_data ) if np . any ( ~ good_mask )...
Sigma clip the data when axis is None .
243,362
def _sigmaclip_withaxis ( self , data , axis = None , masked = True , return_bounds = False , copy = True ) : filtered_data = data . astype ( float ) bad_mask = ~ np . isfinite ( filtered_data ) if np . any ( bad_mask ) : filtered_data [ bad_mask ] = np . nan warnings . warn ( 'Input data contains invalid values (NaNs ...
Sigma clip the data when axis is specified .
243,363
def do_photometry ( self , data , error = None , mask = None , method = 'exact' , subpixels = 5 , unit = None ) : data = np . asanyarray ( data ) if mask is not None : mask = np . asanyarray ( mask ) data = copy . deepcopy ( data ) data [ mask ] = 0 if error is not None : error = copy . deepcopy ( np . asanyarray ( err...
Perform aperture photometry on the input data .
243,364
def _to_sky_params ( self , wcs , mode = 'all' ) : sky_params = { } x , y = np . transpose ( self . positions ) sky_params [ 'positions' ] = pixel_to_skycoord ( x , y , wcs , mode = mode ) crval = SkyCoord ( [ wcs . wcs . crval ] , frame = wcs_to_celestial_frame ( wcs ) , unit = wcs . wcs . cunit ) scale , angle = pixe...
Convert the pixel aperture parameters to those for a sky aperture .
243,365
def _to_pixel_params ( self , wcs , mode = 'all' ) : pixel_params = { } x , y = skycoord_to_pixel ( self . positions , wcs , mode = mode ) pixel_params [ 'positions' ] = np . array ( [ x , y ] ) . transpose ( ) crval = SkyCoord ( [ wcs . wcs . crval ] , frame = wcs_to_celestial_frame ( wcs ) , unit = wcs . wcs . cunit ...
Convert the sky aperture parameters to those for a pixel aperture .
243,366
def source_properties ( data , segment_img , error = None , mask = None , background = None , filter_kernel = None , wcs = None , labels = None ) : if not isinstance ( segment_img , SegmentationImage ) : segment_img = SegmentationImage ( segment_img ) if segment_img . shape != data . shape : raise ValueError ( 'segment...
Calculate photometry and morphological properties of sources defined by a labeled segmentation image .
243,367
def _properties_table ( obj , columns = None , exclude_columns = None ) : columns_all = [ 'id' , 'xcentroid' , 'ycentroid' , 'sky_centroid' , 'sky_centroid_icrs' , 'source_sum' , 'source_sum_err' , 'background_sum' , 'background_mean' , 'background_at_centroid' , 'xmin' , 'xmax' , 'ymin' , 'ymax' , 'min_value' , 'max_v...
Construct a ~astropy . table . QTable of source properties from a SourceProperties or SourceCatalog object .
243,368
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 .
243,369
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 .
243,370
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 .
243,371
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 .
243,372
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 .
243,373
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 .
243,374
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 .
243,375
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 .
243,376
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 .
243,377
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 .
243,378
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 .
243,379
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 .
243,380
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 .
243,381
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 .
243,382
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 .
243,383
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 .
243,384
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 .
243,385
def background_at_centroid ( self ) : from scipy . ndimage import map_coordinates if self . _background is not None : if ( self . _is_completely_masked or np . any ( ~ np . isfinite ( self . centroid ) ) ) : return np . nan * self . _background_unit else : value = map_coordinates ( self . _background , [ [ self . ycent...
The value of the background at the position of the source centroid .
243,386
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 .
243,387
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 .
243,388
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 .
243,389
def covariance_eigvals ( self ) : if not np . isnan ( np . sum ( self . covariance ) ) : eigvals = np . linalg . eigvals ( self . covariance ) if np . any ( eigvals < 0 ) : return ( np . nan , np . nan ) * u . pix ** 2 return ( np . max ( eigvals ) , np . min ( eigvals ) ) * u . pix ** 2 else : return ( np . nan , np ....
The two eigenvalues of the covariance matrix in decreasing order .
243,390
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 .
243,391
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 .
243,392
def _mesh_values ( data , box_size ) : data = np . ma . asanyarray ( data ) ny , nx = data . shape nyboxes = ny // box_size nxboxes = nx // box_size ny_crop = nyboxes * box_size nx_crop = nxboxes * box_size data = data [ 0 : ny_crop , 0 : nx_crop ] data = np . ma . swapaxes ( data . reshape ( nyboxes , box_size , nxbox...
Extract all the data values in boxes of size box_size .
243,393
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 .
243,394
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 .
243,395
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 .
243,396
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 .
243,397
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 .
243,398
def pixel_scale_angle_at_skycoord ( skycoord , wcs , offset = 1. * u . arcsec ) : coord = skycoord . represent_as ( 'unitspherical' ) coord_new = UnitSphericalRepresentation ( coord . lon , coord . lat + offset ) coord_offset = skycoord . realize_frame ( coord_new ) x_offset , y_offset = skycoord_to_pixel ( coord_offse...
Calculate the pixel scale and WCS rotation angle at the position of a SkyCoord coordinate .
243,399
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 .