Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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._...
[ " Casting and checking in one call " ]
Please provide a description of the function:def add_datatype(self, name: str, datatype: DT): self._datatypes[name] = datatype
[ " Register the datatype with it's name " ]
Please provide a description of the function: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._dataty...
[ " Cast a string to the value based on the datatype " ]
Please provide a description of the function: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]...
[ " Checking the value if it fits into the given specification " ]
Please provide a description of the function:def flush(self): self.notify(tuple(self._queue)) self._queue.clear()
[ " Emits the current queue and clears the queue " ]
Please provide a description of the function:def _periodic_callback(self): try: self.notify(self._state) # emit to all subscribers except Exception: # pylint: disable=broad-except self._error_callback(*sys.exc_info()) if self._subscriptions: # if t...
[ " Will be started on first emit " ]
Please provide a description of the function: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...
[ " Decorator to wrap a function to return a Reduce operator.\n\n :param function: function to be wrapped\n :param init: optional initialization for state\n " ]
Please provide a description of the function: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 " ]
Please provide a description of the function: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('"...
[ " Decorator to wrap a coroutine to return a MapAsync operator.\n\n :param coro: coroutine to be wrapped\n :param mode: behavior when a value is currently processed\n :param unpack: value from emits will be unpacked (*value)\n " ]
Please provide a description of the function:def _future_done(self, future): try: # notify the subscribers (except result is an exception or NONE) result = future.result() # may raise exception if result is not NONE: self.notify(result) # may also r...
[ " Will be called when the coroutine is done " ]
Please provide a description of the function:def _run_coro(self, value): # when LAST_DISTINCT is used only start coroutine when value changed if self._options.mode is MODE.LAST_DISTINCT and \ value == self._last_emit: self._future = None return ...
[ " Start the coroutine as task " ]
Please provide a description of the function: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: ...
[ " Decorator to wrap a function to return a Filter operator.\n\n :param predicate: function to be wrapped\n :param unpack: value from emits will be unpacked (*value)\n " ]
Please provide a description of the function:def apply_operator_overloading(): # operator overloading is (unfortunately) not working for the following # cases: # int, float, str - should return appropriate type instead of a Publisher # len - should return an integer # "x in y" - is using __bool...
[ " Function to apply operator overloading to Publisher class " ]
Please provide a description of the function:def assign(self, subject): if not isinstance(subject, (Publisher, Subscriber)): raise TypeError('Assignee has to be Publisher or Subscriber') # check if not already assigned if self._subject is not None: raise Subscri...
[ " Assigns the given subject to the topic " ]
Please provide a description of the function: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\n new topics can be created after this point.\n " ]
Please provide a description of the function:def topics(self): topics_sorted = sorted(self._topics.items(), key=lambda t: t[0]) return MappingProxyType(OrderedDict(topics_sorted))
[ " Ordered dictionary with path:topic ordered by path " ]
Please provide a description of the function: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 " ]
Please provide a description of the function: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=Non...
[ " Decorator to wrap a function to return a MapThreaded operator.\n\n :param function: function to be wrapped\n :param mode: behavior when a value is currently processed\n :param unpack: value from emits will be unpacked (*value)\n " ]
Please provide a description of the function: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\n run_in_executor to run the synchronous function as thread " ]
Please provide a description of the function: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._...
[ " Reset the debounce time " ]
Please provide a description of the function:def subscribe(self, subscriber: 'Subscriber', prepend: bool = False) -> SubscriptionDisposable: # `subscriber in self._subscriptions` is not working because # tuple.__contains__ is using __eq__ which is overwritten and returns ...
[ " Subscribing the given subscriber.\n\n :param subscriber: subscriber to add\n :param prepend: For internal use - usually the subscribers will be\n added at the end of a list. When prepend is True, it will be added\n in front of the list. This will habe an effect in the order the...
Please provide a description of the function:def unsubscribe(self, subscriber: 'Subscriber') -> None: # here is a special implementation which is replacing the more # obvious one: self._subscriptions.remove(subscriber) - this will not # work because list.remove(x) is doing comparision f...
[ " Unsubscribe the given subscriber\n\n :param subscriber: subscriber to unsubscribe\n :raises SubscriptionError: if subscriber is not subscribed (anymore)\n " ]
Please provide a description of the function:def notify(self, value: Any) -> asyncio.Future: results = (s.emit(value, who=self) for s in self._subscriptions) futures = tuple(r for r in results if r is not None) if not futures: return None if len(futures) == 1: ...
[ " Calling .emit(value) on all subscribers. A synchronouse subscriber\n will just return None, a asynchronous one may returns a future. Futures\n will be collected. If no future was returned None will be returned by\n this method. If one futrue was returned that future will be returned.\n ...
Please provide a description of the function:def wait_for(self, timeout=None): from broqer.op import OnEmitFuture # due circular dependency return self | OnEmitFuture(timeout=timeout)
[ " When a timeout should be applied for awaiting use this method.\n :param timeout: optional timeout in seconds.\n :returns: a future returning the emitted value\n " ]
Please provide a description of the function: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\n publisher.\n " ]
Please provide a description of the function:def get(self): if self._state is not NONE: return self._state return Publisher.get(self)
[ " Returns state if defined else it raises a ValueError. See also\n Publisher.get().\n\n :raises ValueError: if this publisher is not initialized and has not\n received any emits.\n " ]
Please provide a description of the function:def notify(self, value: Any) -> asyncio.Future: if self._state == value: return None self._state = value return Publisher.notify(self, value)
[ " Only notifies subscribers if state has changed. See also\n Publisher.notify().\n\n :param value: value to be emitted to subscribers\n :returns: a future if at least one subscriber has returned a future,\n elsewise None\n " ]
Please provide a description of the function:def _move_tuple_axes_first(array, axis): # Figure out how many axes we are operating over naxis = len(axis) # Add remaining axes to the axis tuple axis += tuple(i for i in range(array.ndim) if i not in axis) # The new position of each axis is just...
[ "\n Bottleneck can only take integer axis, not tuple, so this function\n takes all the axes to be operated on and combines them into the\n first dimension of the array so that we can then use axis=0\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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, ...
[ "\n Perform sigma-clipping on the provided data.\n\n The data will be iterated over, each time rejecting values that are\n less or more than a specified number of standard deviations from a\n center value.\n\n Clipped (rejected) pixels are those where::\n\n data < cenfunc(data [,axis=int]) - (...
Please provide a description of the function: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...
[ "\n Calculate sigma-clipped statistics on the provided data.\n\n Parameters\n ----------\n data : array-like or `~numpy.ma.MaskedArray`\n Data array or object that can be converted to an array.\n\n mask : `numpy.ndarray` (bool), optional\n A boolean mask with the same shape as ``data``,...
Please provide a description of the function:def _sigmaclip_noaxis(self, data, masked=True, return_bounds=False, copy=True): filtered_data = data.ravel() # remove masked values and convert to ndarray if isinstance(filtered_data, np.ma.MaskedArray): ...
[ "\n Sigma clip the data when ``axis`` is None.\n\n In this simple case, we remove clipped elements from the\n flattened array during each iteration.\n " ]
Please provide a description of the function:def _sigmaclip_withaxis(self, data, axis=None, masked=True, return_bounds=False, copy=True): # float array type is needed to insert nans into the array filtered_data = data.astype(float) # also makes a copy # ...
[ "\n Sigma clip the data when ``axis`` is specified.\n\n In this case, we replace clipped values with NaNs as placeholder\n values.\n " ]
Please provide a description of the function:def _prepare_photometry_input(data, error, mask, wcs, unit): if isinstance(data, fits.HDUList): for i in range(len(data)): if data[i].data is not None: warnings.warn("Input data is a HDUList object, photometry is " ...
[ "\n Parse the inputs to `aperture_photometry`.\n\n `aperture_photometry` accepts a wide range of inputs, e.g. ``data``\n could be a numpy array, a Quantity array, or a fits HDU. This\n requires some parsing and validation to ensure that all inputs are\n complete and consistent. For example, the dat...
Please provide a description of the function:def aperture_photometry(data, apertures, error=None, mask=None, method='exact', subpixels=5, unit=None, wcs=None): data, error, mask, wcs = _prepare_photometry_input(data, error, mask, w...
[ "\n Perform aperture photometry on the input data by summing the flux\n within the given aperture(s).\n\n Parameters\n ----------\n data : array_like, `~astropy.units.Quantity`, `~astropy.io.fits.ImageHDU`, or `~astropy.io.fits.HDUList`\n The 2D array on which to perform photometry. ``data`` s...
Please provide a description of the function:def _centered_edges(self): edges = [] for position, bbox in zip(self.positions, self.bounding_boxes): xmin = bbox.ixmin - 0.5 - position[0] xmax = bbox.ixmax - 0.5 - position[0] ymin = bbox.iymin - 0.5 - position[...
[ "\n A list of ``(xmin, xmax, ymin, ymax)`` tuples, one for each\n position, of the pixel edges after recentering the aperture at\n the origin.\n\n These pixel edges are used by the low-level `photutils.geometry`\n functions.\n " ]
Please provide a description of the function:def mask_area(self, method='exact', subpixels=5): mask = self.to_mask(method=method, subpixels=subpixels) return [np.sum(m.data) for m in mask]
[ "\n Return the area of the aperture(s) mask.\n\n For ``method`` other than ``'exact'``, this area will be less\n than the exact analytical area (e.g. the ``area`` method). Note\n that for these methods, the values can also differ because of\n fractional pixel positions.\n\n ...
Please provide a description of the function: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) # ...
[ "\n Perform aperture photometry on the input data.\n\n Parameters\n ----------\n data : array_like or `~astropy.units.Quantity` instance\n The 2D array on which to perform photometry. ``data``\n should be background subtracted.\n\n error : array_like or `~as...
Please provide a description of the function:def _prepare_plot(self, origin=(0, 0), indices=None, ax=None, fill=False, **kwargs): import matplotlib.pyplot as plt if ax is None: ax = plt.gca() # This is necessary because the `matplotlib.patches.Patch`...
[ "\n Prepare to plot the aperture(s) on a matplotlib\n `~matplotlib.axes.Axes` instance.\n\n Parameters\n ----------\n origin : array_like, optional\n The ``(x, y)`` position of the origin of the displayed\n image.\n\n indices : int or array of int, opt...
Please provide a description of the function: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) # The aperture object must have a single value for each shape #...
[ "\n Convert the pixel aperture parameters to those for a sky\n aperture.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whether to do the transform...
Please provide a description of the function: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() # The aperture object must have a single value for each...
[ "\n Convert the sky aperture parameters to those for a pixel\n aperture.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n\n mode : {'all', 'wcs'}, optional\n Whether to do the transform...
Please provide a description of the function:def make_random_cmap(ncolors=256, random_state=None): from matplotlib import colors prng = check_random_state(random_state) h = prng.uniform(low=0.0, high=1.0, size=ncolors) s = prng.uniform(low=0.2, high=0.7, size=ncolors) v = prng.uniform(low=0.5...
[ "\n Make a matplotlib colormap consisting of (random) muted colors.\n\n A random colormap is very useful for plotting segmentation images.\n\n Parameters\n ----------\n ncolors : int, optional\n The number of colors in the colormap. The default is 256.\n\n random_state : int or `~numpy.ran...
Please provide a description of the function: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(segme...
[ "\n Calculate photometry and morphological properties of sources defined\n by a labeled segmentation image.\n\n Parameters\n ----------\n data : array_like or `~astropy.units.Quantity`\n The 2D array from which to calculate the source photometry and\n properties. ``data`` should be bac...
Please provide a description of the function:def _properties_table(obj, columns=None, exclude_columns=None): # default properties columns_all = ['id', 'xcentroid', 'ycentroid', 'sky_centroid', 'sky_centroid_icrs', 'source_sum', 'source_sum_err', 'background_sum', 'bac...
[ "\n Construct a `~astropy.table.QTable` of source properties from a\n `SourceProperties` or `SourceCatalog` object.\n\n Parameters\n ----------\n obj : `SourceProperties` or `SourceCatalog` instance\n The object containing the source properties.\n\n columns : str or list of str, optional\n ...
Please provide a description of the function:def _total_mask(self): mask = self._segment_mask | self._data_mask if self._input_mask is not None: mask |= self._input_mask return mask
[ "\n Combination of the _segment_mask, _input_mask, and _data_mask.\n\n This mask is applied to ``data``, ``error``, and ``background``\n inputs when calculating properties.\n " ]
Please provide a description of the function:def _data_zeroed(self): # NOTE: using np.where is faster than # _data = np.copy(self.data_cutout) # self._data[self._total_mask] = 0. return np.where(self._total_mask, 0, self.data_cutout).astype(np.fl...
[ "\n A 2D `~numpy.nddarray` cutout from the input ``data`` where any\n masked pixels (_segment_mask, _input_mask, or _data_mask) are\n set to zero. Invalid values (e.g. NaNs or infs) are set to\n zero. Units are dropped on the input ``data``.\n " ]
Please provide a description of the function:def _filtered_data_zeroed(self): filt_data = self._filtered_data[self._slice] filt_data = np.where(self._total_mask, 0., filt_data) # copy filt_data[filt_data < 0] = 0. return filt_data.astype(np.float64)
[ "\n A 2D `~numpy.nddarray` cutout from the input ``filtered_data``\n (or ``data`` if ``filtered_data`` is `None`) where any masked\n pixels (_segment_mask, _input_mask, or _data_mask) are set to\n zero. Invalid values (e.g. NaNs or infs) are set to zero.\n Units are dropped on th...
Please provide a description of the function:def make_cutout(self, data, masked_array=False): data = np.asanyarray(data) if data.shape != self._segment_img.shape: raise ValueError('data must have the same shape as the ' 'segmentation image input to Sour...
[ "\n Create a (masked) cutout array from the input ``data`` using the\n minimal bounding box of the source segment.\n\n If ``masked_array`` is `False` (default), then the returned\n cutout array is simply a `~numpy.ndarray`. The returned cutout\n is a view (not a copy) of the inpu...
Please provide a description of the function:def to_table(self, columns=None, exclude_columns=None): return _properties_table(self, columns=columns, exclude_columns=exclude_columns)
[ "\n Create a `~astropy.table.QTable` of properties.\n\n If ``columns`` or ``exclude_columns`` are not input, then the\n `~astropy.table.QTable` will include a default list of\n scalar-valued properties.\n\n Parameters\n ----------\n columns : str or list of str, opti...
Please provide a description of the function:def data_cutout_ma(self): return np.ma.masked_array(self._data[self._slice], mask=self._total_mask)
[ "\n A 2D `~numpy.ma.MaskedArray` cutout from the data.\n\n The mask is `True` for pixels outside of the source segment\n (labeled region of interest), masked pixels from the ``mask``\n input, or any non-finite ``data`` values (e.g. NaN or inf).\n " ]
Please provide a description of the function: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)
[ "\n A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``\n image.\n\n The mask is `True` for pixels outside of the source segment\n (labeled region of interest), masked pixels from the ``mask``\n input, or any non-finite ``data`` values (e.g. NaN or inf).\n\n If ``e...
Please provide a description of the function: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)
[ "\n A 2D `~numpy.ma.MaskedArray` cutout from the input\n ``background``.\n\n The mask is `True` for pixels outside of the source segment\n (labeled region of interest), masked pixels from the ``mask``\n input, or any non-finite ``data`` values (e.g. NaN or inf).\n\n If ``ba...
Please provide a description of the function:def coords(self): yy, xx = np.nonzero(self.data_cutout_ma) return (yy + self._slice[0].start, xx + self._slice[1].start)
[ "\n A tuple of two `~numpy.ndarray` containing the ``y`` and ``x``\n pixel coordinates of unmasked pixels within the source segment.\n\n Non-finite pixel values (e.g. NaN, infs) are excluded\n (automatically masked).\n\n If all pixels are masked, ``coords`` will be a tuple of\n ...
Please provide a description of the function:def moments_central(self): ycentroid, xcentroid = self.cutout_centroid.value return _moments_central(self._filtered_data_zeroed, center=(xcentroid, ycentroid), order=3)
[ "\n Central moments (translation invariant) of the source up to 3rd\n order.\n " ]
Please provide a description of the function:def cutout_centroid(self): m = self.moments if m[0, 0] != 0: ycentroid = m[1, 0] / m[0, 0] xcentroid = m[0, 1] / m[0, 0] return (ycentroid, xcentroid) * u.pix else: return (np.nan, np.nan) * u....
[ "\n The ``(y, x)`` coordinate, relative to the `data_cutout`, of\n the centroid within the source segment.\n " ]
Please provide a description of the function:def centroid(self): ycen, xcen = self.cutout_centroid.value return (ycen + self._slice[0].start, xcen + self._slice[1].start) * u.pix
[ "\n The ``(y, x)`` coordinate of the centroid within the source\n segment.\n " ]
Please provide a description of the function: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: retur...
[ "\n The sky coordinates of the centroid within the source segment,\n returned as a `~astropy.coordinates.SkyCoord` object.\n\n The output coordinate frame is the same as the input WCS.\n " ]
Please provide a description of the function:def bbox(self): # (stop - 1) to return the max pixel location, not the slice index return (self._slice[0].start, self._slice[1].start, self._slice[0].stop - 1, self._slice[1].stop - 1) * u.pix
[ "\n The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal\n rectangular region containing the source segment.\n " ]
Please provide a description of the function: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: retu...
[ "\n The sky coordinates of the lower-left vertex of the minimal\n bounding box of the source segment, returned as a\n `~astropy.coordinates.SkyCoord` object.\n\n The bounding box encloses all of the source segment pixels in\n their entirety, thus the vertices are at the pixel *cor...
Please provide a description of the function: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: retu...
[ "\n The sky coordinates of the upper-left vertex of the minimal\n bounding box of the source segment, returned as a\n `~astropy.coordinates.SkyCoord` object.\n\n The bounding box encloses all of the source segment pixels in\n their entirety, thus the vertices are at the pixel *cor...
Please provide a description of the function: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: retu...
[ "\n The sky coordinates of the lower-right vertex of the minimal\n bounding box of the source segment, returned as a\n `~astropy.coordinates.SkyCoord` object.\n\n The bounding box encloses all of the source segment pixels in\n their entirety, thus the vertices are at the pixel *co...
Please provide a description of the function: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: retu...
[ "\n The sky coordinates of the upper-right vertex of the minimal\n bounding box of the source segment, returned as a\n `~astropy.coordinates.SkyCoord` object.\n\n The bounding box encloses all of the source segment pixels in\n their entirety, thus the vertices are at the pixel *co...
Please provide a description of the function:def min_value(self): if self._is_completely_masked: return np.nan * self._data_unit else: return np.min(self.values)
[ "\n The minimum pixel value of the ``data`` within the source\n segment.\n " ]
Please provide a description of the function:def max_value(self): if self._is_completely_masked: return np.nan * self._data_unit else: return np.max(self.values)
[ "\n The maximum pixel value of the ``data`` within the source\n segment.\n " ]
Please provide a description of the function:def minval_cutout_pos(self): if self._is_completely_masked: return (np.nan, np.nan) * u.pix else: arr = self.data_cutout_ma # multiplying by unit converts int to float, but keep as # float in case of N...
[ "\n The ``(y, x)`` coordinate, relative to the `data_cutout`, of the\n minimum pixel value of the ``data`` within the source segment.\n\n If there are multiple occurrences of the minimum value, only the\n first occurence is returned.\n " ]
Please provide a description of the function:def maxval_cutout_pos(self): if self._is_completely_masked: return (np.nan, np.nan) * u.pix else: arr = self.data_cutout_ma # multiplying by unit converts int to float, but keep as # float in case of N...
[ "\n The ``(y, x)`` coordinate, relative to the `data_cutout`, of the\n maximum pixel value of the ``data`` within the source segment.\n\n If there are multiple occurrences of the maximum value, only the\n first occurence is returned.\n " ]
Please provide a description of the function:def minval_pos(self): if self._is_completely_masked: return (np.nan, np.nan) * u.pix else: yp, xp = self.minval_cutout_pos.value return (yp + self._slice[0].start, xp + self._slice[1].start) * ...
[ "\n The ``(y, x)`` coordinate of the minimum pixel value of the\n ``data`` within the source segment.\n\n If there are multiple occurrences of the minimum value, only the\n first occurence is returned.\n " ]
Please provide a description of the function:def maxval_pos(self): if self._is_completely_masked: return (np.nan, np.nan) * u.pix else: yp, xp = self.maxval_cutout_pos.value return (yp + self._slice[0].start, xp + self._slice[1].start) * ...
[ "\n The ``(y, x)`` coordinate of the maximum pixel value of the\n ``data`` within the source segment.\n\n If there are multiple occurrences of the maximum value, only the\n first occurence is returned.\n " ]
Please provide a description of the function:def source_sum(self): if self._is_completely_masked: return np.nan * self._data_unit # table output needs unit else: return np.sum(self.values)
[ "\n The sum of the unmasked ``data`` values within the source segment.\n\n .. math:: F = \\\\sum_{i \\\\in S} (I_i - B_i)\n\n where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the\n ``data``, and :math:`S` are the unmasked pixels in the source\n segment.\n\n Non-fin...
Please provide a description of the function:def source_sum_err(self): if self._error is not None: if self._is_completely_masked: return np.nan * self._error_unit # table output needs unit else: return np.sqrt(np.sum(self._error_values ** 2)) ...
[ "\n The uncertainty of `~photutils.SourceProperties.source_sum`,\n propagated from the input ``error`` array.\n\n ``source_sum_err`` is the quadrature sum of the total errors\n over the non-masked pixels within the source segment:\n\n .. math:: \\\\Delta F = \\\\sqrt{\\\\sum_{i \\...
Please provide a description of the function:def background_sum(self): if self._background is not None: if self._is_completely_masked: return np.nan * self._background_unit # unit for table else: return np.sum(self._background_values) el...
[ "\n The sum of ``background`` values within the source segment.\n\n Pixel values that are masked in the input ``data``, including\n any non-finite pixel values (i.e. NaN, infs) that are\n automatically masked, are also masked in the background array.\n " ]
Please provide a description of the function:def background_mean(self): if self._background is not None: if self._is_completely_masked: return np.nan * self._background_unit # unit for table else: return np.mean(self._background_values) ...
[ "\n The mean of ``background`` values within the source segment.\n\n Pixel values that are masked in the input ``data``, including\n any non-finite pixel values (i.e. NaN, infs) that are\n automatically masked, are also masked in the background array.\n " ]
Please provide a description of the function: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.an...
[ "\n The value of the ``background`` at the position of the source\n centroid.\n\n The background value at fractional position values are\n determined using bilinear interpolation.\n " ]
Please provide a description of the function:def area(self): if self._is_completely_masked: return np.nan * u.pix**2 else: return len(self.values) * u.pix**2
[ "\n The total unmasked area of the source segment in units of\n pixels**2.\n\n Note that the source area may be smaller than its segment area\n if a mask is input to `SourceProperties` or `source_properties`,\n or if the ``data`` within the segment contains invalid values\n ...
Please provide a description of the function: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
[ "\n The total perimeter of the source segment, approximated lines\n through the centers of the border pixels using a 4-connectivity.\n\n If any masked pixels make holes within the source segment, then\n the perimeter around the inner hole (e.g. an annulus) will also\n contribute t...
Please provide a description of the function: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
[ "\n The inertia tensor of the source for the rotation around its\n center of mass.\n " ]
Please provide a description of the function: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.pi...
[ "\n The covariance matrix of the 2D Gaussian function that has the\n same second-order moments as the source.\n " ]
Please provide a description of the function:def _check_covariance(covariance): p = 1. / 12 # arbitrary SExtractor value val = (covariance[0, 0] * covariance[1, 1]) - covariance[0, 1]**2 if val >= p**2: return covariance else: covar = np.copy(covaria...
[ "\n Check and modify the covariance matrix in the case of\n \"infinitely\" thin detections. This follows SExtractor's\n prescription of incrementally increasing the diagonal elements\n by 1/12.\n " ]
Please provide a description of the function: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 cove...
[ "\n The two eigenvalues of the `covariance` matrix in decreasing\n order.\n " ]
Please provide a description of the function:def eccentricity(self): l1, l2 = self.covariance_eigvals if l1 == 0: return 0. # pragma: no cover return np.sqrt(1. - (l2 / l1))
[ "\n The eccentricity of the 2D Gaussian function that has the same\n second-order moments as the source.\n\n The eccentricity is the fraction of the distance along the\n semimajor axis at which the focus lies.\n\n .. math:: e = \\\\sqrt{1 - \\\\frac{b^2}{a^2}}\n\n where :ma...
Please provide a description of the function: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))
[ "\n The angle in radians between the ``x`` axis and the major axis\n of the 2D Gaussian function that has the same second-order\n moments as the source. The angle increases in the\n counter-clockwise direction.\n " ]
Please provide a description of the function:def cxx(self): return ((np.cos(self.orientation) / self.semimajor_axis_sigma)**2 + (np.sin(self.orientation) / self.semiminor_axis_sigma)**2)
[ "\n `SExtractor`_'s CXX ellipse parameter in units of pixel**(-2).\n\n The ellipse is defined as\n\n .. math::\n cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n cyy (y - \\\\bar{y})^2 = R^2\n\n where :math:`R` is a parameter which scal...
Please provide a description of the function:def cyy(self): return ((np.sin(self.orientation) / self.semimajor_axis_sigma)**2 + (np.cos(self.orientation) / self.semiminor_axis_sigma)**2)
[ "\n `SExtractor`_'s CYY ellipse parameter in units of pixel**(-2).\n\n The ellipse is defined as\n\n .. math::\n cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n cyy (y - \\\\bar{y})^2 = R^2\n\n where :math:`R` is a parameter which scal...
Please provide a description of the function:def cxy(self): return (2. * np.cos(self.orientation) * np.sin(self.orientation) * ((1. / self.semimajor_axis_sigma**2) - (1. / self.semiminor_axis_sigma**2)))
[ "\n `SExtractor`_'s CXY ellipse parameter in units of pixel**(-2).\n\n The ellipse is defined as\n\n .. math::\n cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n cyy (y - \\\\bar{y})^2 = R^2\n\n where :math:`R` is a parameter which scal...
Please provide a description of the function: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...
[ "\n Extract all the data values in boxes of size ``box_size``.\n\n Values from incomplete boxes, either because of the image edges or\n masked pixels, are not returned.\n\n Parameters\n ----------\n data : 2D `~numpy.ma.MaskedArray`\n The input masked array.\n\n box_size : int\n T...
Please provide a description of the function: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 sa...
[ "\n Calculate the standard deviation of block-summed data values at\n sizes of ``block_sizes``.\n\n Values from incomplete blocks, either because of the image edges or\n masked pixels, are not included.\n\n Parameters\n ----------\n data : array-like\n The 2D array to block sum.\n\n b...
Please provide a description of the function:def do_photometry(self, image, init_guesses=None): if self.bkg_estimator is not None: image = image - self.bkg_estimator(image) if self.aperture_radius is None: if hasattr(self.psf_model, 'fwhm'): self.apertu...
[ "\n Perform PSF photometry in ``image``.\n\n This method assumes that ``psf_model`` has centroids and flux\n parameters which will be fitted to the data provided in\n ``image``. A compound model, in fact a sum of ``psf_model``,\n will be fitted to groups of stars automatically ide...
Please provide a description of the function: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...
[ "\n Fit, as appropriate, a compound or single model to the given\n ``star_groups``. Groups are fitted sequentially from the\n smallest to the biggest. In each iteration, ``image`` is\n subtracted by the previous fitted group.\n\n Parameters\n ----------\n image : num...
Please provide a description of the function:def _define_fit_param_names(self): xname, yname, fluxname = _extract_psf_fitting_names(self.psf_model) self._pars_to_set = {'x_0': xname, 'y_0': yname, 'flux_0': fluxname} self._pars_to_output = {'x_fit': xname, 'y_fit': yname, ...
[ "\n Convenience function to define mappings between the names of the\n columns in the initial guess table (and the name of the fitted\n parameters) and the actual name of the parameters in the model.\n\n This method sets the following parameters on the ``self`` object:\n * ``pars_...
Please provide a description of the function: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", ...
[ "\n Retrieve uncertainties on fitted parameters from the fitter\n object.\n\n Parameters\n ----------\n star_group_size : int\n Number of stars in the given group.\n\n Returns\n -------\n unc_tab : `~astropy.table.Table`\n Table which con...
Please provide a description of the function: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(sta...
[ "\n Place fitted parameters into an astropy table.\n\n Parameters\n ----------\n fit_model : `astropy.modeling.Fittable2DModel` instance\n PSF or PRF model to fit the data. Could be one of the models\n in this package like `~photutils.psf.sandbox.DiscretePRF`,\n ...
Please provide a description of the function:def do_photometry(self, image, init_guesses=None): if init_guesses is not None: table = super().do_photometry(image, init_guesses) table['iter_detected'] = np.ones(table['x_fit'].shape, dt...
[ "\n Perform PSF photometry in ``image``.\n\n This method assumes that ``psf_model`` has centroids and flux\n parameters which will be fitted to the data provided in\n ``image``. A compound model, in fact a sum of ``psf_model``,\n will be fitted to groups of stars automatically ide...
Please provide a description of the function: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(...
[ "\n Helper function which performs the iterations of the photometry\n process.\n\n Parameters\n ----------\n param_names : list\n Names of the columns which represent the initial guesses.\n For example, ['x_0', 'y_0', 'flux_0'], for intial guesses on\n ...
Please provide a description of the function: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...
[ "\n Calculate the pixel scale and WCS rotation angle at the position of\n a SkyCoord coordinate.\n\n Parameters\n ----------\n skycoord : `~astropy.coordinates.SkyCoord`\n The SkyCoord coordinate.\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n...
Please provide a description of the function:def assert_angle_or_pixel(name, q): if isinstance(q, u.Quantity): if q.unit.physical_type == 'angle' or q.unit == u.pixel: pass else: raise ValueError("{0} should have angular or pixel " "units".f...
[ "\n Check that ``q`` is either an angular or a pixel\n :class:`~astropy.units.Quantity`.\n " ]
Please provide a description of the function: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
[ "\n Convert pixel coordinates to ICRS Right Ascension and Declination.\n\n This is merely a convenience function to extract RA and Dec. from a\n `~astropy.coordinates.SkyCoord` instance so they can be put in\n separate columns in a `~astropy.table.Table`.\n\n Parameters\n ----------\n x : float...
Please provide a description of the function: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: ...
[ "\n Convolve a 2D image with a 2D kernel.\n\n The kernel may either be a 2D `~numpy.ndarray` or a\n `~astropy.convolution.Kernel2D` object.\n\n Parameters\n ----------\n data : array_like\n The 2D array of the image.\n\n kernel : array-like (2D) or `~astropy.convolution.Kernel2D`\n ...
Please provide a description of the function: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) ...
[ "\n Convert a 2D PSF model to one suitable for use with\n `BasicPSFPhotometry` or its subclasses.\n\n The resulting model may be a composite model, but should have only\n the x, y, and flux related parameters un-fixed.\n\n Parameters\n ----------\n psfmodel : a 2D model\n The model to as...