hypso#

A python package form NTNU HYPSO Hyperspectral Image Processing

Submodules#

Classes#

Product

One capture at one processing level.

Functions#

get_hypso1_wavelengths([aoi_x, column_count, bin_factor])

Nominal HYPSO-1 band-centre wavelengths (nm) for an AOI and binning.

get_hypso2_wavelengths([aoi_x, column_count, bin_factor])

Nominal HYPSO-2 band-centre wavelengths (nm) for an AOI and binning.

open(path[, wavelength_range, wavelengths, indices])

Read a HYPSO product file.

read_product(path[, wavelength_range, wavelengths, ...])

Read any supported HYPSO product file into the in-memory model.

write_product(tree, path[, datacube, significant_bits])

Write a product tree in the current file format.

Package Contents#

class hypso.Product(tree)[source]#

One capture at one processing level.

Create one with hypso.open() or from a product tree. A Product is immutable: processing methods return a new Product.

Parameters:

tree (xarray.DataTree) – A product tree as read by hypso.io.product.read_product().

Raises:

ValueError – If the tree has no valid processing_level (L1A-L1C, L2A, L2B).

area_definition()[source]#

A gridded product’s grid as a pyresample.geometry.AreaDefinition.

Raises:

ValueError – If the product is in sensor geometry.

calibrate(coeff_type=None, version=None, **kwargs)[source]#

Calibrate L1A to L1B: top-of-atmosphere radiance Lt.

The L1B has no geolocation until georeference(). Leave that out when only radiance is needed.

Parameters:
  • coeff_type (str, optional) – Radiometric variant: "abs" (default), "moved" or "lab".

  • version (str or dict, optional) – Coefficient release: "V3.1" (default), "V3.1v2spec" (for OC-SMART), "V2", "V1"; or {correction: release} to mix them, e.g. {"smile": "V2"}. See docs/calibration.rst.

  • **kwargs – Passed to hypso.processing.l1a_to_l1b(): coeff_files (explicit files), radiometric, smile, destripe, spectral (False to skip a correction), and keystone (True to apply the sensor’s keystone model; unreviewed groundwork).

Returns:

L1B; the coefficients used and their checksums are recorded in provenance.

Return type:

Product

correct_atmosphere(method='machi', masked=False, mask_flags=None, work_dir=None, config=None, **options)[source]#

Atmospheric correction to L2A.

Parameters:
  • method ({"machi", "dps", "polymer", "acolite", "ocsmart"}, default "machi") – MACHI or dark pixel subtraction (in this process), or an external tool.

  • masked (bool, default False) – Give the method NaN where pixel_flags are set.

  • mask_flags (list of str, optional) – Only these flags, with masked=True.

  • work_dir (str or path, optional) – External tools: where their input and raw output go (kept); default a temporary directory.

  • config (str, path or dict, optional) – External tools: the AC tool configuration (hypso.ac.config); default the HYPSO_AC_CONFIG environment variable.

  • **options – Method-specific options, e.g. est_min_R=0.05 for MACHI, settings={...} overriding the configuration for Polymer or ACOLITE, output="l2r" for ACOLITE.

Returns:

L2A: the method’s reflectance on this product’s bands, its 2D products and flags in variables.

Return type:

Product

derive(group, algorithm=None)[source]#

An L2B product from one of the package’s algorithms (from L2A).

Parameters:
  • group (str) – "BGC" (chlorophyll-a, suspended matter) or "IOP" (absorption, backscattering, Kd).

  • algorithm (str, optional) – BGC: "oci" (default; NASA’s chlor_a, CI and OC4 blend), "oc4", "ci", "ndci" (turbid/eutrophic waters), "nechad2010" (suspended matter); IOP: "qaa" (default). See hypso.processing.l2b_algorithms.

Returns:

Level L2B, e.g. ...L2B.BGC.oci.nc.

Return type:

Product

Examples

>>> chl = l2a.derive("BGC")                 # from an L2A.RRS product
>>> chl.variables["chlor_a"]
>>> tsm = l2a.derive("BGC", "nechad2010")
filename(label=None, ac=None)[source]#

The product’s file name (hypso.io.naming).

Parameters:
  • label (str, optional) – Free-text label for experiments, the last name field.

  • ac (str, optional) – Override the atmospheric correction field (L2A) or source (L2B).

Returns:

e.g. "HYPSO2_HSI.20250304T103805.aeronetvenice.L1C.nc"; L2A names carry the quantity (from the product variable) and the method, e.g. "...L2A.RHOS.machi.nc"; L2B names the group and source, e.g. "...L2B.BGC.oc4.nc".

Return type:

str

footprint(mask=None, step=10, block=8)[source]#

The ground footprint as a shapely polygon in WGS84 longitude/latitude.

See hypso.maps.footprint() (mask="data" for the pixels with data only).

Parameters:
georeference(latitudes=None, longitudes=None, direct=True)[source]#

Georeference an L1B: latitude, longitude and sun and sensor angles.

Parameters:
  • latitudes (array_like or path, optional) – Indirect (GCP-corrected) pixel coordinates, as arrays or paths to raw float32 files. Omit both to use direct georeferencing.

  • longitudes (array_like or path, optional) – Indirect (GCP-corrected) pixel coordinates, as arrays or paths to raw float32 files. Omit both to use direct georeferencing.

  • direct (bool, default True) – Also compute direct georeferencing from the ADCS telemetry (*_direct variables).

Return type:

Product

intermediates()[source]#

The AC tool’s other per-band outputs as an L2A.AUX product.

OC-SMART’s Lt, Lr, Lrc, Lwp, tg_sol and tg_sen (one 2D variable per quantity and band, Lt_434), with the L2A’s geometry and flags. write() writes them as ...L2A.AUX.<method>.nc next to the L2A; the L2A file does not hold them.

Returns:

None when the method returned none (in-process methods, Polymer, ACOLITE).

Return type:

Product or None

classmethod open(path, wavelength_range=None, wavelengths=None, indices=None)[source]#

Read a product file of any level and any supported layout.

Parameters:
  • path (str or pathlib.Path) – A current-format, older grouped or ground-station L1A file.

  • wavelength_range (optional) – Read only some bands (as select_bands()); only those are read from the file. Not for L1A.

  • wavelengths (optional) – Read only some bands (as select_bands()); only those are read from the file. Not for L1A.

  • indices (optional) – Read only some bands (as select_bands()); only those are read from the file. Not for L1A.

Return type:

Product

pixel(latitude, longitude, direct=False)[source]#

The pixel nearest to a location.

Parameters:
  • latitude (float) – Location in degrees.

  • longitude (float) – Location in degrees.

  • direct (bool, default False) – Use the direct (ADCS-only) georeferencing instead.

Returns:

(line, sample), or (y, x) for a gridded product.

Return type:

tuple of int

regrid(target='utm', resolution=None, method='nearest', radius_of_influence=None, max_gb=4.0)[source]#

The product on a map grid, at the same level.

Parameters:
  • target (str, int, pyproj.CRS, AreaDefinition or Product, default "utm") – "utm" (the WGS84 UTM zone of the scene centre), any CRS pyproj accepts (e.g. "EPSG:3035"), a pyresample AreaDefinition, or a gridded Product to share its grid.

  • resolution (float, optional) – Pixel size in the CRS’s units. Default: this product’s resolution, so nothing is oversampled. Not with an AreaDefinition or Product target.

  • method ({"nearest", "bilinear", "average"}, default "nearest") – "nearest" keeps one measured spectrum per pixel; "bilinear" blends neighbouring spectra; "average" takes cell means, for grids at least as coarse as the product.

  • radius_of_influence (float, optional) – Search radius in m; default 1.5 times the coarser pixel size.

  • max_gb (float, default 4.0) – Refuse grids whose cube would be larger.

Returns:

Dimensions (y, x) with CF projection coordinates and a crs grid mapping; pixel_flags gains outside_swath.

Return type:

Product

See also

hypso.grid.regrid

The tree function, with the per-variable rules.

resample(target, method='nearest', radius_of_influence=None)[source]#

Resample the product onto any target, as a bare Dataset.

Parameters:
  • target (pyresample.geometry.AreaDefinition or SwathDefinition) – A grid, or a swath such as another sensor’s (for matchups).

  • method ({"nearest", "bilinear", "average"}, default "nearest") – For the cube and float variables; "average" only onto grids coarser than the product. Flags are combined as in hypso.grid.GridOperators.

  • radius_of_influence (float, optional) – Search radius in m; default 1.5 times the coarser pixel size.

Returns:

The cube, derived variables, each flag as flag_<name> and the target’s latitude and longitude.

Return type:

xarray.Dataset

See also

regrid

The product on a map grid, as a Product.

select_bands(wavelength_range=None, wavelengths=None, indices=None)[source]#

A new Product with only some of the bands (from L1B on).

Parameters:
  • wavelength_range (tuple of float, optional) – (min, max) in nm: the bands whose centre lies within it.

  • wavelengths (array_like, optional) – Wavelengths in nm: the nearest band to each.

  • indices (array_like of int, optional) – Band indices in the sensor’s full band set (band_index).

Returns:

Each band keeps its full-set index, so later steps (TOA reflectance, SRFs) give the same values as on all bands.

Return type:

Product

Raises:

ValueError – On L1A: calibration needs every band.

Examples

>>> vis = l1b.select_bands(wavelength_range=(450, 700))
spectrum(latitude=None, longitude=None, line=None, sample=None)[source]#

The cube’s spectrum at one pixel.

Parameters:
  • latitude (float, optional) – Location in degrees; the nearest pixel is used.

  • longitude (float, optional) – Location in degrees; the nearest pixel is used.

  • line (int, optional) – Pixel indices, instead of a location.

  • sample (int, optional) – Pixel indices, instead of a location.

Returns:

Values over bands, with wavelength coordinates.

Return type:

xarray.DataArray

See also

window

Statistics of a window of pixels around a location.

swath_definition(direct=False)[source]#

The product’s geolocation as a pyresample.geometry.SwathDefinition.

Parameters:

direct (bool, default False) – Use the direct georeferencing instead.

to(level, calibrate=None, georeference=None, toa_reflectance=None, correct_atmosphere=None)[source]#

Run the processing steps from this level up to level.

Parameters:
  • level ({"L1B", "L1C", "L2A"}) – Target level. L1B means georeferenced: an L1B without geolocation is georeferenced first.

  • calibrate (dict, optional) – Options for each step, passed to the method of that name. For L2A, correct_atmosphere={"method": ...} picks the method (default MACHI). georeference=False, for L1B only, skips georeferencing (with a warning).

  • georeference (dict, optional) – Options for each step, passed to the method of that name. For L2A, correct_atmosphere={"method": ...} picks the method (default MACHI). georeference=False, for L1B only, skips georeferencing (with a warning).

  • toa_reflectance (dict, optional) – Options for each step, passed to the method of that name. For L2A, correct_atmosphere={"method": ...} picks the method (default MACHI). georeference=False, for L1B only, skips georeferencing (with a warning).

  • correct_atmosphere (dict, optional) – Options for each step, passed to the method of that name. For L2A, correct_atmosphere={"method": ...} picks the method (default MACHI). georeference=False, for L1B only, skips georeferencing (with a warning).

Return type:

Product

Examples

>>> l1c = l1a.to("L1C", calibrate={"version": "V2"},
...              georeference={"latitudes": lats, "longitudes": lons})
>>> l2a = l1c.to("L2A")                                        # MACHI
>>> l2a = l1c.to("L2A", correct_atmosphere={"method": "dps"})
to_satpy(direct=False)[source]#

The product as a Satpy Scene, one dataset per band.

Parameters:

direct (bool, default False) – Use the direct georeferencing for the swath.

toa_reflectance(use_direct_georef=False, ssi_source='tsis', use_unbinned=True)[source]#

Convert georeferenced L1B radiance to L1C top-of-atmosphere reflectance rhot.

Parameters:
  • use_direct_georef (bool, default False) – Use the direct georeferencing’s solar zenith angle.

  • ssi_source ({"tsis", "thuillier"}, default "tsis") – Solar irradiance spectrum: TSIS-1 HSRS or Thuillier (2002).

  • use_unbinned (bool, default True) – Build the spectral response functions from the unbinned bands.

Returns:

L1C, with the spectral response functions in metadata/srf.

Return type:

Product

tool_products()[source]#

The AC tool’s own geophysical products as L2B products.

Polymer’s chla, ACOLITE’s chl_*/SPM_*, OC-SMART’s chlor_a_*/tsm_*, … grouped by hypso.io.naming.L2B_GROUPS, each with the tool’s flags. An L2A file does not keep them: write() writes them as L2B files (...L2B.BGC.polymer.nc) next to it.

Returns:

{group: Product}, e.g. {"BGC": ..., "IOP": ...}; empty for in-process methods (MACHI, DPS).

Return type:

dict

window(latitude, longitude, size=3, exclude_flags=None, cv_band_range=(405.0, 570.0))[source]#

A window of pixels around a location and its statistics, for matchups.

Parameters:
  • latitude (float) – Location in degrees; the window is centred on the nearest pixel.

  • longitude (float) – Location in degrees; the window is centred on the nearest pixel.

  • size (int, default 3) – Window width in pixels (odd). Clipped at the image edges.

  • exclude_flags (list of str, optional) – pixel_flags names (e.g. ["land", "cloud"]) whose pixels are left out.

  • cv_band_range (tuple of float, default (405, 570)) – Wavelength range (nm) for pixel_valid and cv_median.

Returns:

Per band: mean, median, std, cv (std / median) and valid_count; pixels (the window) and excluded. Attributes: centre pixel and its distance to the location, box_size, pixel_valid and percent_valid (pixels with any finite band in cv_band_range), cv_median and the window’s mean angles. See hypso.window.

Return type:

xarray.Dataset

with_masks(descriptions=None, **masks)[source]#

A new Product with masks added to pixel_flags.

Parameters:
  • descriptions (dict, optional) – {name: text} describing masks, kept in the file.

  • **masks (array_like of bool) – name=mask with the product’s spatial shape, True where flagged. Names may contain letters, digits and _.

Returns:

Existing flags are kept; a mask with an existing name replaces it.

Return type:

Product

Examples

>>> flagged = l1c.with_masks(land=land, cloud=cloud)
with_variables(**variables)[source]#

A new Product with derived 2D variables added.

Parameters:

**variables (array_like or xarray.DataArray) – name=values with the product’s spatial shape; a DataArray’s attributes (e.g. units) are kept. Written with the product and read back by hypso.open().

Return type:

Product

Examples

>>> l2a.with_variables(chla=xr.DataArray(chla, attrs={"units": "mg m-3"}))
write(path=None, out_dir=None, label=None, datacube=False, significant_bits=14, tool_products=True, intermediates=True)[source]#

Write the product in the current file format.

Parameters:
  • path (str or path, optional) – Output file. Default: filename() in out_dir.

  • out_dir (str or path, optional) – Directory for the default name; the current directory if omitted.

  • label (str, optional) – Label for the default name.

  • datacube (bool, default False) – Write the cube as one 3D variable instead of one per band.

  • significant_bits (int or None, default 14) – Keep this many significant mantissa bits of the float bands (L1B-L2A): about 40% smaller L1C bands at most 3.1e-5 relative error; None writes them lossless.

  • tool_products (bool, default True) – L2A: also write the AC tool’s own products (tool_products()) as L2B files in the same directory. The L2A file never holds them; False drops them (with a warning).

  • intermediates (bool, default True) – L2A: also write the AC tool’s other per-band outputs (intermediates(), e.g. OC-SMART’s Lt, Lr, Lrc, tg_sol) as the ...L2A.AUX.<method>.nc file in the same directory. False drops them (with a warning).

Returns:

The written file (for L2A, the L2A file).

Return type:

pathlib.Path

write_footprint(path, mask=None, step=10, block=8)[source]#

Write the footprint, with the capture’s metadata, as an ESRI Shapefile (*.shp, EPSG:4326) or GeoJSON.

See hypso.maps.write_footprints(), which also writes several products to one file.

Parameters:
property atmospheric_correction#

Atmospheric correction method of an L2A product, e.g. "polymer"; None below L2A.

property cube: xarray.DataArray#

dn, Lt, rhot or the L2A variable.

Dimensions (lines, samples, bands), or (y, x, bands) when gridded, with wavelength, radiation_wavelength and fwhm band coordinates. L2B products have none (ValueError); their products are variables.

Type:

The product cube

Return type:

xarray.DataArray

property flags: dict#

{name: boolean DataArray}.

Empty if the product has no flags.

Type:

Masks decoded from pixel_flags

Return type:

dict

property geometry: xarray.Dataset#

Latitude, longitude and sun and sensor angles, as a Dataset.

Empty before georeferencing (L1A, a calibrated L1B). Includes the *_direct variants when direct georeferencing was computed.

Return type:

xarray.Dataset

property grid#

Name of the map grid (e.g. "utm33n_876m"), or None in sensor geometry.

See regrid().

property is_georeferenced: bool#

Whether the product has geolocation (an L1B only after georeference()).

Return type:

bool

property level: str#

"L1A", "L1B", "L1C", "L2A" or "L2B".

Type:

Processing level

Return type:

str

property provenance: list#

one dict per processing step, oldest first.

From metadata/processing: step name, date, software version and git commit, input file and the step’s parameters.

Type:

How the product was made

Return type:

list

property resolution: float#

the larger of the mean along- and across-track ground sampling distance, in m.

For a gridded product, the grid’s pixel size in its CRS’s units (m, or degrees for a geographic grid).

Type:

Pixel size

Return type:

float

property sat_id: str#

Satellite, e.g. "HYPSO-2".

Return type:

str

property shape: tuple#

(lines, samples), or (y, x) when gridded.

Type:

Spatial shape

Return type:

tuple

property target: str#

Capture target name, e.g. "aeronetvenice".

Return type:

str

property tree: xarray.DataTree#

The underlying product tree, as an xarray.DataTree.

A shallow copy: adding, replacing or removing variables and attributes does not change this Product, but the arrays are shared (copying the cube on every access would double memory), so do not modify array values in place - assign a new array instead.

Return type:

xarray.DataTree

property variables: xarray.Dataset#

Derived 2D products, as a Dataset.

Those added with with_variables() and those an atmospheric correction tool returns (e.g. chla, polymer_flags); for an L2B product, its products (e.g. chlor_a).

Return type:

xarray.Dataset

property wavelengths: numpy.ndarray#

Band centre wavelengths in nm, as calibrated (radiation_wavelength).

Return type:

numpy.ndarray

hypso.get_hypso1_wavelengths(aoi_x=428, column_count=1080, bin_factor=9)[source]#

Nominal HYPSO-1 band-centre wavelengths (nm) for an AOI and binning.

hypso.get_hypso2_wavelengths(aoi_x=428, column_count=1080, bin_factor=9)[source]#

Nominal HYPSO-2 band-centre wavelengths (nm) for an AOI and binning.

hypso.open(path, wavelength_range=None, wavelengths=None, indices=None)[source]#

Read a HYPSO product file.

Parameters:
Return type:

Product

Examples

>>> import hypso
>>> l1c = hypso.open("HYPSO2_HSI.20250304T103805.aeronetvenice.L1C.nc")
hypso.read_product(path, wavelength_range=None, wavelengths=None, indices=None)[source]#

Read any supported HYPSO product file into the in-memory model.

Parameters:
  • path (str or pathlib.Path)

  • wavelength_range (optional) – Read only some bands, selected as in hypso.processing.bands.select_bands() (at most one of them). Only the selected band variables are read from the file; a file holding the cube as one variable is read whole and then subset.

  • wavelengths (optional) – Read only some bands, selected as in hypso.processing.bands.select_bands() (at most one of them). Only the selected band variables are read from the file; a file holding the cube as one variable is read whole and then subset.

  • indices (optional) – Read only some bands, selected as in hypso.processing.bands.select_bands() (at most one of them). Only the selected band variables are read from the file; a file holding the cube as one variable is read whole and then subset.

Returns:

See the module description. tree.encoding["source"] holds the path (not written back).

Return type:

xarray.DataTree

Raises:

ValueError – If no product cube or processing level is found, or the file uses the levels from before format 3.0.

hypso.write_product(tree, path, datacube=False, significant_bits=SIGNIFICANT_BITS)[source]#

Write a product tree in the current file format.

Parameters:
  • tree (xarray.DataTree) – In-memory model (see the module description).

  • path (str or pathlib.Path)

  • datacube (bool, default False) – Write the cube as one 3D variable instead of one variable per band.

  • significant_bits (int or None, default 14) – Keep this many significant mantissa bits of the float band variables (L1B-L2A; netCDF BitRound, max relative error 2**-(bits + 1); values stay float32, NaN is kept, readers need nothing special). None writes them lossless. L1A counts, geometry, derived variables and metadata are always lossless. Recorded in the band_quantization global attribute.

Return type:

None