goodman_photometry package#
Subpackages#
Submodules#
goodman_photometry.astrometry module#
goodman_photometry.goodman_astro module#
A module for Goodman photometry and astrometry data processing.
This module provides functions for processing photometric data from the Goodman telescope, including FITS header handling, WCS management, object detection, photometric calibration, and data visualization. It integrates with various astronomical data reduction tools and libraries like Astropy and SExtractor.
- Key Features:
FITS header metadata extraction and manipulation
WCS (World Coordinate System) handling and conversion
Object detection using SExtractor
Photometric calibration and zero-point calculation
Catalog matching and data quality evaluation
Visualization tools for images and photometric results
Integration with Vizier catalog services
- Main Functions:
extract_observation_metadata(): Extracts observation metadata from FITS headers. calculate_saturation_threshold(): Calculates saturation threshold based on gain/read noise. check_wcs(): Validates and returns WCS from a FITS header. get_objects_sextractor(): Detects objects in an image using SExtractor. calibrate_photometry(): Performs photometric calibration using reference catalogs. get_vizier_catalog(): Retrieves catalog data from Vizier services. plot_image(): Plots 2D images with optional WCS projection.
The module is designed to work within the Goodman data reduction pipeline, providing tools for accurate photometric and astrometric calibration.
- goodman_photometry.goodman_astro.add_colorbar(mappable=None, ax=None, size='5%', pad=0.1)#
Add a colorbar to a matplotlib Axes object.
This function appends a colorbar to the side of the given Axes using a custom size and padding. If no Axes is provided, the current active Axes is used.
- Parameters:
mappable (matplotlib.cm.ScalarMappable, optional) – The object to which the colorbar corresponds (e.g., from imshow()).
ax (matplotlib.axes.Axes, optional) – The Axes to which the colorbar should be added. If None, uses current Axes.
size (str, optional) – Width of the colorbar as a percentage of the original axes. Default is “5%”.
pad (float, optional) – Padding between the colorbar and the plot in inches. Default is 0.1.
- Returns:
The created colorbar instance.
- Return type:
matplotlib.colorbar.Colorbar
- goodman_photometry.goodman_astro.binned_map(x, y, values, bins=16, statistic='mean', quantiles=(0.5, 97.5), point_color=None, show_colorbar=True, show_axes=True, show_points=False, ax=None, data_range=None, **imshow_kwargs)#
Plot a binned 2D statistical map from irregular data using binned_statistic_2d.
- Parameters:
x (array-like) – X-coordinates of data points.
y (array-like) – Y-coordinates of data points.
values (array-like) – Data values at each (x, y) location.
bins (int or [int, int], optional) – Number of bins per axis (default is 16).
statistic (str or callable, optional) – Statistic to compute in each bin (e.g., ‘mean’, ‘median’, or a function).
quantiles (tuple, optional) – Percentiles for image normalization (default: (0.5, 97.5)).
point_color (str or None) – Color for overplotted data points (if shown).
show_colorbar (bool) – Whether to add a colorbar.
show_axes (bool) – Whether to show axis ticks and labels.
show_points (bool) – Whether to overlay the (x, y) points on the plot.
ax (matplotlib.axes.Axes, optional) – Axes object to plot in. Defaults to current axes.
data_range (list or tuple, optional) – [[xmin, xmax], [ymin, ymax]] data range for binning.
**imshow_kwargs – Additional keyword arguments passed to imshow.
- Returns:
None
- goodman_photometry.goodman_astro.calculate_saturation_threshold(gain_value, read_noise_value)#
Estimates the saturation threshold based on the readout mode.
- Parameters:
gain_value (float) – The detector gain (e-/ADU).
read_noise_value (float) – The detector read noise (e-).
- Returns:
The saturation threshold in ADU, estimated based on the provided gain and read noise values.
- Return type:
float
- goodman_photometry.goodman_astro.calibrate_photometry(object_table, catalog_table, search_radius=None, pixel_scale=None, spatial_order=0, background_order=None, object_mag_column='mag', object_mag_error_column='magerr', object_ra_column='ra', object_dec_column='dec', object_flags_column='flags', object_x_column='x', object_y_column='y', catalog_mag_column='R', catalog_mag_error_column=None, catalog_mag1_column=None, catalog_mag2_column=None, catalog_ra_column='RAJ2000', catalog_dec_column='DEJ2000', error_threshold=None, magnitude_limits=None, update_results=True, verbose=False, **kwargs)#
Higher-level photometric calibration routine.
This function wraps the goodman_photometry.goodman_astro.match routine with convenient defaults for typical tabular data. It performs photometric calibration by matching objects in the object table to stars in the reference catalog.
- Parameters:
object_table (astropy.table.Table) – Table of detected objects.
catalog_table (astropy.table.Table) – Reference photometric catalog.
search_radius (float, optional) – Matching radius in degrees. If not provided, it is calculated based on the pixel scale and object FWHM.
pixel_scale (float, optional) – Pixel scale in degrees per pixel. Used to calculate the search radius if not provided.
spatial_order (int, optional) – Order of the spatial polynomial for the zero point (0 for constant). Default is 0.
background_order (int, optional) – Order of the spatial polynomial for the additive flux term. Set to None to disable this term.
object_mag_column (str, optional) – Column name for object instrumental magnitude. Default is ‘mag’.
object_mag_error_column (str, optional) – Column name for object magnitude error. Default is ‘magerr’.
object_ra_column (str, optional) – Column name for object Right Ascension. Default is ‘ra’.
object_dec_column (str, optional) – Column name for object Declination. Default is ‘dec’.
object_flags_column (str, optional) – Column name for object flags. Default is ‘flags’.
object_x_column (str, optional) – Column name for object x coordinate. Default is ‘x’.
object_y_column (str, optional) – Column name for object y coordinate. Default is ‘y’.
catalog_mag_column (str, optional) – Column name for catalog magnitude. Default is ‘R’.
catalog_mag_error_column (str, optional) – Column name for catalog magnitude error. Default is None.
catalog_mag1_column (str, optional) – Column name for the first catalog magnitude defining the stellar color. Default is None.
catalog_mag2_column (str, optional) – Column name for the second catalog magnitude defining the stellar color. Default is None.
catalog_ra_column (str, optional) – Column name for catalog Right Ascension. Default is ‘RAJ2000’.
catalog_dec_column (str, optional) – Column name for catalog Declination. Default is ‘DEJ2000’.
error_threshold (float, optional) – Maximum photometric error to consider for calibration (for both observed and catalog magnitudes). Default is None.
magnitude_limits (list, optional) – Magnitude range for catalog magnitudes to avoid outliers (e.g., [8, 22]). Default is None.
update_results (bool, optional) – If True, adds mag_calib and mag_calib_err columns to the object table. Default is True.
verbose (bool or callable, optional) – Whether to show verbose messages during execution. Default is False.
**kwargs – Additional keyword arguments passed to goodman_photometry.goodman_astro.match.
- Returns:
A dictionary containing photometric calibration results, as returned by goodman_photometry.goodman_astro.match.
- Return type:
dict
- goodman_photometry.goodman_astro.check_photometry_results(results: dict) dict#
Check whether photometric calibration results are available.
- Parameters:
results (dict) – Output dictionary from calibrate_photometry().
- Returns:
The same results dictionary if not None.
- Return type:
dict
- Raises:
ValueError – If results is None, indicating photometric calibration failed.
- goodman_photometry.goodman_astro.check_wcs(header: Header) WCS#
Check whether a FITS header contains a valid celestial WCS solution.
- Parameters:
header (astropy.io.fits.Header) – FITS header to check for WCS.
- Returns:
Parsed WCS object from the header.
- Return type:
astropy.wcs.WCS
- Raises:
ValueError – If WCS is absent or not celestial.
- goodman_photometry.goodman_astro.clear_wcs(header, remove_comments=False, remove_history=False, remove_underscored=False, copy=False)#
Clear WCS-related keywords from a FITS header.
- Parameters:
header (astropy.io.fits.Header) – Header to operate on.
remove_comments (bool) – Remove COMMENT keywords if True.
remove_history (bool) – Remove HISTORY keywords if True.
remove_underscored (bool) – Remove keys starting with ‘_’ (e.g., from Astrometry.Net).
copy (bool) – If True, operate on a copy instead of modifying the original header.
- Returns:
Modified FITS header.
- Return type:
astropy.io.fits.Header
- goodman_photometry.goodman_astro.convert_match_results_to_table(match_results, pixscale=None, columns=None)#
Convert dict returned by calibrate_photometry() to an astropy Table.
- Resulting table includes:
oidx, cidx, dist: indices of positionally matched objects and catalogue stars, and pairwise distances in degrees.
omag, omagerr, cmag, cmagerr: instrumental and catalogue magnitudes with errors.
color: catalogue colors or zeros if no color term fitting is done.
ox, oy, oflags: image coordinates and flags of matched objects.
zero, zero_err: empirical zero points (cat - instr. magnitudes) and errors.
zero_model, zero_model_err: modeled zero points and fit errors.
color_term: fitted color term used in the calibration.
obj_zero: zero points for all input objects (not necessarily matched).
idx: boolean index for final fit objects.
idx0: boolean index for initial quality cut objects.
- Parameters:
match_results (dict) – Dictionary output from calibrate_photometry().
pixscale (float, optional) – Pixel scale in arcsec/pixel to add fwhm_arcsec and ell columns.
columns (list, optional) – List of columns to retain in the resulting table.
- Returns:
Formatted table of photometric results.
- Return type:
astropy.table.Table
- goodman_photometry.goodman_astro.create_bad_pixel_mask(image, saturation_threshold, binning)#
Create a comprehensive bad pixel mask.
Creates a comprehensive bad pixel mask, identifying and masking saturated pixels, cosmic rays, and pixels outside the circular field of view (FOV) of Goodman images.
- Parameters:
image (numpy.ndarray) – 2D array representing the image data from a FITS file.
saturation_threshold (int) – Saturation threshold derived from calculate_saturation_threshold.
binning (int) – Binning factor of the data (1, 2, 3, etc.).
- Returns:
- Boolean mask with the same dimensions as image.
Pixels are masked (True) if they are bad, otherwise unmasked (False).
- Return type:
numpy.ndarray
- goodman_photometry.goodman_astro.create_goodman_wcs(header)#
Create WCS from a Header.
Creates a WCS (World Coordinate System) guess using telescope coordinates, binning, position angle, and plate scale.
- Parameters:
header (astropy.io.fits.Header) – The FITS header containing necessary metadata.
- Returns:
Updated FITS header with WCS information.
- Return type:
astropy.io.fits.Header
- Raises:
ValueError – If neither “RA”/”DEC” nor “TELRA”/”TELDEC” are present in the header.
- goodman_photometry.goodman_astro.evaluate_data_quality_results(source_catalog: Table)#
Evaluate data quality metrics from a source detection catalog.
This function processes the results of get_objects_sextractor() or a similar source detection catalog, computing median image quality indicators like FWHM and ellipticity.
- Parameters:
source_catalog (astropy.table.Table) – Catalog of detected sources containing columns ‘fwhm’, ‘a’ (major axis), and ‘b’ (minor axis).
- Returns:
fwhm (float): Median FWHM of the sources in pixels.
fwhm_error (float): Median absolute deviation (MAD) of FWHM in pixels.
ellipticity (float): Median ellipticity of the sources (1 - b/a).
ellipticity_error (float): Propagated error of the ellipticity estimate.
- Return type:
tuple
- goodman_photometry.goodman_astro.extract_observation_metadata(header)#
Extract observation metadata from a FITS header and ensure the wavelength mode is IMAGING.
- Parameters:
header (astropy.io.fits.Header) – The FITS header containing observation metadata.
- Returns:
- A tuple containing:
filter_name (str): The active filter name, determined from the header.
serial_binning (int): Binning factor in the serial direction.
parallel_binning (int): Binning factor in the parallel direction.
observation_time (str): The observation time, extracted from the header.
gain (float): The detector gain (e-/ADU).
read_noise (float): The detector read noise (e-).
saturation_threshold (float): The saturation threshold (in ADU), calculated based on the readout mode.
exposure_time (float): The exposure time (in seconds).
- Return type:
tuple
- Raises:
SystemExit – If the wavelength mode (WAVMODE) is not set to “IMAGING”.
- goodman_photometry.goodman_astro.file_write(filename: str, contents: str = None, append: bool = False) None#
Write content to a file.
Opens the file in write or append mode and writes the given content to it.
- Parameters:
filename (str) – Path to the file to write to.
contents (str, optional) – The content to be written into the file. If None, nothing is written.
append (bool, optional) – If True, content is appended to the file. If False (default), the file is overwritten.
- goodman_photometry.goodman_astro.format_astromatic_opts(options: dict) str#
Format a dictionary of options into an Astromatic-compatible command-line string.
Booleans are converted to Y/N, arrays to comma-separated strings, and strings are quoted when necessary.
- Parameters:
options (dict) – Dictionary of options to be converted into command-line arguments.
- Returns:
A formatted string with options suitable for Astromatic tools (e.g., SExtractor, SWarp).
- Return type:
str
- goodman_photometry.goodman_astro.get_filter_set(filter_name: str) tuple[str, str]#
Determine the catalog filter and corresponding photometric filter.
Determine the catalog filter and corresponding photometric filter for calibration, based on the Goodman filter in use.
- Parameters:
filter_name (str) – Goodman filter name (from FITS header FILTER/FILTER2 keywords).
- Returns:
- A tuple containing:
catalog_filter (str): The catalog filter (e.g., Gaia Gmag, BPmag) to retrieve.
photometry_filter (str): The photometric filter used for calibration (e.g., g_SDSS, r_SDSS).
- Return type:
tuple[str, str]
Notes
Currently supports only SDSS filters (u, g, r, i, z). Future improvements:
Add support for Bessel UBVRI, Johnson UBV, Stromgren ubvy, and Kron-Cousins Rc filters.
Handle narrow-band filters separately.
- goodman_photometry.goodman_astro.get_frame_center(filename: str = None, header: Header = None, wcs: WCS = None, image_width: int = None, image_height: int = None, image_shape: tuple = None)#
Calculate the central coordinates (RA, Dec) and field radius of an image.
The function accepts either a WCS object, a FITS header, or a FITS file path. If image dimensions are not provided, they will be extracted from the header or the image shape.
- Parameters:
filename (str, optional) – Path to the FITS file.
header (astropy.io.fits.Header, optional) – FITS header object.
wcs (astropy.wcs.WCS, optional) – World Coordinate System object.
image_width (int, optional) – Width of the image in pixels.
image_height (int, optional) – Height of the image in pixels.
image_shape (tuple, optional) – Image shape as (height, width), used as fallback.
- Returns:
- A tuple of (ra_center, dec_center, search_radius), in degrees.
If a valid celestial WCS is not available, all values will be None.
- Return type:
tuple
- goodman_photometry.goodman_astro.get_intrinsic_scatter(observed_values, observed_errors, min_scatter=0, max_scatter=None)#
Calculate the intrinsic scatter of a dataset given observed values and their errors.
This function estimates the intrinsic scatter by fitting a model that accounts for both observational errors and intrinsic scatter. The intrinsic scatter is constrained to be between min_scatter and max_scatter.
- Parameters:
observed_values (numpy.ndarray) – Array of observed values.
observed_errors (numpy.ndarray) – Array of errors corresponding to the observed values.
min_scatter (float, optional) – Minimum allowed value for the intrinsic scatter. Defaults to 0.
max_scatter (float, optional) – Maximum allowed value for the intrinsic scatter. Defaults to None.
- Returns:
The estimated intrinsic scatter.
- Return type:
float
- goodman_photometry.goodman_astro.get_new_file_name(current_file_name: str, new_path: str = '', new_extension: str = '') str#
Generate a new file path with an optional new directory and/or file extension.
- Parameters:
current_file_name (str) – The original file name with its path.
new_path (str, optional) – The new directory for the file. Defaults to the original directory.
new_extension (str, optional) – The new file extension (can include an underscore, e.g., ‘_BMP.png’). If provided, it replaces the existing extension.
- Returns:
The updated file path.
- Return type:
str
- Raises:
ValueError – If current_file_name is empty.
- goodman_photometry.goodman_astro.get_objects_sextractor(image, header=None, mask=None, err=None, thresh=2.0, aper=3.0, r0=0.0, gain=1, edge=0, minarea=5, wcs=None, sn=3.0, bg_size=None, sort=True, reject_negative=True, checkimages=[], extra_params=[], extra={}, psf=None, catfile=None, _workdir=None, _tmpdir=None, _exe=None, verbose=False)#
Extract objects from an image using SExtractor.
This function is a thin wrapper around the SExtractor binary. It processes the image, taking into account optional mask and noise map, and returns a list of detected objects. Optionally, it can also return SExtractor-produced checkimages.
For more details about SExtractor parameters and principles of operation, refer to the SExtractor documentation at https://sextractor.readthedocs.io/en/latest/. Detection flags (returned in the flags column of the results table) are documented at https://sextractor.readthedocs.io/en/latest/Flagging.html#extraction-flags-flags. Additionally, any object with pixels masked by the input mask in its footprint will have the 0x100 flag set.
- Parameters:
image (numpy.ndarray) – Input image as a NumPy array.
header (astropy.io.fits.Header, optional) – Image header.
mask (numpy.ndarray, optional) – Image mask as a boolean array (True values will be masked).
err (numpy.ndarray, optional) – Image noise map as a NumPy array.
thresh (float, optional) – Detection threshold in sigmas above local background. Used for DETECT_THRESH parameter. Default is 2.0.
aper (float or list, optional) – Circular aperture radius in pixels for flux measurement. If a list is provided, flux is measured for all apertures. Default is 3.0.
r0 (float, optional) – Smoothing kernel size (sigma, or FWHM/2.355) for improving object detection. Default is 0.0.
gain (float, optional) – Image gain in e/ADU. Default is 1.
edge (int, optional) – Reject objects closer to the image edge than this value. Default is 0.
minarea (int, optional) – Minimum number of pixels for an object to be considered a detection (DETECT_MINAREA). Default is 5.
wcs (astropy.wcs.WCS, optional) – Astrometric solution for assigning sky coordinates (ra/dec) to detected objects.
sn (float, optional) – Minimum S/N ratio for an object to be considered a detection. Default is 3.0.
bg_size (int, optional) – Background grid size in pixels (BACK_SIZE). Default is None.
sort (bool, optional) – Whether to sort detections by decreasing brightness. Default is True.
reject_negative (bool, optional) – Whether to reject detections with negative fluxes. Default is True.
checkimages (list, optional) – List of SExtractor checkimages to return. Default is [].
extra_params (list, optional) – List of extra object parameters to return. Default is [].
extra (dict, optional) – Dictionary of extra configuration parameters for SExtractor. Default is {}.
psf (str, optional) – Path to PSFEx-made PSF model file for PSF photometry. Default is None.
catfile (str, optional) – Path to save the output SExtractor catalog. Default is None.
_workdir (str, optional) – Directory for temporary files. If specified, files are not deleted. Default is None.
_tmpdir (str, optional) – Directory for temporary files. Files are deleted after execution. Default is None.
_exe (str, optional) – Path to SExtractor executable. If not provided, the function searches for it in the system PATH. Default is None.
verbose (bool or callable, optional) – Whether to show verbose messages. Can be a boolean or a print-like function. Default is False.
- Returns:
Table of detected objects. If checkimages are requested, returns a list with the table as the first element and checkimages as subsequent elements.
- Return type:
astropy.table.Table or list
- goodman_photometry.goodman_astro.get_observation_time(header=None, filename: str = None, time_string: str = None, return_datetime: bool = False, verbose=False)#
Extract observation time from a FITS header, FITS file, or a user-provided string.
- Parameters:
header (astropy.io.fits.Header, optional) – FITS header with time keywords.
filename (str, optional) – Path to a FITS file (used if header is not provided).
time_string (str, optional) – A user-provided ISO-formatted time string.
return_datetime (bool, optional) – If True, return Python datetime object instead of Astropy Time.
verbose (bool, optional) – Unused, for backward compatibility.
- Returns:
Parsed time object or None if parsing fails.
- Return type:
astropy.time.Time or datetime.datetime or None
- goodman_photometry.goodman_astro.get_photometric_zeropoint(match_results, use_model=False)#
Calculate the median photometric zero point from calibration results.
- Parameters:
match_results (dict) – Output from calibrate_photometry().
use_model (bool) – If True, use modeled zero points instead of empirical ones.
- Returns:
(median_zero_point, median_zero_point_error)
- Return type:
tuple
- goodman_photometry.goodman_astro.get_pixel_scale(wcs=None, filename=None, header=None)#
Return the pixel scale of an image in degrees per pixel.
This function calculates the pixel scale from a WCS object, FITS header, or a FITS file.
- Parameters:
wcs (astropy.wcs.WCS, optional) – A precomputed WCS object.
filename (str, optional) – Path to a FITS file. Used if wcs and header are not provided.
header (astropy.io.fits.Header, optional) – A FITS header object. Used if wcs is not provided.
- Returns:
Pixel scale in degrees per pixel.
- Return type:
float
- Raises:
ValueError – If none of wcs, header, or filename is provided or WCS cannot be constructed.
- goodman_photometry.goodman_astro.get_vizier_catalog(right_ascension, declination, search_radius, catalog='gaiadr2', row_limit=-1, column_filters={}, extra_columns=[], include_distance=False, verbose=False)#
Download any catalog from Vizier.
This function retrieves data from Vizier for a given catalog and field region. For popular catalogs, additional photometric data is augmented based on analytical magnitude conversion formulas.
- Supported catalogs with augmentation:
ps1: Pan-STARRS DR1
gaiadr2: Gaia DR2
gaiaedr3: Gaia eDR3
gaiadr3syn: Gaia DR3 synthetic photometry
skymapper: SkyMapper DR1.1
vsx: AAVSO Variable Stars Index
apass: AAVSO APASS DR9
sdss: SDSS DR12
atlas: ATLAS-RefCat2
usnob1: USNO-B1
gsc: Guide Star Catalogue 2.2
- Parameters:
right_ascension (float) – Right Ascension of the field center in degrees.
declination (float) – Declination of the field center in degrees.
search_radius (float) – Search radius around the field center in degrees.
catalog (str) – Vizier catalog identifier or a supported catalog short name.
row_limit (int) – Maximum number of rows to return. Default is -1 (no limit).
column_filters (dict) – Dictionary of column filters as documented at Vizier.
extra_columns (list) – Additional column names to include in the output.
include_distance (bool) – If True, adds a column for distances from the field center.
verbose (bool) – [Currently unused] Enable verbose logging.
- Returns:
Table containing the catalog data augmented with additional columns, if applicable.
- Return type:
astropy.table.Table
- goodman_photometry.goodman_astro.make_kernel(core_radius: float = 1.0, extent_factor: float = 1.0) ndarray#
Generate a 2D Gaussian kernel image.
The kernel is centered at the origin and defined using a Gaussian profile with a specified core radius and extent.
- Parameters:
core_radius (float, optional) – The Gaussian core radius (standard deviation). Defaults to 1.0.
extent_factor (float, optional) – Extent of the kernel in units of core radius. Determines the size of the kernel array. Defaults to 1.0.
- Returns:
A 2D numpy array representing the Gaussian kernel.
- Return type:
np.ndarray
- goodman_photometry.goodman_astro.make_series(multiplier=1.0, x=1.0, y=1.0, order=1, sum=False, zero=True)#
Generate a polynomial series up to the specified order using x and y.
- Parameters:
multiplier (float) – Scalar multiplier for each term (default is 1.0).
x (float or np.ndarray) – x-values (can be scalar or array).
y (float or np.ndarray) – y-values (can be scalar or array).
order (int) – Maximum order of the polynomial terms.
sum (bool) – If True, return the sum of all terms; otherwise, return the list of terms.
zero (bool) – If True, include a constant term (zeroth order).
- Returns:
List of polynomial terms or their sum (if sum=True).
- Return type:
list[np.ndarray] or np.ndarray
- goodman_photometry.goodman_astro.mask_field_of_view(image, binning)#
Masks out the edges of the field of view (FOV) in Goodman images.
- Parameters:
image (numpy.ndarray) – The image array from the FITS file.
binning (int) – The binning factor (e.g., 1, 2, 3).
- Returns:
- A boolean mask with the same dimensions as ‘image’.
Pixels outside the FOV are masked (True), and others are unmasked (False).
- Return type:
numpy.ndarray
- goodman_photometry.goodman_astro.match(obj_ra, obj_dec, obj_mag, obj_magerr, obj_flags, cat_ra, cat_dec, cat_mag, cat_magerr=None, cat_color=None, sr=0.0008333333333333334, obj_x=None, obj_y=None, spatial_order=0, bg_order=None, threshold=5.0, niter=10, accept_flags=0, cat_saturation=None, max_intrinsic_rms=0, sn=None, verbose=False, robust=True, scale_noise=False, ecmag_thresh=None, cmag_limits=None, use_color=True)#
Low-level photometric matching routine.
This function builds the photometric model for objects detected in an image. It includes catalogue magnitude, positionally-dependent zero point, a linear color term, an optional additive flux term, and considers possible intrinsic magnitude scatter on top of measurement errors.
- Parameters:
obj_ra (ndarray) – Array of Right Ascension values for the objects.
obj_dec (ndarray) – Array of Declination values for the objects.
obj_mag (ndarray) – Array of instrumental magnitude values for the objects.
obj_magerr (ndarray) – Array of instrumental magnitude errors for the objects.
obj_flags (ndarray, optional) – Array of flags for the objects.
cat_ra (ndarray) – Array of catalogue Right Ascension values.
cat_dec (ndarray) – Array of catalogue Declination values.
cat_mag (ndarray) – Array of catalogue magnitudes.
cat_magerr (ndarray, optional) – Array of catalogue magnitude errors.
cat_color (ndarray, optional) – Array of catalogue color values.
sr (float) – Matching radius in degrees.
obj_x (ndarray, optional) – Array of x coordinates of objects on the image.
obj_y (ndarray, optional) – Array of y coordinates of objects on the image.
spatial_order (int) – Order of zero point spatial polynomial (0 for constant).
bg_order (int, optional) – Order of additive flux term spatial polynomial (None to disable this term in the model).
threshold (float, optional) – Rejection threshold (relative to magnitude errors) for object-catalogue pair rejection in the fit.
niter (int) – Number of iterations for the fitting.
accept_flags (int) – Bitmask for acceptable object flags. Objects with any other flags are excluded.
cat_saturation (float, optional) – Saturation level for the catalogue. Stars brighter than this magnitude will be excluded from the fit.
max_intrinsic_rms (float) – Maximum intrinsic RMS for fitting. If set to 0, intrinsic scatter is not included in the noise model.
sn (float, optional) – Minimum acceptable signal-to-noise ratio (1/obj_magerr) for objects included in the fit.
verbose (bool or callable) – Whether to show verbose messages. Can be a boolean or a print-like function.
robust (bool) – Whether to use robust least squares fitting instead of weighted least squares.
scale_noise (bool) – Whether to re-scale the noise model (object and catalogue magnitude errors) to match actual data scatter.
ecmag_thresh (float, optional) – Maximum photometric error threshold for calibration (applies to both observed and catalogue magnitudes).
cmag_limits (tuple, optional) – Magnitude range for catalogue magnitudes (e.g., (8, 22) for reasonable photometry limits).
use_color (bool) – Whether to use catalogue color in deriving the color term.
- Returns:
Dictionary containing the results of the photometric matching:
oidx (ndarray): Indices of matched objects in the object list.
cidx (ndarray): Indices of matched catalogue stars.
dist (ndarray): Pairwise distances between matched objects and catalogue stars (in degrees).
omag (ndarray): Instrumental magnitudes of matched objects.
omag_err (ndarray): Errors of instrumental magnitudes.
cmag (ndarray): Catalogue magnitudes of matched objects.
cmag_err (ndarray): Errors of catalogue magnitudes.
color (ndarray): Catalogue colors corresponding to the matches (zeros if no color term fitting).
ox (ndarray): x coordinates of matched objects on the image.
oy (ndarray): y coordinates of matched objects on the image.
oflags (ndarray): Flags of matched objects.
zero (ndarray): Empirical zero points (catalogue - instrumental magnitudes).
zero_err (ndarray): Errors of the empirical zero points.
zero_model (ndarray): Modeled zero points (including color terms) for matched objects.
zero_model_err (ndarray): Errors of the modeled zero points.
color_term (float or None): Fitted color term, where instrumental magnitude is defined as obj_mag = cat_mag - color * color_term. None if color term is not used.
zero_fn (callable): Function to compute the zero point (without color term) at a given position and instrumental magnitude.
obj_zero (ndarray): Zero points computed for all input objects (not necessarily matched to the catalogue) using zero_fn (excluding the color term).
params (ndarray): Internal parameters of the fitted polynomial.
intrinsic_rms (float): Fitted value of intrinsic scatter.
error_scale (float): Noise scaling factor.
idx (ndarray): Boolean mask indicating objects/catalogue stars used in the final fit (excluding rejected ones).
idx0 (ndarray): Boolean mask indicating objects/catalogue stars passing only initial quality cuts.
- Return type:
dict
zero_fn is a callable function with the signature:
zero_fn(xx, yy, mag=None, get_err=False, add_intrinsic_rms=False)
where: - xx, yy: Image coordinates. - mag: Instrumental magnitude of the object (needed for the additive flux term). - get_err: If True, returns the estimated zero point error instead of zero point value. - add_intrinsic_rms: If True, includes the intrinsic scatter term in the error estimation.
The computed zero point from zero_fn does not include the contribution of the color term. To derive the final calibrated magnitude:
mag_calibrated = mag_instrumental + color * color_term
where color is the object’s true color, and color_term is the fitted color term in the output dictionary.
- goodman_photometry.goodman_astro.plot_image(image, wcs=None, quantiles=(0.01, 0.99), cmap='Blues_r', x_points=None, y_points=None, use_wcs_for_points=False, point_marker='r.', point_size=2, title=None, figsize=None, show_grid=False, output_file=None, dpi=300, save_to_file=False)#
Plot a 2D image with optional WCS projection, color scaling, and overlay points.
- Parameters:
image (numpy.ndarray) – The 2D array representing the image data to be plotted.
wcs (astropy.wcs.WCS, optional) – The WCS object for astronomical projections. If None, a standard plot is created.
quantiles (tuple of float, optional) – Percentile values for scaling image brightness (default is (0.01, 0.99)).
cmap (str, optional) – Colormap to use for the image (default is ‘Blues_r’).
x_points (array-like, optional) – X-coordinates of points to overlay on the image.
y_points (array-like, optional) – Y-coordinates of points to overlay on the image.
use_wcs_for_points (bool, optional) – Whether to transform points using WCS (default is False).
point_marker (str, optional) – Matplotlib marker style for the overlay points (default is ‘r.’).
point_size (float, optional) – Size of the overlay points (default is 2).
title (str, optional) – Title for the plot.
figsize (tuple of float, optional) – Size of the figure in inches (width, height). If None, defaults to Matplotlib’s default.
show_grid (bool, optional) – Whether to overlay a grid (default is False).
output_file (str, optional) – File path to save the plot. If None, the plot is displayed instead of being saved (default is None).
dpi (int, optional) – Resolution of the saved plot in dots per inch (default is 300).
- Returns:
This function does not return any value. It either displays the plot or saves it to a file if output_file is provided.
- Return type:
None
- Raises:
ValueError – If the quantiles are invalid (e.g., negative or out of range).
- goodman_photometry.goodman_astro.plot_photcal(image, phot_table, wcs=None, column_scale='mag_calib', quantiles=(0.02, 0.98), output_file=None, save_to_file=False, show_plot=False, dpi=300)#
Plot a calibrated photometric image with source ellipses colored by a photometric quantity.
- Parameters:
image (np.ndarray) – 2D image array to display.
phot_table (astropy.table.Table) – Table of photometric detections.
wcs (astropy.wcs.WCS, optional) – WCS solution for the image.
column_scale (str) – Column in phot_table to use for color mapping.
quantiles (tuple of float) – Lower and upper quantiles for image display scaling.
output_file (str, optional) – Path to save the plot. If None, plot is shown.
show_plot (bool, optional) – Whether to show the plot. Defaults to False.
dpi (int) – Resolution of the saved plot in dots per inch.
- goodman_photometry.goodman_astro.plot_photometric_match(match_result, ax=None, mode='mag', show_masked=True, show_final=True, cmag_limits=None, **kwargs)#
Visualizes photometric match results in various modes.
This function generates different types of diagnostic plots based on the results of a photometric matching routine. The visualization can include magnitude residuals, normalized residuals, color dependencies, zero points, model predictions, residuals, and distance distributions.
- Parameters:
match_result (dict) – Dictionary containing the results of photometric matching. Expected keys include: - idx0 (ndarray): Boolean mask indicating objects used in initial fitting. - idx (ndarray): Boolean mask indicating objects used in the final fit. - cmag (ndarray): Catalogue magnitudes of matched objects. - zero (ndarray): Empirical zero points (catalogue - instrumental magnitudes). - zero_model (ndarray): Modeled zero points. - zero_err (ndarray): Errors of the empirical zero points. - color (ndarray, optional): Catalogue colors of matched objects. - ox, oy (ndarray): x and y coordinates of objects on the image. - dist (ndarray): Pairwise distances between matched objects and catalogue stars (in degrees). - cat_col_mag, cat_col_mag1, cat_col_mag2 (str, optional): Names of the catalogue magnitudes and colors. - color_term (float, optional): Fitted color term for magnitude transformation.
ax (matplotlib.axes.Axes, optional) – The matplotlib axis to plot on. If None, the current axis (plt.gca()) will be used.
mode (str) – Type of plot to generate. Options include: - ‘mag’: Residuals vs. catalogue magnitude. - ‘normed’: Normalized residuals vs. magnitude. - ‘color’: Residuals vs. catalogue color. - ‘zero’: Spatial map of the zero point. - ‘model’: Spatial map of the model zero point. - ‘residuals’: Spatial map of residuals (instrumental - model). - ‘dist’: Spatial map of displacement between matched objects and catalogue stars.
show_masked (bool, optional) – Whether to display masked data points (those that were rejected from the final fit). Defaults to True.
show_final (bool, optional) – Whether to highlight the final selection of matched objects used in the fit. Defaults to True.
cmag_limits (tuple, optional) – Limits for the x-axis in magnitude plots (e.g., (8, 22)). If None, limits are automatically determined.
**kwargs – Additional arguments passed to binned_map, which is used for spatial mapping plots.
- Returns:
The axis containing the generated plot.
- Return type:
matplotlib.axes.Axes
Notes
The function includes a _model_string() helper to display the photometric transformation equation used.
_plot_residual_vs() is a helper function to generate various residual plots.
When binned_map is used (for zero, model, residuals, and dist modes), it creates a spatially binned visualization of the respective quantities.
- goodman_photometry.goodman_astro.refine_wcs_scamp(obj, cat=None, wcs=None, header=None, sr=0.0005555555555555556, order=3, cat_col_ra='RAJ2000', cat_col_dec='DEJ2000', cat_col_ra_err='e_RAJ2000', cat_col_dec_err='e_DEJ2000', cat_col_mag='rmag', cat_col_mag_err='e_rmag', cat_mag_lim=99, sn=None, extra={}, get_header=False, update=False, _workdir=None, _tmpdir=None, _exe=None, verbose=False)#
Refine the WCS solution using SCAMP.
This function is a wrapper for running SCAMP on a user-provided object list and reference catalog to refine the astrometric solution. It matches objects in the frame with a reference catalog and computes a refined WCS solution.
- Parameters:
obj (astropy.table.Table) – List of objects on the frame, containing at least x, y, and flux columns.
cat (astropy.table.Table or str, optional) – Reference astrometric catalog or name of a network catalog. Default is None.
wcs (astropy.wcs.WCS, optional) – Initial WCS solution. Default is None.
header (astropy.io.fits.Header, optional) – FITS header containing the initial astrometric solution. Default is None.
sr (float, optional) – Matching radius in degrees. Default is 2/3600.
order (int, optional) – Polynomial order for PV distortion solution (1 or greater). Default is 3.
cat_col_ra (str, optional) – Catalog column name for Right Ascension. Default is ‘RAJ2000’.
cat_col_dec (str, optional) – Catalog column name for Declination. Default is ‘DEJ2000’.
cat_col_ra_err (str, optional) – Catalog column name for Right Ascension error. Default is ‘e_RAJ2000’.
cat_col_dec_err (str, optional) – Catalog column name for Declination error. Default is ‘e_DEJ2000’.
cat_col_mag (str, optional) – Catalog column name for the magnitude in the closest band. Default is ‘rmag’.
cat_col_mag_err (str, optional) – Catalog column name for the magnitude error. Default is ‘e_rmag’.
cat_mag_lim (float or list, optional) – Magnitude limit for catalog stars. If a list, treated as lower and upper limits. Default is 99.
sn (float or list, optional) – Signal-to-noise ratio threshold for object matching. If a list, treated as lower and upper limits. Default is None.
extra (dict, optional) – Dictionary of additional parameters to pass to SCAMP. Default is {}.
get_header (bool, optional) – If True, return the FITS header instead of the WCS solution. Default is False.
update (bool, optional) – If True, update the object list in-place with refined ra and dec coordinates. Default is False.
_workdir (str, optional) – Directory for temporary files. If specified, files are not deleted. Default is None.
_tmpdir (str, optional) – Directory for temporary files. Files are deleted after execution. Default is None.
_exe (str, optional) – Path to SCAMP executable. If not provided, the function searches for it in the system PATH. Default is None.
verbose (bool or callable, optional) – Whether to show verbose messages. Can be a boolean or a print-like function. Default is False.
- Returns:
Refined WCS solution or FITS header if get_header=True. Returns None if the refinement fails.
- Return type:
astropy.wcs.WCS or astropy.io.fits.Header
- goodman_photometry.goodman_astro.spherical_distance(ra_deg_1, dec_deg_1, ra_deg_2, dec_deg_2)#
Calculate the spherical angular distance between two celestial coordinates.
This function computes the great-circle distance between two points on the celestial sphere using a trigonometric approximation formula.
- Parameters:
ra_deg_1 (float or np.ndarray) – Right ascension of the first point(s) in degrees.
dec_deg_1 (float or np.ndarray) – Declination of the first point(s) in degrees.
ra_deg_2 (float or np.ndarray) – Right ascension of the second point(s) in degrees.
dec_deg_2 (float or np.ndarray) – Declination of the second point(s) in degrees.
- Returns:
Spherical angular distance(s) in degrees between the coordinate pairs.
- Return type:
float or np.ndarray
- goodman_photometry.goodman_astro.spherical_match(ra_deg_1, dec_deg_1, ra_deg_2, dec_deg_2, search_radius_deg=0.0002777777777777778)#
Perform spherical positional matching between two lists of celestial coordinates.
Uses astropy.coordinates.search_around_sky to identify matches between two sets of coordinates within a given angular search radius.
- Parameters:
ra_deg_1 (float or np.ndarray) – Right ascension of the first list (in degrees).
dec_deg_1 (float or np.ndarray) – Declination of the first list (in degrees).
ra_deg_2 (float or np.ndarray) – Right ascension of the second list (in degrees).
dec_deg_2 (float or np.ndarray) – Declination of the second list (in degrees).
search_radius_deg (float, optional) – Maximum allowed angular separation (in degrees) to be considered a match. Default is 1 arcsecond (1/3600 degrees).
- Returns:
- A tuple of three arrays:
matched_indices_1 (np.ndarray): Indices in the first list of matched coordinates.
matched_indices_2 (np.ndarray): Indices in the second list of matched coordinates.
matched_distances_deg (np.ndarray): Angular distances (in degrees) between matched pairs.
- Return type:
tuple
- goodman_photometry.goodman_astro.table_get_column(table: Table, column_name: str, default=0)#
Get a column from an astropy table, or return a default value if it is missing.
This is a convenience wrapper to safely access a column in a table.
- Parameters:
table (astropy.table.Table) – Input table.
column_name (str) – Name of the column to retrieve.
default (scalar or array-like, optional) – Default value to return if the column is not found. If scalar, it will be broadcasted to match the table length. If array-like, it will be returned directly. If None, the function returns None.
- Returns:
The column values if found, otherwise the default value broadcasted or returned as-is depending on its type.
- Return type:
np.ndarray or None
- goodman_photometry.goodman_astro.table_to_ldac(table, header=None, writeto=None)#
Convert an Astropy Table to an LDAC-style FITS HDU list.
- Parameters:
table (astropy.table.Table) – The data table to convert.
header (astropy.io.fits.Header, optional) – FITS header to include. If None, an empty header is used.
writeto (str, optional) – If provided, writes the HDU list to a FITS file.
- Returns:
The HDU list containing the primary, header, and data extensions.
- Return type:
astropy.io.fits.HDUList
- goodman_photometry.goodman_astro.wcs_sip2pv(header)#
Convert the WCS header from SIP (Simple Imaging Polynomial) to TPV (Tangent Plane Polynomial) representation.
This function modifies the input FITS header to replace SIP distortion keywords with TPV distortion keywords. It ensures the presence of the CD matrix by converting the PC matrix if necessary.
- Parameters:
header (astropy.io.fits.Header or dict) – The FITS header containing SIP distortion keywords.
- Returns:
The modified header with TPV distortion keywords.
- Return type:
astropy.io.fits.Header or dict