UVIS_Observation#
Cassini/UVIS observation built from one or several PDS3 products.
- class cassini_upyp.uvisdata.UVIS_Observation(*files, batch=None, target=None, prime_instrument=None, ID=0, name=None, sort=True)#
Bases:
objectCassini/UVIS observation assembled from one or more PDS3 products.
This class loads UVIS PDS3 data/label pairs (
.DAT/.LBL), concatenates exposures in time order, and provides utilities for:calibration (counts/s -> radiance),
background noise estimation and subtraction,
geometry computation from SPICE kernels,
stellar contamination identification,
pixel binning based on geometry or manual selection.
See [1] for details on UVIS data processing.
- Parameters:
*files (str or pathlib.Path or iterable of (str or pathlib.Path)) –
One or more PDS base paths (with or without extension). Each entry can be: If a single iterable is passed (e.g. a list of paths), it is unpacked.
If exactly two paths are provided and they form a single .LBL/.DAT pair, they are interpreted as one explicit product.
Otherwise, each input is interpreted as a product base path: the extension (if any) is ignored and the corresponding .LBL and .DAT files are expected to share the same base name.
Strings are treated as paths, not as iterables of characters.
batch (str or pathlib.Path, optional) –
Path to a text file listing PDS products, one per line.
Each line may be an absolute path or a path relative to the location of the batch file. Relative paths are interpreted with respect to the directory containing the batch file.
If
batchis provided, it overrides*files. The same pairing rules apply as for*files: if the batch contains exactly two entries forming a .LBL/.DAT pair, they are treated as a single explicit product; otherwise, each entry is interpreted as a product base path.target (str, optional) – Main target name used for georeference computations. Stored uppercased. Default is
None.prime_instrument ({"PRIME", "UVIS", "CIRS", "VIMS", "ISS"}, optional) – Prime instrument tag stored in metadata and used for naming. If “UVIS” is provided, it is normalized internally to “PRIME”.
ID (int, optional) – Extra identifier used when multiple observations share the same base name. Default is 0 (no identifier).
name (str, optional) – If provided, overrides the auto-generated observation name. The default name is constructed as:
CHANNEL_YEAR_DOY_INSTRUMENT(_ID)sort (bool, optional) – If True (default), input files (and resulting exposures) are ordered by spacecraft clock start time.
- Variables:
name (str) – Observation name (auto-generated or user-provided).
target (str or None) – Target name (uppercased) or None.
YEAR (int) – Observation year (from first exposure).
DOY (int) – Day of year of the observation (from first exposure).
channel ({"FUV", "EUV"}) – UVIS channel inferred from the first product ID.
prime (str) – Prime instrument tag used in metadata/naming.
n_pics (int) – Number of exposures (time samples).
n_pixels (int) – Number of spatial pixels.
n_wl (int) – Number of spectral pixels.
slit (str) – Slit state (from first product). Can be “OCCULTATION”, “LOW_RESOLUTION”, or “HIGH_RESOLUTION”.
slit_width (float) – Slit width [µm].
slit_dlambda (float) – Slit width image on the spectral dimension detector [Å]. Defines the point spread function (PSF).
WL (numpy.ndarray) – Wavelength grid for the detector [Å]. Shape: (n_wl,).
counts (numpy.ndarray) – Raw detector counts. Shape: (n_pics, n_pixels, n_wl).
cps (numpy.ndarray) – Counts per second (counts / expo_time). Same shape as
counts.cps_bg_removed (numpy.ndarray) – Background-corrected counts per second. Same shape as
counts.data (numpy.ndarray) – Calibrated radiance array [kR]. Same shape as
counts). Populated bycalibrate().uncertainty_sup (numpy.ndarray or None) – Upper radiance uncertainty array. Populated by
calibrate()/get_radiance_uncertainty().uncertainty_inf (numpy.ndarray or None) – Lower radiance uncertainty array. Populated by
calibrate()/get_radiance_uncertainty().calibration (numpy.ndarray) – Calibration multiplier per exposure [kR/counts]. Same shape as
counts.calibration_error (numpy.ndarray) – Calibration uncertainty array.
geometry (list[Geometry] or None) – Per-exposure
Geometryobjects. Populated byset_geometry().pixel_LOS (numpy.ndarray or None) – Structured array of line-of-sight geometry per pixel and exposure. Fields:
"lon"[°],"lat"[°],"alt"[km],"sza"[°],"phase"[°],"ems"[°],"lt"[h]. Shape: (n_pics, n_pixels, 5) for each field. The last dimension corresponds to the pixel center, bottom-left, bottom-right, upper-right, and upper-left corners, respectively.spacecraft_position (numpy.ndarray or None) – Sub-spacecraft point properties in planetocentric coordinates (shape: (n_pics,) Fields:
"lon"[°],"lat"[°],"alt"[km],"sza"[°],"phase"[°],"ems"[°],"lt"[h]. Altitude is the spacecraft altitude.HD (float or None) – Mean heliocentric distance during the observation. Populated by
set_geometry().pixel_stars_mask (numpy.ndarray) – Boolean mask of star-contaminated pixels (shape: (n_pics, n_pixels)).
pixel_corrupted (numpy.ndarray) – Boolean mask of pixels showing partial data (shape: (n_pics, n_pixels)).
evil_pixels (numpy.ndarray) – Boolean mask of known bad pixels on the detector. Shape: (64, 1024).
evil_pixels_binned (numpy.ndarray) – Boolean mask of known bad pixels after binning. Shape: (n_pixels, n_wl).
background_level (float) – Background level in counts/s per spectral pixel (before binning factors).
background_error (float) – Uncertainty on background_level.
ET_start (numpy.ndarray) – Ephemeris times at each exposure start (seconds past J2000).
ET_middle (numpy.ndarray) – Ephemeris times at each exposure mid-point.
ET_stop (numpy.ndarray) – Ephemeris times at each exposure end.
UTC_start (list[str]) – UTC strings for exposure start times.
UTC_middle (list[str]) – UTC strings for exposure mid-point times.
UTC_stop (list[str]) – UTC strings for exposure end times.
time_exposition (numpy.ndarray) – Array of times during the each exposure (s). Shape : (n_pics, PicsPerExposure). PicsPerExposure is defined in the pipeline defaults file. Default is 60. Useful for getting geometric information at finer time resolution than the exposure cadence.
is_calibrated (bool) – True if data has been populated by calibrate().
calibration_set (bool) – True if per-exposure calibration arrays are set.
is_bkg_removed (bool) – True if background correction has been applied to cps_bg_removed.
is_smoothed (bool) – True if smoothing has been applied to calibrated spectra.
instrument (Instrument) – Cassini/UVIS
Instrumentobject providing instrument properties and SPICE instrument kernel management.pds_data (list of PDSRawData) – List of loaded PDS products forming the observation.
Notes
All PDS products are saved into
self.pds_dataasPDSRawDataobjects.Geometry is not computed during initialization. Call
set_geometry()to populateself.geometryandself.pixel_LOS.This initializer loads and unloads SPICE kernels (LSK, and IK indirectly via Instrument). Ensure the kernel paths are correctly configured in your environment configuration.
See also
set_geometry()Compute SPICE-based geometry for each exposure.
set_background()Estimate and/or set detector background level.
calibrate()Apply radiometric calibration and populate calibrated arrays.
bin_pixels()Bin pixels geometrically or manually into a
UVIS_Bincontainer.
References
[1] Le Guennic et al. (2026)
- integrate_radiance(wl_range=None, method='simpson')#
Integrate the calibrated radiance over a specified wavelength range.
- Parameters:
wl_range (tuple of float, optional) – Wavelength range (min, max) for integration. If None (default), integrates over the full wavelength range of the detector.
method ({'simpson', 'trapezoid'}, optional) – Integration method to use. Default is ‘simpson’. See
cassini_upyp.uvisutils.integrate_spectrum()for details.
- Returns:
Integrated radiance values per exposure and spatial pixel.
- Return type:
numpy.ndarray
- get_radiance_uncertainty()#
Compute per-pixel radiance uncertainties (upper/lower).
Uses Garwood Poisson bounds on detector counts, then propagates count and calibration uncertainties to radiance. If a background level is set, adds its contribution in quadrature.
Uses
cassini_upyp.uvisutils.poisson_error()to compute count uncertainties.- Returns:
(uncertainty_sup, uncertainty_inf), same shape as
self.counts.- Return type:
tuple[np.ndarray, np.ndarray]
- Raises:
RuntimeError – If calibration has not been set prior to calling this method.
- smooth(force=False, smoothing_kernel=array([0.0625, 0.25, 0.375, 0.25, 0.0625]))#
Smooth the calibrated FUV data and uncertainties using 1D convolution. Uses
cassini_upyp.uvisutils.smooth_spectrum()for convolution.- Parameters:
force (bool, optional) – If True, forces smoothing even if data is already smoothed. Default is False.
smoothing_kernel (array-like, optional) – 1D array defining the smoothing kernel.
Notes
Smoothing is applied only on valid (non-NaN) data points.
- get_calibration(sctime, interp='pchip', flat_field=True)#
Retrieve the calibration multiplier (inverse sensitivity) of the Cassini UVIS instrument.
The method incorporates several calibration steps:
Laboratory calibration data is adjusted for slit width.
Time variation is accounted for using spacecraft time.
Flat-field corrections are applied if flat_field is True.
Binning is performed according to the spatial and spectral binning factors.
- Parameters:
sctime (float) – Spacecraft time of the observation, used to apply time-dependent calibration modifiers and to select the appropriate flat-field epoch.
interp ({'linear', 'pchip'}, optional) –
Interpolation method used to map the lab calibration to the full detector range. See
uvisutils.interpolate_nans()for details.Default is ‘pchip’.
flat_field (bool, optional) – If True, apply flat-field correction (including its time variation). If False, the flat-field is effectively disabled. Default is True.
- Returns:
A dictionary containing:
- ’calibration’numpy.ndarray
The calibration multiplier, binned and shaped to match the raw data dimensions.
- ’calibration_error’numpy.ndarray
The calibration error array.
- Return type:
dict[str, np.ndarray]
Notes
For the FUV channel, pixels known as ‘evil’ pixels with anomalous behavior are handled, and corresponding elements in the arrays are set to NaN.
- set_calibration(**kwargs)#
Set calibration factors for all exposures.
This method computes and assigns calibration factors and uncertainties for each exposure using the get_calibration method.
- Parameters:
**kwargs – Additional keyword arguments passed to get_calibration.
- calibrate(wl_interp='pchip', nan_interp='linear', flat_field=True, smooth=True)#
Calibrate counts/s to radiance and populate data and uncertainty arrays.
- Parameters:
wl_interp ({"pchip","linear"}) – Interpolation used when building calibration sensitivity vs wavelength.
nan_interp ({"linear","pchip"}) – Interpolation used to fill NaNs in calibrated spectra.
flat_field (bool) – Apply flat-field and its time-dependent modifier.
smooth (bool) – Apply spectral smoothing.
- get_geometry(ET, **kwargs)#
Compute the geometry for a given ephemeris time.
- Parameters:
ET (float) – Ephemeris time for which to compute the geometry.
**kwargs – Additional keyword arguments for the Geometry class.
- Returns:
A Geometry object computed for the given time.
- Return type:
- set_geometry(et_range=None, **kwargs)#
Compute and set geometry for a range of exposures.
- Parameters:
et_range (array_like, optional) – Array of ephemeris times for which to compute geometry. If None, the middle time of each exposure is used.
**kwargs – Additional keyword arguments passed to the geometry computation.
Notes
This method updates the geometry attribute and computes the mean heliocentric distance (HD) and line-of-sight pixel data.
- plot_all_geometry(folder, out_format='png', duration=0.016666666666666666, **kwargs)#
Plot geometry for all exposures and save the results.
- Parameters:
folder (str or Path) – Directory in which to save the plots or GIF.
out_format (str, optional) – Output format (‘png’ for individual images or ‘gif’ for animation). Default is ‘png’.
duration (float, optional) – Duration per frame for GIF animation (in seconds). Default is 1/60.
- UV_picture(wl_range=None, **kwargs)#
Build and plot a projected UV radiance map for this observation.
This is a convenience wrapper around
cassini_upyp.geometry.UV_picture.UV_picture(). See that function for the full parameter list and plotting options.- Parameters:
wl_range (tuple[float, float] or None, optional) – Wavelength interval passed to the UV map builder.
**kwargs – Additional keyword arguments forwarded to
cassini_upyp.geometry.UV_picture.UV_picture().
- Returns:
matplotlib.figure.Figure – Figure containing the UV map.
matplotlib.axes.Axes – Axes containing the UV map.
- add_pixel_stars_from_file(file)#
Add star contamination data from a file.
- Parameters:
file (str) – Path to the file containing star pixel information.
Notes
The file should have a header followed by lines with two values representing pixel indices.
- plot_radiance_evolution(output_path=None, ylim=(0.01, 20), yscale='log', wl_range=(1600, 1900), method='trapezoid')#
Plot the evolution of integrated radiance for each pixel over exposures.
- Parameters:
output_path (str | Path, optional) – File path to save the PDF containing the plots. Default is ‘signal_time_variation.pdf’.
ylim (tuple[float, float], optional) – Y-axis limits for the plots. Default is (0.01, 20).
yscale (str, optional) – Scale for the y-axis (‘log’ or ‘linear’). Default is ‘log’.
wl_range (tuple[float, float], optional) – Wavelength range for integration. Default is (1600, 1900).
method ({'simpson', 'trapz'}, optional) – Integration method to use. Default is ‘simpson’.
- check_stars(cmap='plasma', wl_range=(1600, 1900), method='trapezoid')#
Create an interactive heatmap of integrated radiance to identify and flag pixels contaminated by stars or other artefacts.
The plot displays integrated radiance per (exposure, pixel) cell. Users can click cells to toggle them as contaminated; selected cells are tracked in
self.pixel_starsandself.pixel_stars_mask. Sliders allow real-time adjustment of the color scale, exposure range, and colormap.- Parameters:
cmap (str, optional) – Initial colormap. Default is
'gist_ncar'.wl_range (tuple of float, optional) – Wavelength bounds for radiance integration, in angströms. Default is
(1600, 1900).method ({'simpson', 'trapz', 'trapezoid'}, optional) – Numerical integration method. Default is
'trapezoid'.
See also
cassini_upyp.uvisdata.UVIS_Observation.integrate_radiance(),cassini_upyp.geometry.UV_picture.UV_picture()
- save_stars(filepath)#
Save the list of stellar-contaminated pixels to a text file.
- Parameters:
filepath (str or Path) – Output path for the star pixel list.
- Returns:
The original filepath argument.
- Return type:
str or Path
- get_background(alt_limit, mode='simulate', wl_range=(1400, 1850))#
Compute the background noise level and its uncertainty from the raw detector counts.
This method selects background pixels based on altitude criteria from the geometry (using self.pixel_LOS) and calculates the average counts per second over a specified wavelength range. It supports two modes: - ‘average’: simply average the counts of background pixels. - ‘simulate’: perform a simulation by fitting a histogram of gaps in the counts, optionally in parallel.
- Parameters:
mode ({'average', 'simulate'}, optional) – The method to compute the background. Default is ‘simulate’.
alt_limit (float) – Minimum altitude limit to consider a pixel as background.
wl_range (tuple of int, optional) – Wavelength range (min, max) to consider for background calculation. Default is (1600, 1900).
parallel (bool, optional) – Whether to perform the simulation in parallel processing. Default is True.
- Returns:
A tuple (cps, cps_err) representing the background counts per second and its uncertainty.
- Return type:
tuple of float
- Raises:
ValueError – If the specified wavelength range is outside the detector range or if geometry is not initialized.
- set_background(bg=None, bg_uncertainty=None, **kwargs)#
Set (or estimate) the detector background level and update background-corrected CPS.
If bg and bg_uncertainty are not provided, estimates them with get_background(**kwargs). Then updates self.cps_bg_removed.
- Parameters:
bg (float, optional) – Background level in counts/s per spectral pixel (before applying UVIS binning).
bg_uncertainty (float, optional) – 1-sigma uncertainty on bg, same units as bg.
**kwargs – Passed to get_background() when estimating the background.
Notes
- self.cps_bg_removed is computed as:
cps_bg_removed = cps - bg * SPATIAL_BIN * SPECTRAL_BIN
If the observation is already calibrated, this method refreshes the calibrated data to reflect the updated background.
- bin_pixels(pixels=None, keys=('lat', 'alt', 'lt'), bin_boundaries=(array([-90, -70, -50, -30, -10, 10, 30, 50, 70, 90]), [0, 50, 150, 250, 350, 450, 550, 650, 750, 850, 950, 1050, 1150, 1250, 1350, 1450, 1550, inf], [0, 12, 24]), mode='center', modulo=None)#
Bin detector pixels either automatically using geometric criteria or manually using explicit pixel indices.
Two mutually exclusive binning modes are supported:
1) Automatic (geometric) binning Pixels are assigned to bins based on geometric quantities stored in
pixel_LOS(e.g. latitude, altitude, local time), using user-defined bin boundaries.2) Manual binning Pixels are grouped explicitly by providing their detector indices
(i_pic, i_pix). In this mode, no geometric selection is performed.- Parameters:
pixels (sequence or None, optional) –
Manual pixel selection. If None, automatic geometric binning is used.
Accepted formats are:
[(i, j), (i, j), ...]: a single bin containing all listed pixels.[[(i, j), ...], [(i, j), ...], ...]: multiple bins, each defined by its own list of pixels.
Indices are interpreted as
(exposure_index, pixel_index).keys (tuple of str, optional) –
Geometric quantities used for automatic binning. Each key must correspond to a field in
pixel_LOS.Accepted values are:
'lon': longitude of the tangent point of the line of sight'lat': latitude'alt': altitude'sza': solar zenith angle'phase': phase angle'ems': emission angle'lt': local time
bin_boundaries (tuple of sequences, optional) – Bin boundaries for each geometric key. The number of boundary arrays must match the number of keys. Bin boudaries must be monotonically increasing and cover the range of values in the data. Modular quantities (e.g. longitude, local time) are handled with wrap-around logic.
mode ({'center', 'all'}, optional) –
Selection mode for geometric binning:
'center': use the central LOS value of each pixel.'all'require all LOS samples of the pixel to fall withinthe bin boundaries.
modulo (float, optional) – Modulo value for wrap-around of geometric quantities (e.g. 360 for longitude, 24 for local time). Required if any of the keys are modular.
- Returns:
A
UVIS_Bininstance containing the binned pixel indices and, if geometry is available, the mean geometric properties per bin.- Return type:
- Raises:
RuntimeError – If automatic binning is requested but
pixel_LOSis not set.ValueError – If input formats are invalid or inconsistent.
Examples
Automatic geometric binning by altitude and latitude:
- bins = uvis_obs.bin_pixels(
keys=(‘alt’, ‘lat’), bin_boundaries=(
np.arange(500, 1000, 50), # altitude bins (km) np.linspace(-90, 90, 19) # latitude bins (deg)
), mode=’center’
)
- Automatic geometric binning by longitude:
- bins = uvis_obs.bin_pixels(
keys=(‘lon’,), bin_boundaries=(
[350, 10, 30], # Two bins: [350-360] U [0-10], and [10-30] degrees
), modulo = 360 )
Manual binning of explicitly selected pixels into a single bin:
- bins = uvis_obs.bin_pixels(
pixels=[(20, 39), (21, 40), (22, 41)]
)
Manual binning into multiple independent bins:
- bins = uvis_obs.bin_pixels(
- pixels=[
[(20, 39), (21, 40)], [(10, 5), (10, 6), (10, 7)]
]
)
- save(filepath=None, overwrite=False)#
Saves the current UVIS_Observation instance to a pickle (.pkl) file. The object is save without self.geometry attribute unless keyword fullsave is set.
- Parameters:
filepath (str, optional) – Path of the output file. Defaults to “<self.name>.pkl”.
overwrite (bool, optional) – If True, overwrites an existing file without asking. Defaults to False.
- Returns:
The final filepath of the saved pickle file.
- Return type:
str
- Raises:
PermissionError – If the file cannot be written due to permission issues.
OSError – For other I/O-related errors.
- save_JSON(filepath=None, overwrite=False)#
Saves main attributes of the current UVIS observations to a JSON file.
- Parameters:
filepath (str, optional) – The desired filepath for the JSON file. If not provided, defaults to “<self.name>.json”.
overwrite (bool, optional) – If True, overwrites the file if it already exists. Defaults to False.
- Returns:
The final filepath of the saved JSON file.
- Return type:
str
- Raises:
PermissionError – If the file cannot be written due to permission issues.
OSError – For other I/O related errors.
- classmethod load_JSON(filepath)#
Loads the specified JSON file and returns its content as a dictionary.
- Parameters:
filepath (str) – The path to the JSON file to load.
- Returns:
A dictionary containing the data from the JSON file.
- Return type:
dict
- Raises:
FileNotFoundError – If the specified file does not exist.
PermissionError – If the file cannot be opened due to permission issues.
OSError – For other I/O related errors.