Skip to content

Plume operators (geo)

Plume post-processing on GeoArrays, behind the [geo] extra (pip install 'plumax[geo]'): the ten operators ported from geotoolz's plume module, as pipekit_ops.Operators built with geoops's public carrier helpers (the pattern of radtrax's [geo] operators). Importing plumax.geo does not need the extra; the operators load on first use, and a missing extra raises an ImportError naming it.

geo

Plume operators on GeoArrays, behind the [geo] extra.

  • :mod:plumax.geo.plume: the ten plume operators ported from geotoolz's plume module (#134): masks, contours, footprints, shape filters, column statistics and QND features, wind cones, the integrated mass enhancement, the cross-sectional flux and column-unit conversion.
  • :mod:plumax.geo.plume_array: the array functions under them (plume_mask, wind_advection_cone, convert_column_units, ...).
  • :mod:plumax.geo.starts: the starting values of an image fit, the direction from the source to the mask's centroid (plume_direction) and a grid of source positions (source_offset_grid) for a multistart solve.
  • :mod:plumax.geo.transects: cross-plume transects of a column image (cross_plume_transects, CrossPlumeProfile), each one's line density, centre and width, the smoothed centreline and the width law.
  • :mod:plumax.geo.vetting: PlumeVetting, :mod:plumax.vetting's candidate vetting and scene null on GeoArrays, as one Dataset (#157).

Importing this subpackage does not need the extra; the operators load on first use, and a missing extra raises an ImportError naming it.

plume: the operators

The plume operators on GeoArrays (behind the [geo] extra).

Ten operators ported from geotoolz's plume module (#134) with their behaviour unchanged; its eleventh, SBMP, moved to radtrax as radtrax.geo.MBMP. They wrap the array functions in :mod:plumax.geo.plume_array and are pipekit Operators built with geoops's public carrier helpers, as radtrax's [geo] operators are.

Per-pixel operators accept a geoarray.GeoArray or a plain np.ndarray and return the same carrier kind; geo-dependent operators (advection geometry, pixel-area maths, footprints) require a georeferenced GeoArray and raise TypeError otherwise. The area and distance operators (PlumeFootprint, WindAdvectionCone, IMEEstimate, CrossSectionalFlux) work in metres and raise ValueError on a geographic CRS (see :func:geoops.carrier.require_projected_crs). Vector outputs are geopandas.GeoDataFrame. Algorithms follow the literature cited in :mod:plumax.geo.plume_array:

  • PlumeMask / PlumeContours / PlumeFootprint: Frankenberg et al. (2016) detection and segmentation conventions.
  • IMEEstimate: Varon et al. (2018) integrated mass enhancement.
  • CrossSectionalFlux: Krings et al. (2011) / Varon (2018) appendix.
  • PlumeShapeFilter / PlumeColumnStats / PlumeQNDFeatures: Pérez Carrasco et al. (2026), the false-plume classifier's features.

The IME and cross-section operators expect the enhancement carrier to be in kg/m^2. Use :class:ColumnToMass to convert from ppm m or mol/m^2.

Nodata: pixels that are non-finite or equal the carrier's fill_value (see :func:geoops.carrier.valid_pixels) never enter a threshold, statistic or sum, and are never part of a plume mask or contour. Output fill values follow the output's meaning, not the input's: boolean masks declare fill_value=False, float products (scores, converted columns) hold NaN at nodata pixels and declare fill_value=NaN, and label images use 0 (see :class:PlumeContours for its one documented exception).

PlumeMask

PlumeMask(*, threshold: ThresholdMode = 'otsu', min_area_px: int = 50, connectivity: Connectivity = 8, nbins: int = 256)

Bases: Operator

Binary plume mask from a single-band score or enhancement map.

Thresholds the input (absolute number, Otsu, or percentile) and drops connected components smaller than min_area_px pixels — the Frankenberg et al. (2016) detection convention, also used by Varon et al. (2018, 2021) for S2/AVIRIS plume identification.

Parameters:

Name Type Description Default
threshold ThresholdMode

float (absolute), "otsu", or "percentile:<p>" with p in [0, 100].

'otsu'
min_area_px int

Minimum component size in pixels.

50
connectivity Connectivity

4 or 8 connectivity for component labelling.

8
nbins int

Histogram bins for the "otsu" threshold (see :func:geoops.segment.otsu_threshold); ignored by the other modes. Default 256.

256

Nodata pixels (non-finite or equal to the input's fill value) are excluded from the Otsu / percentile threshold and are always False in the mask, which declares fill_value=False.

Examples:

>>> mask = PlumeMask(
...     threshold="percentile:99.5", min_area_px=50,
... )(enhancement)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    threshold: ThresholdMode = "otsu",
    min_area_px: int = 50,
    connectivity: Connectivity = 8,
    nbins: int = 256,
) -> None:
    self.threshold = threshold
    self.min_area_px = min_area_px
    self.connectivity = connectivity
    self.nbins = nbins

PlumeContours

PlumeContours(*, min_area_px: int = 50, return_labels: bool = True, connectivity: Connectivity = 8)

Bases: Operator

Connected-component labelling of a plume mask.

Returns either an int32 label image (default) or a boolean mask of the retained components. Component size threshold and connectivity follow :func:label_components.

Nodata pixels (non-finite -- e.g. a NaN score -- or equal to the input's fill value) are never part of a contour. In the boolean output they are False (fill_value=False). In the label image they hold the input's fill value when it is a non-positive int32 value (e.g. -9999, so it cannot collide with a label); otherwise (NaN, no fill, or a positive fill) they are 0 (background), and a GeoArray output then carries fill_value=0.

Examples:

>>> labels = PlumeContours(min_area_px=50)(mask)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    min_area_px: int = 50,
    return_labels: bool = True,
    connectivity: Connectivity = 8,
) -> None:
    self.min_area_px = min_area_px
    self.return_labels = return_labels
    self.connectivity = connectivity

PlumeFootprint

PlumeFootprint(*, min_area_m2: float = 500.0, simplify_tolerance: float | None = 15.0, properties: Sequence[str] | None = None, extra_properties: Sequence[Callable[..., Any]] | None = None)

Bases: Operator

Vectorize a plume mask into polygons with per-plume metadata.

The region properties come from the same machinery as :class:geoops.measure.RegionProps (defaults to :data:geoops.measure.DEFAULT_REGIONPROPS, pixel units) and the polygons from :func:georeader.vectorize.get_polygons. Returns a GeoDataFrame with one row per surviving plume: geometry, area_m2, centroid, mean_enhancement / max_enhancement (if enhancement is supplied), n_pixels, label_id, and skimage region properties such as major_axis_length, orientation, eccentricity, solidity, perimeter, bbox-*, and inertia_tensor_eigvals-*.

Nodata pixels never form a polygon (of a boolean mask, or of a label image whose fill is positive, such as a uint8 raster's 255), non-positive labels are background, and nodata enhancement pixels are ignored by the per-polygon statistics.

Geo-dependent: polygonisation needs the carrier's transform and CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError). Areas are in m^2 and the simplify tolerance in m, so the CRS must be projected with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Parameters:

Name Type Description Default
min_area_m2 float

Drop polygons smaller than this area (m^2).

500.0
simplify_tolerance float | None

Douglas-Peucker tolerance (m) for polygon simplification; None to skip.

15.0
properties Sequence[str] | None

Region properties forwarded to regionprops_table.

None
extra_properties Sequence[Callable[..., Any]] | None

User-defined regionprops_table callables.

None

Called as op(mask, enhancement=None). The optional enhancement carrier must sit on the mask's pixel grid (ValueError otherwise); it enables the mean_enhancement / max_enhancement statistics per polygon.

Examples:

>>> gdf = PlumeFootprint(min_area_m2=500.0)(mask, kg_m2)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    min_area_m2: float = 500.0,
    simplify_tolerance: float | None = 15.0,
    properties: Sequence[str] | None = None,
    extra_properties: Sequence[Callable[..., Any]] | None = None,
) -> None:
    self.min_area_m2 = min_area_m2
    self.simplify_tolerance = simplify_tolerance
    self.properties = tuple(
        DEFAULT_REGIONPROPS if properties is None else properties
    )
    self.extra_properties = (
        None
        if extra_properties is None
        else tuple(
            reject_config_summary(extra_property, "extra_properties")
            for extra_property in extra_properties
        )
    )

PlumeShapeFilter

PlumeShapeFilter(*, min_area_px: int = 50, min_fiber_to_major_ratio: float = 1.0, max_fiber_to_major_ratio: float = 10.0, min_fiber_width: float = 1.0, max_fiber_width: float = 100.0)

Bases: Operator

Drop instance labels that fail a fiber-shape morphology gate.

Adapted from Pérez Carrasco et al. (2026), physical_constraints. apply_physical_constraints — a post-Mask R-CNN gate that distinguishes elongated plume features from compact false positives. Per instance:

  1. area = mask.sum(); drop when below min_area_px.
  2. fiber_length = longest Euclidean path through the skeleton, in pixel widths (diagonal steps count sqrt(2); see :func:geoops.measure.skeleton_length).
  3. major_axis = regionprops.axis_major_length — the PCA-based major axis of the equivalent ellipse. The original paper uses cv2.minAreaRect (rotated minimum-area rectangle), avoided here to keep the optional-dependency surface unchanged; the two measures agree closely for typical plume morphologies.
  4. fiber_width = area / fiber_length.
  5. Keep iff min_fiber_to_major_ratio <= fiber_length / major_axis <= max_fiber_to_major_ratio AND min_fiber_width <= fiber_width <= max_fiber_width.

Surviving instances keep their original integer labels; rejected instances are mapped to background (0).

Parameters:

Name Type Description Default
min_area_px int

Minimum pixel count to consider an instance.

50
min_fiber_to_major_ratio float

Lower bound on fiber/major.

1.0
max_fiber_to_major_ratio float

Upper bound on fiber/major.

10.0
min_fiber_width float

Lower bound on area / fiber_length.

1.0
max_fiber_width float

Upper bound on area / fiber_length.

100.0
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    min_area_px: int = 50,
    min_fiber_to_major_ratio: float = 1.0,
    max_fiber_to_major_ratio: float = 10.0,
    min_fiber_width: float = 1.0,
    max_fiber_width: float = 100.0,
) -> None:
    require_positive("min_area_px", min_area_px, allow_zero=True)
    if min_fiber_to_major_ratio < 0 or max_fiber_to_major_ratio <= 0:
        raise ValueError("fiber-to-major ratio bounds must be non-negative")
    if min_fiber_to_major_ratio > max_fiber_to_major_ratio:
        raise ValueError("min_fiber_to_major_ratio must be <= max")
    if min_fiber_width < 0 or max_fiber_width <= 0:
        raise ValueError("fiber width bounds must be non-negative")
    if min_fiber_width > max_fiber_width:
        raise ValueError("min_fiber_width must be <= max")
    self.min_area_px = int(min_area_px)
    self.min_fiber_to_major_ratio = float(min_fiber_to_major_ratio)
    self.max_fiber_to_major_ratio = float(max_fiber_to_major_ratio)
    self.min_fiber_width = float(min_fiber_width)
    self.max_fiber_width = float(max_fiber_width)

PlumeColumnStats

Bases: Operator

Per-instance in-mask vs background statistics of a column field.

Adapted from Pérez Carrasco et al. (2026), rfc_utils.xch4_metrics. For every non-zero label in the input map, returns a row with the in-mask mean, the out-of-mask (background) mean / std, and three derived metrics used by the paper's Random-Forest false-plume classifier:

  • contrast = mean_plume / mean_background
  • z_score = (mean_plume - mean_background) / std_background
  • intensity_per_area = (sum_plume - mean_background * n_plume) / n_plume

Nodata column pixels (non-finite or equal to the column carrier's fill value) are left out of every statistic.

Called as op(labels, column): column is the column field (single-band GeoArray or plain array) on the label map's pixel grid (ValueError otherwise).

PlumeQNDFeatures

PlumeQNDFeatures(*, degree: int = 6, eps: float = 50.0, min_samples: int = 50, perc_threshold: float = 98.0)

Bases: Operator

Per-instance Quantile-Normality-Deviation features for plume QA.

Adapted from Pérez Carrasco et al. (2026) — the feature pipeline that feeds the Random-Forest false-plume classifier (rfc_utils.get_QND_df_cms / get_plume_info). For each non-zero label in the input map this operator emits one row containing:

  • qnd_column_* — polynomial coefficients of the Kolmogorov-Smirnov distance between the in-mask CDF of the column field and a Gaussian fit to the full scene's column distribution, sampled across 100 percentiles in [0.01, 0.99].
  • qnd_albedo_* — same construction over the optional albedo field.
  • n_clumps — DBSCAN cluster count of in-mask pixels above the perc_threshold percentile (per the paper's clump-count signal).
  • contrast / z_score / intensity_per_area — the same stats that :class:PlumeColumnStats emits, included so a single call assembles the full feature vector used by the paper.

Nodata column / albedo pixels (non-finite or equal to the carrier's fill value) are left out of every feature.

Called as op(labels, column, albedo=None): column is the column-enhancement carrier and albedo an optional albedo carrier, both on the label map's pixel grid (ValueError otherwise). Without albedo the qnd_albedo_* coefficients are NaN.

Parameters:

Name Type Description Default
degree int

Degree of the QND polynomial (paper default: 6).

6
eps float

DBSCAN eps (pixels).

50.0
min_samples int

DBSCAN min_samples.

50
perc_threshold float

Percentile (within the instance mask) above which pixels are eligible for clustering.

98.0
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    degree: int = 6,
    eps: float = 50.0,
    min_samples: int = 50,
    perc_threshold: float = 98.0,
) -> None:
    if degree < 1:
        raise ValueError("degree must be >= 1")
    require_positive("eps", eps)
    if min_samples < 1:
        raise ValueError("min_samples must be >= 1")
    if not 0.0 < perc_threshold < 100.0:
        raise ValueError("perc_threshold must be in (0, 100)")
    self.degree = int(degree)
    self.eps = float(eps)
    self.min_samples = int(min_samples)
    self.perc_threshold = float(perc_threshold)

WindAdvectionCone

WindAdvectionCone(*, source: Sequence[float], wind_u: float, wind_v: float, half_angle_deg: float = 30.0, max_distance: float = 5000.0, crs: str | None = None)

Bases: Operator

Mask likely downwind plume extent from a source and wind vector.

Rasterizes a circular sector centered at source, oriented along (wind_u, wind_v), with half-angle half_angle_deg and radius max_distance. The mask is useful as a prior for plume segmentation when the source location and wind are known (e.g. from a reanalysis product), following the practice of Varon et al. (2018, 2021).

Geo-dependent: the cone is rasterised in CRS coordinates via the carrier's transform, so the input must be a georeferenced GeoArray (plain arrays raise TypeError). max_distance is in metres and the cone angle is measured in the map plane, so the carrier CRS must be projected with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Parameters:

Name Type Description Default
source Sequence[float]

(x, y) source coordinates. If crs is supplied, source is interpreted in that CRS and reprojected to the carrier CRS (which must then be set); otherwise it is in carrier CRS coordinates (m).

required
wind_u float

Eastward wind component (m/s).

required
wind_v float

Northward wind component (m/s).

required
half_angle_deg float

Half-angle of the cone in degrees, in [0, 180]; 180 is the full disc (see :func:wind_advection_cone).

30.0
max_distance float

Radius of the cone (m).

5000.0
crs str | None

Optional CRS of source.

None

Examples:

>>> cone = WindAdvectionCone(
...     source=(x0, y0), wind_u=3.0, wind_v=1.0,
...     half_angle_deg=30.0, max_distance=5000.0,
... )(enhancement)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    source: Sequence[float],
    wind_u: float,
    wind_v: float,
    half_angle_deg: float = 30.0,
    max_distance: float = 5000.0,
    crs: str | None = None,
) -> None:
    self.source = as_tuple(source)
    self.wind_u = wind_u
    self.wind_v = wind_v
    self.half_angle_deg = half_angle_deg
    self.max_distance = max_distance
    self.crs = crs

IMEEstimate

IMEEstimate(*, wind_speed: float, length_method: Literal['max_axis', 'convex_hull', 'skeleton'] = 'max_axis', pixel_area_m2: float | None = None, return_uncertainty: bool = True, uncertainty_fraction: float = 0.5)

Bases: Operator

Integrated Mass Enhancement (IME) flux estimator.

Implements the IME method of Varon et al. (2018), AMT Quantifying methane point sources from fine-scale satellite observations of atmospheric methane plumes:

.. math::

\mathrm{IME} \;=\; \sum_{i \in \mathrm{plume}}
                    \Omega_i \,\Delta A_i, \qquad
Q \;=\; \frac{U_{\mathrm{eff}}\,\mathrm{IME}}{L}

where :math:\Omega_i is the column enhancement (kg/m^2) of pixel :math:i, :math:\Delta A_i is its area (m^2), :math:L is the effective plume length (m) — see :func:plume_length — and :math:U_{\mathrm{eff}} is the effective wind speed (m/s). Varon et al. (2018) calibrate :math:U_{\mathrm{eff}} against LES simulations; this operator takes the calibrated value as wind_speed.

The enhancement carrier MUST be in kg/m^2. Use :class:ColumnToMass upstream to convert from ppm m or mol/m^2: passing other units silently produces nonsense. Nodata enhancement pixels (non-finite or equal to the fill value) add nothing to the IME.

Geo-dependent: pixel area (m^2) and plume length (m) are derived from the carrier's transform, so the input must be a georeferenced GeoArray (plain arrays raise TypeError) in a projected CRS with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Called as op(enhancement, plume_mask): plume_mask is a boolean carrier selecting plume pixels on the enhancement's pixel grid (same shape, transform and CRS; ValueError otherwise -- a mask on another grid would be indexed against the wrong pixels).

Parameters:

Name Type Description Default
wind_speed float

Effective wind speed :math:U_{\mathrm{eff}} in m/s.

required
length_method Literal['max_axis', 'convex_hull', 'skeleton']

Length estimator: "max_axis", "convex_hull", or "skeleton". See :func:plume_length; "skeleton" raises ValueError for compact plumes whose skeleton collapses to a point.

'max_axis'
pixel_area_m2 float | None

Override the pixel area (m^2); default is the absolute input transform determinant in the projected CRS's metres (exact on an equal-area projection; on UTM it ignores the projection's scale factor, a < 0.1 % error near the central meridian).

None
return_uncertainty bool

Append emission_rate_uncertainty_kg_s.

True
uncertainty_fraction float

Fractional 1-sigma uncertainty on Q. The default 0.5 follows Varon et al. (2018) Table 3.

0.5

The call returns a dict with keys ime_kg, length_m, wind_speed_m_s, emission_rate_kg_s, and optionally emission_rate_uncertainty_kg_s.

Examples:

Estimate Q in kg/s from a ppm m enhancement map::

from plumax.geo import ColumnToMass, IMEEstimate, PlumeMask

kg_m2 = ColumnToMass(units_in="ppm_m")(enhancement)
mask = PlumeMask(threshold="percentile:99")(kg_m2)
result = IMEEstimate(
    wind_speed=3.5,
    length_method="convex_hull",
)(kg_m2, mask)
print(result["emission_rate_kg_s"])
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    wind_speed: float,
    length_method: Literal["max_axis", "convex_hull", "skeleton"] = "max_axis",
    pixel_area_m2: float | None = None,
    return_uncertainty: bool = True,
    uncertainty_fraction: float = 0.5,
) -> None:
    self.wind_speed = wind_speed
    self.length_method = length_method
    self.pixel_area_m2 = pixel_area_m2
    self.return_uncertainty = return_uncertainty
    require_positive("uncertainty_fraction", uncertainty_fraction, allow_zero=True)
    self.uncertainty_fraction = uncertainty_fraction

CrossSectionalFlux

CrossSectionalFlux(*, source: Sequence[float], wind_u: float, wind_v: float, n_transects: int = 5, transect_spacing_m: float = 100.0)

Bases: Operator

Estimate cross-sectional flux at downwind transects.

For each transect :math:\Gamma_k across the wind at downwind distance :math:d_k, the operator integrates the column mass carried through it:

.. math::

Q_k \;=\; \int_{\Gamma_k} \gamma(\Omega) \,
             (\mathbf{u} \cdot \mathbf{n}) \, d\ell
    \;\approx\; \sum_{q} \Delta s_q \, \gamma(\Omega)_q
             \, (\mathbf{u} \cdot \mathbf{n}_q)

where :math:\gamma is the trace (:func:functax.transfer.trace_plan), which reads the column by bilinear interpolation at the midpoint nodes of a line rule along :math:\Gamma_k, at least 400 and at most a quarter of a pixel apart, and the sum is integrix's rule sum. Reading the column on the line, rather than summing a strip of pixels, keeps the flux unbiased when the wind is oblique to the pixel grid. This is the cross-section method of Krings et al. (2011) and Varon et al. (2018, appendix); a flat downwind profile of :math:Q_k versus :math:d_k confirms a steady-state estimate.

The enhancement carrier MUST be in kg/m^2 (see :class:ColumnToMass). Pixels outside the plume mask and nodata enhancement pixels (non-finite or equal to the fill value) are read as zero, so they add nothing to a transect's flux. The scene ends at its pixels' outer edges, where the edge pixels are read as they are, and nodes beyond it read zero. Each transect spans the across-wind offsets of the plume pixels whose bilinear hat reaches it, plus that hat's reach along the transect, :math:|a e_x + d e_y| + |b e_x + e e_y| for the transform's steps and the transect's direction :math:e, so the column of the edge pixels is counted in full. Arc lengths, normals and that reach come from the transform, so the flux holds for oblique winds and for pixels that are not square.

Geo-dependent: transect placement and pixel size come from the carrier's transform and CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError) in a projected CRS with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Called as op(enhancement, plume_mask): plume_mask is a boolean plume carrier on the enhancement's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
source Sequence[float]

(x, y) source coordinates in the carrier CRS (m).

required
wind_u float

Eastward wind component (m/s).

required
wind_v float

Northward wind component (m/s).

required
n_transects int

Number of downwind transects to evaluate.

5
transect_spacing_m float

Along-wind distance between transects (m).

100.0

The call returns a geopandas.GeoDataFrame with one row per transect: geometry (the across-wind LineString the flux is integrated over), transect_id, distance_m, flux_kg_s, n_pixels (the plume pixels that the transect's trace reads).

Examples:

Evaluate fluxes at 100 m, 200 m, 300 m downwind::

gdf = CrossSectionalFlux(
    source=(x0, y0),
    wind_u=3.0, wind_v=1.0,
    n_transects=3, transect_spacing_m=100.0,
)(kg_m2, mask)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    source: Sequence[float],
    wind_u: float,
    wind_v: float,
    n_transects: int = 5,
    transect_spacing_m: float = 100.0,
) -> None:
    self.source = as_tuple(source)
    self.wind_u = wind_u
    self.wind_v = wind_v
    self.n_transects = n_transects
    self.transect_spacing_m = transect_spacing_m

ColumnToMass

ColumnToMass(*, gas: str = 'CH4', units_in: ColumnUnit = 'ppm_m', units_out: ColumnUnit = 'kg_m2', pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD)

Bases: Operator

Convert column enhancement units (ppm m / mol m^-2 / kg m^-2).

Thin wrapper over :func:convert_column_units. The ppm m conversion uses the ideal-gas air density at the layer's pressure and temperature, the ISA sea-level 101 325 Pa and 288.15 K unless the scene's are given; see that function's docstring for the exact relation. Nodata pixels (non-finite or equal to the fill value) are not converted: they hold NaN and the output declares fill_value=NaN (a converted column is a new quantity, so the input's fill -- e.g. -9999 ppm m -- is not carried over).

Parameters:

Name Type Description Default
gas str

"CH4" (default) or "CO2".

'CH4'
units_in ColumnUnit

Units of the input carrier.

'ppm_m'
units_out ColumnUnit

Desired output units.

'kg_m2'
pressure_pa float

Layer pressure p [Pa] for the ppm m conversion.

P_STANDARD
temperature_k float

Layer temperature T [K] for the ppm m conversion.

T_STANDARD

Examples:

>>> kg_m2 = ColumnToMass(
...     gas="CH4", units_in="ppm_m", units_out="kg_m2",
... )(enhancement)
Source code in src/plumax/geo/_src/plume.py
def __init__(
    self,
    *,
    gas: str = "CH4",
    units_in: ColumnUnit = "ppm_m",
    units_out: ColumnUnit = "kg_m2",
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
) -> None:
    self.gas = gas
    self.units_in = units_in
    self.units_out = units_out
    self.pressure_pa = pressure_pa
    self.temperature_k = temperature_k

vetting: plume vetting on carriers

PlumeVetting runs plume vetting (vet_candidate and the scene null) on every candidate of a scene and returns the scores as one xarray.Dataset; the decision rule is left to the caller.

Plume vetting on GeoArrays (behind the [geo] extra): one Dataset per scene.

PlumeVetting is the L2 operator over the array-level vetting in :mod:plumax.vetting (#157): it reads a radiance GeoArray, its matched-filter GeoArray and a stack of candidate masks, runs vet_candidate on each candidate and the scene null (null_masks, null_pvalue) beside it, and returns the scores as one xarray.Dataset. It returns scores, not a verdict: the decision rule is #158's.

PlumeVetting

PlumeVetting(*, window: AbsorptionWindow, table: Float[ArrayLike, 'D Bf'], delta_grid: Float[ArrayLike, ' D'], n_null: int = 100, key: Array | None = None, k: int = DEFAULT_K, keep: float = DEFAULT_KEEP, degree: int = DEFAULT_DEGREE, box: int = DEFAULT_BOX)

Bases: Operator

Vet every candidate of a scene and its scene null; scores as a Dataset.

Called as PlumeVetting(window=..., table=..., delta_grid=...)(cube, mf, masks). For each candidate M_c of masks, with every candidate kept out of the background pool,

(ΔX̂_c, D_norm,c) = vet_candidate(L, MF, M_c), and

p̂_c = null_pvalue(D_norm,c, {D_norm(M_s)}) over n_null copies M_s of M_c from null_masks, each vetted as M_c is; a copy that cannot be scored (radtrax's DegenerateInputError) scores NaN and null_pvalue leaves it out.

The cube is (B, H, W) with its band centres in nm in attrs["wavelengths"]; mf is (H, W) or (1, H, W) on the cube's pixel grid, in mol/m² (the units of window.mf_background_mol_m2). Nodata pixels of either carrier (non-finite, or equal to its fill_value) are dropped from every candidate and kept out of the pool and the null copies. The candidates' random draws split key in candidate order, so the same key gives the same p_null.

The Dataset has dims candidate (C) and band (the window's Bf fitting bands, coordinate wavelength_nm) and holds delta_x_mol_m2 (ΔX̂), d_norm, p_null (NaN when n_null = 0) and n_pairs per candidate; ratio (R), continuum (P(λ; ĉ)) and fit (P(λ; ĉ) E(λ; ΔX̂), the fitted ratio) per candidate and band; and attributes window (the window's fields as JSON) and key (the key's raw data).

Parameters:

Name Type Description Default
window AbsorptionWindow

The gas's AbsorptionWindow (radtrax.retrieval.absorption).

required
table Float[ArrayLike, 'D Bf']

E(λ; ΔX_d) on the window's fitting bands, (D, Bf), from radtrax's transmittance_table.

required
delta_grid Float[ArrayLike, ' D']

The columns ΔX_d of the table's rows [mol/m²], (D,), starting at 0.

required
n_null int

Number of null copies per candidate; 0 skips the null.

100
key Array | None

A jax.random key for the null copies; None uses jax.random.key(0).

None
k int

Number of seeds before growth (vet_candidate).

DEFAULT_K
keep float

Fraction of the pairs kept, in (0, 1].

DEFAULT_KEEP
degree int

The continuum's Legendre degree.

DEFAULT_DEGREE
box int

Margin, in pixels, around the seeds' bounding box that the pool is drawn from.

DEFAULT_BOX

Raises:

Type Description
ParameterError

If n_null is negative.

ShapeError

If the cube is not (B, H, W), has no attrs["wavelengths"] with B entries, table does not have one column per fitting band, or masks is not (C, H, W) on the cube's grid; and whatever vet_candidate raises on a candidate.

Examples:

A pipeline sketch, after radtrax's matched filter::

from plumax.geo import PlumeVetting

scores = PlumeVetting(
    window=window, table=table, delta_grid=delta_grid, n_null=100
)(
    cube, mf, masks
)
scores["d_norm"], scores["p_null"]
Source code in src/plumax/geo/_src/vetting.py
def __init__(
    self,
    *,
    window: AbsorptionWindow,
    table: Float[ArrayLike, "D Bf"],
    delta_grid: Float[ArrayLike, " D"],
    n_null: int = 100,
    key: Array | None = None,
    k: int = DEFAULT_K,
    keep: float = DEFAULT_KEEP,
    degree: int = DEFAULT_DEGREE,
    box: int = DEFAULT_BOX,
) -> None:
    require_positive(
        "n_null",
        n_null,
        caller="PlumeVetting",
        allow_zero=True,
        error=ParameterError,
    )
    self.window = window
    self.table = table
    self.delta_grid = delta_grid
    self.n_null = int(n_null)
    self.key = jax.random.key(0) if key is None else key
    self.k = k
    self.keep = keep
    self.degree = degree
    self.box = box

get_config

get_config() -> dict[str, Any]

The JSON-safe configuration, without the arrays (table, grid, key).

Source code in src/plumax/geo/_src/vetting.py
def get_config(self) -> dict[str, Any]:
    """The JSON-safe configuration, without the arrays (table, grid, key)."""
    return {
        "window": jsonable(dataclasses.asdict(self.window)),
        "n_null": self.n_null,
        "k": self.k,
        "keep": self.keep,
        "degree": self.degree,
        "box": self.box,
    }

from_config classmethod

from_config(config: dict[str, Any], *, table: Float[ArrayLike, 'D Bf'] | None = None, delta_grid: Float[ArrayLike, ' D'] | None = None, key: Array | None = None) -> PlumeVetting

Rebuild from get_config's output and the arrays it leaves out.

Raises:

Type Description
TypeError

If table or delta_grid is not given; the config holds neither.

Source code in src/plumax/geo/_src/vetting.py
@classmethod
def from_config(
    cls,
    config: dict[str, Any],
    *,
    table: Float[ArrayLike, "D Bf"] | None = None,
    delta_grid: Float[ArrayLike, " D"] | None = None,
    key: Array | None = None,
) -> PlumeVetting:
    """Rebuild from `get_config`'s output and the arrays it leaves out.

    Raises:
        TypeError: If ``table`` or ``delta_grid`` is not given; the
            config holds neither.
    """
    if table is None or delta_grid is None:
        raise TypeError(
            "PlumeVetting.from_config needs the table= and delta_grid= "
            "arrays, which get_config leaves out"
        )
    config = dict(config)
    window = dict(config.pop("window"))
    for name in ("fit_nm", "absorbing_nm"):
        window[name] = tuple(tuple(band) for band in window[name])
    return cls(
        window=AbsorptionWindow(**window),
        table=table,
        delta_grid=delta_grid,
        key=key,
        **config,
    )

starts: starting values of an image fit

The starting direction of a column-plume fit, from the source to the centroid of the plume mask, and the grid of source positions that solve_coupled_multistart starts from.

Starting values for a plume fit (implementation in plumax.geo._src.starts).

plume_direction

plume_direction(mask: Bool[ndarray, 'row col'], transform: Any, source: tuple[float, float], *, weights: Float[ndarray, 'row col'] | None = None) -> float

Direction from the source to the centroid of the mask.

φ₀ = atan2(s̄₂ − s₀₂, s̄₁ − s₀₁), with s̄ = ∑ₙ ωₙ sₙ / ∑ₙ ωₙ over the mask.

Algorithm
  1. Place every pixel centre sₙ in the CRS with the geotransform.
  2. Weight the mask pixels by ωₙ (1, or weights) and take the centroid s̄.
  3. Take the angle of s̄ − s₀.

With the enhancement as weights the centroid is the plume's centre of mass, which depends less on where the outline is drawn.

Parameters:

Name Type Description Default
mask Bool[ndarray, 'row col']

Plume mask; True marks plume pixels.

required
transform Any

Affine geotransform from (col, row) to the CRS [m].

required
source tuple[float, float]

Source position s₀ [m] in the same CRS.

required
weights Float[ndarray, 'row col'] | None

Optional weights ωₙ ≥ 0, such as the enhancement.

None

Returns:

Type Description
float

φ₀ [rad], counter-clockwise from the CRS x axis (east), in (−π, π].

Raises:

Type Description
DomainError

If the mask is empty, its weights are negative or sum to zero, or its centroid is within one pixel of the source.

Examples:

A plume of pixels north-east of the source, on a north-up 60 m grid:

>>> import numpy as np
>>> from affine import Affine
>>> transform = Affine(60.0, 0.0, 0.0, 0.0, -60.0, 600.0)
>>> mask = np.zeros((10, 10), dtype=bool)
>>> mask[[4, 3, 2], [5, 6, 7]] = True
>>> angle = plume_direction(mask, transform, (270.0, 270.0))
>>> round(float(np.degrees(angle)), 6)
45.0
Source code in src/plumax/geo/_src/starts.py
def plume_direction(
    mask: Bool[np.ndarray, "row col"],
    transform: Any,
    source: tuple[float, float],
    *,
    weights: Float[np.ndarray, "row col"] | None = None,
) -> float:
    """Direction from the source to the centroid of the mask.

    φ₀ = atan2(s̄₂ − s₀₂, s̄₁ − s₀₁), with s̄ = ∑ₙ ωₙ sₙ / ∑ₙ ωₙ over the mask.

    Algorithm:
        1. Place every pixel centre sₙ in the CRS with the geotransform.
        2. Weight the mask pixels by ωₙ (1, or ``weights``) and take the
           centroid s̄.
        3. Take the angle of s̄ − s₀.

    With the enhancement as ``weights`` the centroid is the plume's centre of
    mass, which depends less on where the outline is drawn.

    Args:
        mask: Plume mask; True marks plume pixels.
        transform: Affine geotransform from ``(col, row)`` to the CRS [m].
        source: Source position s₀ [m] in the same CRS.
        weights: Optional weights ωₙ ≥ 0, such as the enhancement.

    Returns:
        φ₀ [rad], counter-clockwise from the CRS x axis (east), in (−π, π].

    Raises:
        DomainError: If the mask is empty, its weights are negative or sum
            to zero, or its centroid is within one pixel of the source.

    Examples:
        A plume of pixels north-east of the source, on a north-up 60 m grid:

        >>> import numpy as np
        >>> from affine import Affine
        >>> transform = Affine(60.0, 0.0, 0.0, 0.0, -60.0, 600.0)
        >>> mask = np.zeros((10, 10), dtype=bool)
        >>> mask[[4, 3, 2], [5, 6, 7]] = True
        >>> angle = plume_direction(mask, transform, (270.0, 270.0))
        >>> round(float(np.degrees(angle)), 6)
        45.0
    """
    mask = np.asarray(mask, dtype=bool)
    if not bool(mask.any()):
        raise DomainError("plume_direction: the mask is empty.")
    if weights is None:
        weight = mask.astype(float)
    else:
        weights = np.asarray(weights, dtype=float)
        if bool(np.any(weights[mask] < 0.0)):
            raise DomainError("plume_direction: `weights` must be ≥ 0 on the mask.")
        weight = np.where(mask, weights, 0.0)
    # ∑ₙ ωₙ
    total = float(einx.sum("[row col]", weight))
    if total <= 0.0:
        raise DomainError("plume_direction: the weights sum to zero on the mask.")

    # --- direction ---
    # sₙ = (xₙ, yₙ), the pixel centres
    easting, northing = pixel_centers(mask.shape, transform)
    # g = √|det A|, the pixel side
    pixel_side = math.sqrt(pixel_area(transform))
    return direction_from_centroid(
        einx.id("row col, row col -> row col (1 + 1)", easting, northing),
        weight,
        source,
        pixel_side,
        undefined_message=(
            "plume_direction: the centroid of the mask is within one pixel of the "
            "source, so the direction is undefined."
        ),
    )

source_offset_grid

source_offset_grid(source: tuple[float, float], *, pixel_size: float, n: int = 3, step: int = 1) -> Float[np.ndarray, 'start axis']

An n × n grid of source positions around the source, step pixels apart.

s_ij = s₀ + step · g · (i, j) for i, j ∈ {−(n − 1)/2, …, (n − 1)/2}.

The starts run over i (x) first and j (y) second, so the middle start, index n² // 2, is the source itself.

Parameters:

Name Type Description Default
source tuple[float, float]

Source position s₀ [m].

required
pixel_size float

Pixel side g [m].

required
n int

Starts along each axis, odd.

3
step int

Spacing of the starts, in pixels.

1

Returns:

Type Description
Float[ndarray, 'start axis']

The n² starts, one (x, y) row each [m].

Raises:

Type Description
ParameterError

If n is not a positive odd number, or step or pixel_size is not positive.

Examples:

>>> grid = source_offset_grid((100.0, 200.0), pixel_size=60.0)
>>> grid.shape
(9, 2)
>>> grid[4].tolist()
[100.0, 200.0]
>>> grid[0].tolist()
[40.0, 140.0]
Source code in src/plumax/geo/_src/starts.py
def source_offset_grid(
    source: tuple[float, float],
    *,
    pixel_size: float,
    n: int = 3,
    step: int = 1,
) -> Float[np.ndarray, "start axis"]:
    """An n × n grid of source positions around the source, ``step`` pixels apart.

    s_ij = s₀ + step · g · (i, j) for i, j ∈ {−(n − 1)/2, …, (n − 1)/2}.

    The starts run over i (x) first and j (y) second, so the middle start,
    index n² // 2, is the source itself.

    Args:
        source: Source position s₀ [m].
        pixel_size: Pixel side g [m].
        n: Starts along each axis, odd.
        step: Spacing of the starts, in pixels.

    Returns:
        The n² starts, one ``(x, y)`` row each [m].

    Raises:
        ParameterError: If ``n`` is not a positive odd number, or ``step`` or
            ``pixel_size`` is not positive.

    Examples:
        >>> grid = source_offset_grid((100.0, 200.0), pixel_size=60.0)
        >>> grid.shape
        (9, 2)
        >>> grid[4].tolist()
        [100.0, 200.0]
        >>> grid[0].tolist()
        [40.0, 140.0]
    """
    if n < 1 or n % 2 == 0:
        raise ParameterError(f"n must be a positive odd number, got {n}")
    if step < 1:
        raise ParameterError(f"step must be ≥ 1, got {step}")
    require_positive("pixel_size", pixel_size)
    half = (n - 1) // 2
    # step · g · i for i ∈ {−half, …, half}
    offsets = step * pixel_size * np.arange(-half, half + 1, dtype=float)
    offset_x, offset_y = np.meshgrid(offsets, offsets, indexing="ij")
    # (step g i, step g j), i over x first
    grid = einx.id("x y, x y -> (x y) (1 + 1)", offset_x, offset_y)
    # s₀ + step g (i, j)
    starts = einx.add(
        "start axis, axis -> start axis", grid, np.asarray(source, dtype=float)
    )
    return starts

transects: cross-plume transects

Profiles of the enhancement across the plume at regular downwind distances, by spline interpolation of the image, and each profile's line density, centre and width. CrossPlumeProfile returns them as one table on a GeoArray; the array functions underneath give the smoothed centreline and the width law, the starting values of a column-plume fit. They are NumPy and SciPy code, outside any traced path.

Cross-plume transects (implementation in plumax.geo._src.transects).

CrossPlumeProfile

CrossPlumeProfile(*, source: Sequence[float], direction: float, n_transects: int, transect_spacing_m: float, half_length_m: float, order: int = 3)

Bases: Operator

Transect table of a plume image: one row per downwind distance.

Called as op(enhancement) on a GeoArray in kg m⁻² and a projected CRS in metres. Returns a GeoDataFrame with geometry (the transect LineString), distance_m, line_density_kg_m, centre_m, width_m, centre_smooth_m and converged.

The line density is the signed sum of :func:transect_moments; the centre and width are those of :func:fit_transect_gaussians with w_min = δ, and the smoothed centre is :func:smooth_centreline of them. Samples are a pixel apart. Times a wind speed U, the line density is the flux Q_k = U q̂_k that CrossSectionalFlux reports, with interpolated samples in place of whole pixels.

Geo-dependent: the input must be a georeferenced GeoArray (plain arrays raise TypeError) in a projected CRS with metre units (a geographic CRS raises ValueError), as for CrossSectionalFlux. Nodata pixels (non-finite or equal to the fill value) become NaN.

Parameters:

Name Type Description Default
source Sequence[float]

Source position s₀ [m] in the carrier's CRS.

required
direction float

Plume direction φ [rad], counter-clockwise from east.

required
n_transects int

Number of transects T.

required
transect_spacing_m float

Downwind spacing Δ_d [m].

required
half_length_m float

Half the transect length [m].

required
order int

Spline order of the interpolation.

3

Examples:

Profiles every 120 m out to 2.4 km, each ±1.5 km across::

table = CrossPlumeProfile(
    source=(x0, y0),
    direction=np.deg2rad(30.0),
    n_transects=20,
    transect_spacing_m=120.0,
    half_length_m=1500.0,
)(column_mass)
Source code in src/plumax/geo/_src/transects.py
def __init__(
    self,
    *,
    source: Sequence[float],
    direction: float,
    n_transects: int,
    transect_spacing_m: float,
    half_length_m: float,
    order: int = 3,
) -> None:
    self.source = as_tuple(source)
    self.direction = float(direction)
    self.n_transects = int(n_transects)
    self.transect_spacing_m = float(transect_spacing_m)
    self.half_length_m = float(half_length_m)
    self.order = int(order)

TransectProfiles dataclass

TransectProfiles(distance: Float[ndarray, ' transect'], offset: Float[ndarray, ' offset'], values: Float[ndarray, 'transect offset'])

Interpolated enhancement across the plume at regular downwind distances.

Attributes:

Name Type Description
distance Float[ndarray, ' transect']

Downwind distance d_k of each transect [m].

offset Float[ndarray, ' offset']

Crosswind offset c_j of each sample [m], δ apart and symmetric about the plume axis.

values Float[ndarray, 'transect offset']

Enhancement v_kj [kg m⁻²]; NaN outside the image or near nodata.

sample_spacing property

sample_spacing: float

δ = c_{j+1} − c_j [m].

cross_plume_transects

cross_plume_transects(enhancement: Float[ndarray, 'row col'], transform: Any, *, source: tuple[float, float], direction: float, n_transects: int, spacing: float, half_length: float, sample_spacing: float | None = None, order: int = 3) -> TransectProfiles

Profiles across the plume by spline interpolation of the image.

v_kj = 𝓘_ΔΩ(p_kj) with p_kj = s₀ + d_k e_∥ + c_j e_⊥, d_k = k Δ_d and c_j = (j − (S − 1)/2) δ.

Algorithm
  1. Build the sample points p_kj in the carrier's coordinates.
  2. Map them to fractional pixel indices with the inverse transform.
  3. Interpolate with a spline of the given order, nodata filled with zero; samples outside the image or within two pixels of nodata become NaN.
  4. Drop transects whose centre point is outside the image.

The S = 2 round(h / δ) + 1 samples run from −h to h, rounded to whole samples. Transects closer than a pixel would reuse the same pixels, so their line densities would be correlated.

Parameters:

Name Type Description Default
enhancement Float[ndarray, 'row col']

Column enhancement ΔΩ [kg m⁻²], nodata as NaN.

required
transform Any

Affine geotransform from (col, row) to metres.

required
source tuple[float, float]

Source position s₀ [m] in the carrier's CRS.

required
direction float

Plume direction φ [rad], counter-clockwise from east.

required
n_transects int

Number of transects T.

required
spacing float

Downwind spacing Δ_d [m].

required
half_length float

Half the transect length h [m].

required
sample_spacing float | None

Sample spacing δ [m]; defaults to the pixel side.

None
order int

Spline order of the interpolation, 0 to 5.

3

Returns:

Name Type Description
The TransectProfiles

class:TransectProfiles, in the dtype of enhancement.

Raises:

Type Description
ParameterError

If spacing is below one pixel, a length is not positive, half_length is below one sample, n_transects is below one, or order is outside 0 to 5.

DomainError

If no transect lies inside the image.

Examples:

A uniform ridge of 1 kg m⁻² three pixels wide along x, on a 60 m grid, has a line density of 3 × 60 = 180 kg m⁻¹:

>>> import numpy as np
>>> from affine import Affine
>>> transform = Affine(60.0, 0.0, 0.0, 0.0, -60.0, 1200.0)
>>> image = np.zeros((20, 20))
>>> image[9:12, :] = 1.0
>>> profiles = cross_plume_transects(
...     image, transform, source=(30.0, 570.0), direction=0.0,
...     n_transects=4, spacing=120.0, half_length=300.0,
... )
>>> profiles.values.shape
(4, 11)
>>> np.round(transect_moments(profiles)["line_density"], 9).tolist()
[180.0, 180.0, 180.0, 180.0]
Source code in src/plumax/geo/_src/transects.py
def cross_plume_transects(
    enhancement: Float[np.ndarray, "row col"],
    transform: Any,
    *,
    source: tuple[float, float],
    direction: float,
    n_transects: int,
    spacing: float,
    half_length: float,
    sample_spacing: float | None = None,
    order: int = 3,
) -> TransectProfiles:
    """Profiles across the plume by spline interpolation of the image.

    v_kj = 𝓘_ΔΩ(p_kj) with p_kj = s₀ + d_k e_∥ + c_j e_⊥, d_k = k Δ_d and
    c_j = (j − (S − 1)/2) δ.

    Algorithm:
        1. Build the sample points p_kj in the carrier's coordinates.
        2. Map them to fractional pixel indices with the inverse transform.
        3. Interpolate with a spline of the given order, nodata filled with
           zero; samples outside the image or within two pixels of nodata
           become NaN.
        4. Drop transects whose centre point is outside the image.

    The S = 2 round(h / δ) + 1 samples run from −h to h, rounded to whole
    samples. Transects closer than a pixel would reuse the same pixels, so
    their line densities would be correlated.

    Args:
        enhancement: Column enhancement ΔΩ [kg m⁻²], nodata as NaN.
        transform: Affine geotransform from ``(col, row)`` to metres.
        source: Source position s₀ [m] in the carrier's CRS.
        direction: Plume direction φ [rad], counter-clockwise from east.
        n_transects: Number of transects T.
        spacing: Downwind spacing Δ_d [m].
        half_length: Half the transect length h [m].
        sample_spacing: Sample spacing δ [m]; defaults to the pixel side.
        order: Spline order of the interpolation, 0 to 5.

    Returns:
        The :class:`TransectProfiles`, in the dtype of ``enhancement``.

    Raises:
        ParameterError: If ``spacing`` is below one pixel, a length is not
            positive, ``half_length`` is below one sample, ``n_transects`` is
            below one, or ``order`` is outside 0 to 5.
        DomainError: If no transect lies inside the image.

    Examples:
        A uniform ridge of 1 kg m⁻² three pixels wide along x, on a 60 m
        grid, has a line density of 3 × 60 = 180 kg m⁻¹:

        >>> import numpy as np
        >>> from affine import Affine
        >>> transform = Affine(60.0, 0.0, 0.0, 0.0, -60.0, 1200.0)
        >>> image = np.zeros((20, 20))
        >>> image[9:12, :] = 1.0
        >>> profiles = cross_plume_transects(
        ...     image, transform, source=(30.0, 570.0), direction=0.0,
        ...     n_transects=4, spacing=120.0, half_length=300.0,
        ... )
        >>> profiles.values.shape
        (4, 11)
        >>> np.round(transect_moments(profiles)["line_density"], 9).tolist()
        [180.0, 180.0, 180.0, 180.0]
    """
    dtype = np.result_type(np.asarray(enhancement).dtype, np.float32)
    image = np.asarray(enhancement, dtype=np.float64)
    if image.ndim != 2:
        raise ParameterError(
            f"cross_plume_transects: the image must be 2-D, got {image.ndim}-D"
        )
    # g = √|det A|, the pixel side
    pixel_side = math.sqrt(pixel_area(transform))
    # δ, the sample spacing along a transect
    spacing_sample = pixel_side if sample_spacing is None else float(sample_spacing)
    _check_sampling(
        n_transects, spacing, half_length, spacing_sample, order, pixel_side
    )

    # --- sample points ---
    # d_k = k Δ_d, k = 1, …, T
    distance = spacing * np.arange(1, n_transects + 1, dtype=np.float64)
    # c_j = (j − (S − 1)/2) δ, S = 2 round(h / δ) + 1
    half_samples = round(half_length / spacing_sample)
    offset = spacing_sample * np.arange(
        -half_samples, half_samples + 1, dtype=np.float64
    )
    # e_∥ = (cos φ, sin φ),  e_⊥ = (−sin φ, cos φ)
    along, across = angle_frame(direction)
    # p_kj = s₀ + d_k e_∥ + c_j e_⊥
    downwind = einx.multiply("transect, axis -> transect axis", distance, along)
    crosswind = einx.multiply("offset, axis -> offset axis", offset, across)
    points = einx.add(
        "transect axis, offset axis, axis -> transect offset axis",
        downwind,
        crosswind,
        np.asarray(source, dtype=np.float64),
    )

    # --- fractional pixel indices ---
    rows, cols = _pixel_indices(points, transform)

    # --- interpolation ---
    nodata = ~np.isfinite(image)
    filled = np.where(nodata, 0.0, image)
    coordinates = np.stack([rows, cols])
    # v_kj = 𝓘_ΔΩ(p_kj)
    values = ndimage.map_coordinates(filled, coordinates, order=order, mode="nearest")
    # a sample is outside when its nearest pixel is
    num_rows, num_cols = image.shape
    inside = (
        (rows >= -0.5)
        & (rows <= num_rows - 0.5)
        & (cols >= -0.5)
        & (cols <= num_cols - 0.5)
    )
    near_nodata = _near_nodata(nodata, coordinates)
    values = np.where(inside & ~near_nodata, values, np.nan)

    # --- transects inside the image ---
    centre = inside[:, half_samples]
    if not bool(centre.any()):
        raise DomainError(
            "cross_plume_transects: no transect has its centre inside the image."
        )
    return TransectProfiles(
        distance=distance[centre].astype(dtype),
        offset=offset.astype(dtype),
        values=values[centre].astype(dtype),
    )

transect_moments

transect_moments(profiles: TransectProfiles) -> dict[str, Float[np.ndarray, ' transect']]

Line density, centre and width of each transect from its moments.

q̂_k = δ ∑_j v_kj; m̂_k = ∑_j c_j v⁺_kj / ∑_j v⁺_kj; ŵ_k² = ∑_j (c_j − m̂_k)² v⁺_kj / ∑_j v⁺_kj, with v⁺ = max(v, 0).

The line density is the signed sum, unbiased under zero-mean noise. A positive-part sum would add σ / √(2π) per sample for noise of standard deviation σ, a bias of S δ σ / √(2π) that grows with the transect. The same noise floor pulls ŵ_k towards the half-length, so the width of :func:fit_transect_gaussians is the one to use on noisy images. NaN samples carry no weight.

Parameters:

Name Type Description Default
profiles TransectProfiles

The transects.

required

Returns:

Type Description
dict[str, Float[ndarray, ' transect']]

line_density q̂ [kg m⁻¹], centre m̂ [m] and width ŵ [m],

dict[str, Float[ndarray, ' transect']]

one per transect; the centre and width are NaN where no sample is

dict[str, Float[ndarray, ' transect']]

positive.

Examples:

>>> import numpy as np
>>> profiles = TransectProfiles(
...     distance=np.array([60.0]),
...     offset=np.array([-60.0, 0.0, 60.0]),
...     values=np.array([[1.0, 2.0, 1.0]]),
... )
>>> moments = transect_moments(profiles)
>>> moments["line_density"].tolist(), moments["centre"].tolist()
([240.0], [0.0])
Source code in src/plumax/geo/_src/transects.py
def transect_moments(
    profiles: TransectProfiles,
) -> dict[str, Float[np.ndarray, " transect"]]:
    """Line density, centre and width of each transect from its moments.

    q̂_k = δ ∑_j v_kj;  m̂_k = ∑_j c_j v⁺_kj / ∑_j v⁺_kj;
    ŵ_k² = ∑_j (c_j − m̂_k)² v⁺_kj / ∑_j v⁺_kj, with v⁺ = max(v, 0).

    The line density is the signed sum, unbiased under zero-mean noise. A
    positive-part sum would add σ / √(2π) per sample for noise of standard
    deviation σ, a bias of S δ σ / √(2π) that grows with the transect. The
    same noise floor pulls ŵ_k towards the half-length, so the width of
    :func:`fit_transect_gaussians` is the one to use on noisy images. NaN
    samples carry no weight.

    Args:
        profiles: The transects.

    Returns:
        ``line_density`` q̂ [kg m⁻¹], ``centre`` m̂ [m] and ``width`` ŵ [m],
        one per transect; the centre and width are NaN where no sample is
        positive.

    Examples:
        >>> import numpy as np
        >>> profiles = TransectProfiles(
        ...     distance=np.array([60.0]),
        ...     offset=np.array([-60.0, 0.0, 60.0]),
        ...     values=np.array([[1.0, 2.0, 1.0]]),
        ... )
        >>> moments = transect_moments(profiles)
        >>> moments["line_density"].tolist(), moments["centre"].tolist()
        ([240.0], [0.0])
    """
    # v⁺ = max(v, 0), NaN samples carry no weight
    finite = np.isfinite(profiles.values)
    values = np.where(finite, profiles.values, 0.0)
    positive = np.maximum(values, 0.0)
    # q̂_k = δ ∑_j v_kj
    signed_sum = einx.sum("transect [offset]", values)
    line_density = profiles.sample_spacing * signed_sum
    # ∑_j v⁺_kj
    weight = einx.sum("transect [offset]", positive)
    # m̂_k = ∑_j c_j v⁺_kj / ∑_j v⁺_kj
    first_moment = einx.dot(
        "transect offset, offset -> transect", positive, profiles.offset
    )
    centre = _divide(first_moment, weight)
    # (c_j − m̂_k)²
    deviation = einx.subtract(
        "offset, transect -> transect offset", profiles.offset, centre
    )
    # ŵ_k² = ∑_j (c_j − m̂_k)² v⁺_kj / ∑_j v⁺_kj
    second_moment = einx.sum("transect [offset]", np.square(deviation) * positive)
    width = np.sqrt(_divide(second_moment, weight))
    return {"line_density": line_density, "centre": centre, "width": width}

fit_transect_gaussians

fit_transect_gaussians(profiles: TransectProfiles, *, min_width: float, max_offset: float | None = None) -> dict[str, np.ndarray]

Least-squares Gaussian per transect.

(q̂_k, m̂_k, ŵ_k) = argmin ∑_j (v_kj − q / (√(2π) w) exp(−(c_j − m)² / 2w²))², with q ≥ 0, |m| ≤ m_max and w ≥ w_min.

Algorithm
  1. Start from (the moment q̂_k, the offset of the largest sample, 2δ).
  2. Solve the bounded problem by trust-region reflective least squares over the finite samples, transect by transect.
  3. Mark a fit converged when the solver reports success and no parameter sits on a bound.

The fitted q is the area under the Gaussian, so it is a line density.

Parameters:

Name Type Description Default
profiles TransectProfiles

The transects.

required
min_width float

Smallest width w_min [m], the sample spacing in SPIIRE.

required
max_offset float | None

Largest centre offset m_max [m]; defaults to twice the half-length.

None

Returns:

Type Description
dict[str, ndarray]

line_density [kg m⁻¹], centre [m], width [m] and

dict[str, ndarray]

converged, one per transect; NaN and not converged where a

dict[str, ndarray]

transect has fewer than three finite samples or none above zero.

Raises:

Type Description
ParameterError

If min_width or max_offset is not positive.

Examples:

>>> import numpy as np
>>> offset = np.arange(-600.0, 601.0, 60.0)
>>> values = 0.1 / (np.sqrt(2 * np.pi) * 150.0) * np.exp(
...     -0.5 * ((offset - 30.0) / 150.0) ** 2
... )
>>> profiles = TransectProfiles(
...     distance=np.array([60.0]), offset=offset, values=values[None]
... )
>>> fits = fit_transect_gaussians(profiles, min_width=60.0)
>>> [round(float(fits[key][0]), 6) for key in ("line_density", "centre", "width")]
[0.1, 30.0, 150.0]
>>> bool(fits["converged"][0])
True
Source code in src/plumax/geo/_src/transects.py
def fit_transect_gaussians(
    profiles: TransectProfiles,
    *,
    min_width: float,
    max_offset: float | None = None,
) -> dict[str, np.ndarray]:
    """Least-squares Gaussian per transect.

    (q̂_k, m̂_k, ŵ_k) = argmin ∑_j (v_kj − q / (√(2π) w) exp(−(c_j − m)² / 2w²))²,
    with q ≥ 0, |m| ≤ m_max and w ≥ w_min.

    Algorithm:
        1. Start from (the moment q̂_k, the offset of the largest sample, 2δ).
        2. Solve the bounded problem by trust-region reflective least squares
           over the finite samples, transect by transect.
        3. Mark a fit converged when the solver reports success and no
           parameter sits on a bound.

    The fitted q is the area under the Gaussian, so it is a line density.

    Args:
        profiles: The transects.
        min_width: Smallest width w_min [m], the sample spacing in SPIIRE.
        max_offset: Largest centre offset m_max [m]; defaults to twice the
            half-length.

    Returns:
        ``line_density`` [kg m⁻¹], ``centre`` [m], ``width`` [m] and
        ``converged``, one per transect; NaN and not converged where a
        transect has fewer than three finite samples or none above zero.

    Raises:
        ParameterError: If ``min_width`` or ``max_offset`` is not positive.

    Examples:
        >>> import numpy as np
        >>> offset = np.arange(-600.0, 601.0, 60.0)
        >>> values = 0.1 / (np.sqrt(2 * np.pi) * 150.0) * np.exp(
        ...     -0.5 * ((offset - 30.0) / 150.0) ** 2
        ... )
        >>> profiles = TransectProfiles(
        ...     distance=np.array([60.0]), offset=offset, values=values[None]
        ... )
        >>> fits = fit_transect_gaussians(profiles, min_width=60.0)
        >>> [round(float(fits[key][0]), 6) for key in ("line_density", "centre", "width")]
        [0.1, 30.0, 150.0]
        >>> bool(fits["converged"][0])
        True
    """
    require_positive("min_width", min_width)
    offset = np.asarray(profiles.offset, dtype=np.float64)
    spacing_sample = profiles.sample_spacing
    # m_max = 2 h
    bound = 2.0 * float(np.max(np.abs(offset))) if max_offset is None else max_offset
    require_positive("max_offset", bound)
    lower = np.array([0.0, -bound, min_width])
    upper = np.array([np.inf, bound, np.inf])
    moments = transect_moments(profiles)

    num_transects = profiles.values.shape[0]
    estimates = np.full((num_transects, 3), np.nan)
    converged = np.zeros(num_transects, dtype=bool)
    for transect in range(num_transects):
        row = np.asarray(profiles.values[transect], dtype=np.float64)
        finite = np.isfinite(row)
        if int(finite.sum()) < 3:
            continue
        # no positive sample: nothing to fit, a failed fit
        if not bool(np.any(row[finite] > 0.0)):
            continue
        positions = offset[finite]
        # v_kj / s_k with s_k = max_j |v_kj|, so the solver's tolerances see
        # residuals of order one
        scale = float(np.max(np.abs(row[finite])))
        samples = row[finite] / scale
        start = _gaussian_start(
            float(moments["line_density"][transect]) / scale,
            samples,
            positions,
            spacing_sample,
            lower,
            upper,
        )
        fit = optimize.least_squares(
            _gaussian_residual,
            start,
            jac=_gaussian_jacobian,
            bounds=(lower, upper),
            method="trf",
            x_scale="jac",
            args=(positions, samples),
        )
        # q = s_k q̃
        estimates[transect] = fit.x * np.array([scale, 1.0, 1.0])
        converged[transect] = bool(fit.success) and not bool(
            np.any(fit.active_mask != 0)
        )
    dtype = profiles.values.dtype
    # q, m, w per transect, parameters first
    params = einx.id("transect param -> param transect", estimates.astype(dtype))
    line_density, centre, width = params
    return {
        "line_density": line_density,
        "centre": centre,
        "width": width,
        "converged": converged,
    }

smooth_centreline

smooth_centreline(centre: Float[ndarray, ' transect'], width: Float[ndarray, ' transect'], converged: Bool[ndarray, ' transect'], *, window: int = 19, polyorder: int = 2, n_iter: int = 3, threshold: float = 1.5, rejected: Literal['smoothed', 'zero'] = 'smoothed') -> Float[np.ndarray, ' transect']

Centreline with failed fits interpolated and outliers rejected.

m̃ = SG(m̂); m̂_k ← m̃_k where |m̂_k − m̃_k| > 1.5 ŵ_k; repeated, with zeros put before the centres so the line starts at the source.

Algorithm
  1. Interpolate m̂_k and ŵ_k linearly across the unconverged transects.
  2. Put 100 zeros before them, which are never rejected.
  3. Repeat n_iter times: smooth with a Savitzky–Golay filter to get m̃_k, and replace m̂_k wherever |m̂_k − m̃_k| > threshold · ŵ_k.
  4. Smooth once more and drop the zeros.

SPIIRE sets the rejected centres to zero (rejected="zero"), which pulls a bent plume back towards a straight one; the default replaces them by the smoothed line. The window is shortened to the largest odd number not above the series length.

Parameters:

Name Type Description Default
centre Float[ndarray, ' transect']

Centres m̂_k [m], one per transect.

required
width Float[ndarray, ' transect']

Widths ŵ_k [m], the scale of the rejection test.

required
converged Bool[ndarray, ' transect']

Which fits converged.

required
window int

Savitzky–Golay window, odd.

19
polyorder int

Savitzky–Golay polynomial order, below window.

2
n_iter int

Rounds of rejection.

3
threshold float

Rejection threshold, in widths.

1.5
rejected Literal['smoothed', 'zero']

What a rejected centre becomes: "smoothed" or "zero".

'smoothed'

Returns:

Type Description
Float[ndarray, ' transect']

The smoothed centreline m̃_k [m], one per transect.

Raises:

Type Description
ParameterError

If window is not odd, polyorder is not below it, n_iter is negative, threshold is not positive or rejected is unknown.

DomainError

If no fit converged.

Examples:

A straight line with one failed fit and one outlier:

>>> import numpy as np
>>> centre = np.zeros(30)
>>> centre[10], centre[20] = 500.0, 400.0
>>> converged = np.ones(30, dtype=bool)
>>> converged[10] = False
>>> smoothed = smooth_centreline(centre, np.full(30, 60.0), converged)
>>> bool(np.max(np.abs(smoothed)) < 60.0)
True
Source code in src/plumax/geo/_src/transects.py
def smooth_centreline(
    centre: Float[np.ndarray, " transect"],
    width: Float[np.ndarray, " transect"],
    converged: Bool[np.ndarray, " transect"],
    *,
    window: int = 19,
    polyorder: int = 2,
    n_iter: int = 3,
    threshold: float = 1.5,
    rejected: Literal["smoothed", "zero"] = "smoothed",
) -> Float[np.ndarray, " transect"]:
    """Centreline with failed fits interpolated and outliers rejected.

    m̃ = SG(m̂); m̂_k ← m̃_k where |m̂_k − m̃_k| > 1.5 ŵ_k; repeated, with zeros
    put before the centres so the line starts at the source.

    Algorithm:
        1. Interpolate m̂_k and ŵ_k linearly across the unconverged
           transects.
        2. Put 100 zeros before them, which are never rejected.
        3. Repeat ``n_iter`` times: smooth with a Savitzky–Golay filter to
           get m̃_k, and replace m̂_k wherever |m̂_k − m̃_k| > threshold · ŵ_k.
        4. Smooth once more and drop the zeros.

    SPIIRE sets the rejected centres to zero (``rejected="zero"``), which
    pulls a bent plume back towards a straight one; the default replaces
    them by the smoothed line. The window is shortened to the largest odd
    number not above the series length.

    Args:
        centre: Centres m̂_k [m], one per transect.
        width: Widths ŵ_k [m], the scale of the rejection test.
        converged: Which fits converged.
        window: Savitzky–Golay window, odd.
        polyorder: Savitzky–Golay polynomial order, below ``window``.
        n_iter: Rounds of rejection.
        threshold: Rejection threshold, in widths.
        rejected: What a rejected centre becomes: ``"smoothed"`` or ``"zero"``.

    Returns:
        The smoothed centreline m̃_k [m], one per transect.

    Raises:
        ParameterError: If ``window`` is not odd, ``polyorder`` is not below
            it, ``n_iter`` is negative, ``threshold`` is not positive or
            ``rejected`` is unknown.
        DomainError: If no fit converged.

    Examples:
        A straight line with one failed fit and one outlier:

        >>> import numpy as np
        >>> centre = np.zeros(30)
        >>> centre[10], centre[20] = 500.0, 400.0
        >>> converged = np.ones(30, dtype=bool)
        >>> converged[10] = False
        >>> smoothed = smooth_centreline(centre, np.full(30, 60.0), converged)
        >>> bool(np.max(np.abs(smoothed)) < 60.0)
        True
    """
    if window < 1 or window % 2 == 0:
        raise ParameterError(f"window must be a positive odd number, got {window}")
    if not 0 <= polyorder < window:
        raise ParameterError(
            f"polyorder must be in [0, window), got {polyorder} for window {window}"
        )
    require_positive("n_iter", n_iter, allow_zero=True)
    require_positive("threshold", threshold)
    if rejected not in ("smoothed", "zero"):
        raise ParameterError(f"rejected must be 'smoothed' or 'zero', got {rejected!r}")
    dtype = np.result_type(np.asarray(centre).dtype, np.float32)
    centre = np.asarray(centre, dtype=np.float64)
    width = np.asarray(width, dtype=np.float64)
    good = np.asarray(converged, dtype=bool) & np.isfinite(centre) & np.isfinite(width)
    if not bool(good.any()):
        raise DomainError("smooth_centreline: no fit converged.")

    # --- fill the failed fits ---
    index = np.arange(centre.shape[0], dtype=np.float64)
    # m̂_k and ŵ_k, linear between converged neighbours
    filled_centre = np.interp(index, index[good], centre[good])
    filled_width = np.interp(index, index[good], width[good])

    # --- start at the source ---
    # (0, …, 0, m̂_1, …, m̂_T), the zeros never rejected
    series = np.concatenate([np.zeros(_SOURCE_PAD), filled_centre])
    scale = np.concatenate([np.full(_SOURCE_PAD, np.inf), filled_width])
    length = series.shape[0]
    # the largest odd window not above the length, and above polyorder
    window = min(window, length if length % 2 == 1 else length - 1)
    if polyorder >= window:
        raise ParameterError(
            f"polyorder {polyorder} needs a window above it; the series has "
            f"{length} points"
        )

    # --- reject the outliers ---
    for _ in range(n_iter):
        # m̃ = SG(m̂)
        smoothed = signal.savgol_filter(series, window, polyorder)
        # |m̂_k − m̃_k| > threshold · ŵ_k
        outlier = np.abs(series - smoothed) > threshold * scale
        replacement = smoothed if rejected == "smoothed" else 0.0
        series = np.where(outlier, replacement, series)
    # m̃ = SG(m̂), the zeros dropped
    smoothed = signal.savgol_filter(series, window, polyorder)
    return smoothed[_SOURCE_PAD:].astype(dtype)

fit_width_law

fit_width_law(distance: Float[ndarray, ' transect'], width: Float[ndarray, ' transect'], *, reference_distance: float, initial_width: float = 0.0) -> tuple[float, float]

Reference width and exponent from a line through the log widths.

½ log(ŵ_k² − w₀²) = log w_ref + b log(d_k / d_ref), by least squares.

Widths at or below w₀, and non-finite ones, are left out. The result is the reference_width and width_exponent of gauss_plume.PlumeGeometry.

Parameters:

Name Type Description Default
distance Float[ndarray, ' transect']

Downwind distances d_k [m].

required
width Float[ndarray, ' transect']

Widths ŵ_k [m], as fitted by :func:fit_transect_gaussians.

required
reference_distance float

Reference distance d_ref [m].

required
initial_width float

Initial width w₀ [m].

0.0

Returns:

Type Description
tuple[float, float]

(w_ref, b): the width at d_ref [m] and the exponent.

Raises:

Type Description
ParameterError

If reference_distance is not positive or initial_width is negative.

DomainError

If fewer than two transects at distinct distances keep a width above w₀.

Examples:

>>> import numpy as np
>>> distance = np.array([250.0, 500.0, 1000.0, 2000.0])
>>> width = 100.0 * (distance / 1000.0) ** 0.8
>>> reference_width, exponent = fit_width_law(
...     distance, width, reference_distance=1000.0
... )
>>> round(reference_width, 6), round(exponent, 6)
(100.0, 0.8)
Source code in src/plumax/geo/_src/transects.py
def fit_width_law(
    distance: Float[np.ndarray, " transect"],
    width: Float[np.ndarray, " transect"],
    *,
    reference_distance: float,
    initial_width: float = 0.0,
) -> tuple[float, float]:
    """Reference width and exponent from a line through the log widths.

    ½ log(ŵ_k² − w₀²) = log w_ref + b log(d_k / d_ref), by least squares.

    Widths at or below w₀, and non-finite ones, are left out. The result is
    the ``reference_width`` and ``width_exponent`` of
    ``gauss_plume.PlumeGeometry``.

    Args:
        distance: Downwind distances d_k [m].
        width: Widths ŵ_k [m], as fitted by :func:`fit_transect_gaussians`.
        reference_distance: Reference distance d_ref [m].
        initial_width: Initial width w₀ [m].

    Returns:
        ``(w_ref, b)``: the width at d_ref [m] and the exponent.

    Raises:
        ParameterError: If ``reference_distance`` is not positive or
            ``initial_width`` is negative.
        DomainError: If fewer than two transects at distinct distances keep a
            width above w₀.

    Examples:
        >>> import numpy as np
        >>> distance = np.array([250.0, 500.0, 1000.0, 2000.0])
        >>> width = 100.0 * (distance / 1000.0) ** 0.8
        >>> reference_width, exponent = fit_width_law(
        ...     distance, width, reference_distance=1000.0
        ... )
        >>> round(reference_width, 6), round(exponent, 6)
        (100.0, 0.8)
    """
    require_positive("reference_distance", reference_distance)
    require_positive("initial_width", initial_width, allow_zero=True)
    distance = np.asarray(distance, dtype=np.float64)
    width = np.asarray(width, dtype=np.float64)
    kept = np.isfinite(width) & (width > initial_width) & (distance > 0.0)
    if np.unique(distance[kept]).shape[0] < 2:
        raise DomainError(
            "fit_width_law: fewer than two distances keep a width above the "
            "initial width."
        )
    # x_k = log(d_k / d_ref)
    log_distance = np.log(distance[kept] / reference_distance)
    # y_k = ½ log(ŵ_k² − w₀²)
    log_width = 0.5 * np.log(np.square(width[kept]) - initial_width**2)
    # x_k − x̄,  y_k − ȳ
    centred_x = log_distance - np.mean(log_distance)
    centred_y = log_width - np.mean(log_width)
    # b = ∑ (x − x̄)(y − ȳ) / ∑ (x − x̄)²
    exponent = float(einx.dot("[k], [k] ->", centred_x, centred_y)) / float(
        einx.dot("[k], [k] ->", centred_x, centred_x)
    )
    # log w_ref = ȳ − b x̄
    log_reference = float(np.mean(log_width)) - exponent * float(np.mean(log_distance))
    return math.exp(log_reference), exponent

plume_array: the array functions

Plume masks, geometry and column units on NumPy arrays (behind [geo]).

The array functions under the operators in :mod:plumax.geo.plume, ported from geotoolz's plume module (#134) with their behaviour unchanged. They take plain arrays and an affine transform, no carrier, but build on geoops's public mask, measure and threshold helpers and on shapely, so they need the [geo] extra too. Algorithms and unit conventions follow the trace-gas plume literature cited per function:

  • Varon et al. (2018), AMT: the integrated mass enhancement (IME) method.
  • Frankenberg et al. (2016), PNAS: airborne CH4 plume detection.
  • Thompson et al. (2015), AMT, and Foote et al. (2020), TGRS: the matched-filter CH4 retrievals whose columns these functions convert.

plume_mask

plume_mask(values: Num[ndarray, 'h w'] | Num[ndarray, '1 h w'], *, threshold: ThresholdMode = 'otsu', min_area_px: int = 50, connectivity: Connectivity = 8, nbins: int = 256) -> Bool[np.ndarray, 'h w']

Threshold an enhancement map and remove small connected components.

Parameters:

Name Type Description Default
values Num[ndarray, 'h w'] | Num[ndarray, '1 h w']

Single-band enhancement map, (H, W) or (1, H, W).

required
threshold ThresholdMode

Absolute number, "otsu", or "percentile:<p>"; see :func:geoops.segment.resolve_threshold.

'otsu'
min_area_px int

Minimum connected-component size in pixels.

50
connectivity Connectivity

4 or 8 connectivity for component labelling.

8
nbins int

Histogram bins for the "otsu" threshold. Default 256.

256

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask of the surviving plume pixels.

Source code in src/plumax/geo/_src/plume_array.py
def plume_mask(
    values: Num[np.ndarray, "h w"] | Num[np.ndarray, "1 h w"],
    *,
    threshold: ThresholdMode = "otsu",
    min_area_px: int = 50,
    connectivity: Connectivity = 8,
    nbins: int = 256,
) -> Bool[np.ndarray, "h w"]:
    """Threshold an enhancement map and remove small connected components.

    Args:
        values: Single-band enhancement map, ``(H, W)`` or ``(1, H, W)``.
        threshold: Absolute number, ``"otsu"``, or ``"percentile:<p>"``;
            see :func:`geoops.segment.resolve_threshold`.
        min_area_px: Minimum connected-component size in pixels.
        connectivity: 4 or 8 connectivity for component labelling.
        nbins: Histogram bins for the ``"otsu"`` threshold. Default ``256``.

    Returns:
        Boolean ``(H, W)`` mask of the surviving plume pixels.
    """
    arr = squeeze_single_band(values)
    raw = threshold_mask(arr, threshold, nbins=nbins)
    return label_components(raw, min_area_px=min_area_px, connectivity=connectivity) > 0

wind_advection_cone

wind_advection_cone(shape: tuple[int, int], transform: Any, *, source: tuple[float, float], wind_u: float, wind_v: float, half_angle_deg: float = 30.0, max_distance: float = 5000.0) -> Bool[np.ndarray, 'h w']

Rasterize an analytical downwind sector mask.

Marks pixels whose center lies within max_distance of source and whose bearing from the source is within half_angle_deg of the wind direction (wind_u, wind_v) — a geometric prior for where an advected plume can be. The source pixel itself is included.

With d = (x − x₀, y − y₀) the offset of a pixel center from the source and ŵ = (u, v) / ‖(u, v)‖ the unit wind vector, a pixel is inside when

‖d‖ ≤ max_distance  and  d·ŵ ≥ ‖d‖ · cos(half_angle_deg)

i.e. the angle between d and ŵ is at most half_angle_deg. For half_angle_deg ≤ 90 the angle test alone keeps the sector in the downwind half-plane (cos ≥ 0 ⇒ d·ŵ ≥ 0); half_angle_deg > 90 widens it past the crosswind line, and half_angle_deg = 180 is the full disc of radius max_distance, upwind pixels included.

Parameters:

Name Type Description Default
shape tuple[int, int]

Raster shape (H, W).

required
transform Any

Affine-like geotransform of the raster; its CRS units must match source and max_distance.

required
source tuple[float, float]

(x, y) source coordinates in CRS units.

required
wind_u float

Eastward wind component.

required
wind_v float

Northward wind component.

required
half_angle_deg float

Half-angle of the sector in degrees, in [0, 180].

30.0
max_distance float

Sector radius in CRS units.

5000.0

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask, True inside the downwind sector.

Raises:

Type Description
ValueError

If the wind vector is zero, half_angle_deg is outside [0, 180], or max_distance is not positive.

Source code in src/plumax/geo/_src/plume_array.py
def wind_advection_cone(
    shape: tuple[int, int],
    transform: Any,
    *,
    source: tuple[float, float],
    wind_u: float,
    wind_v: float,
    half_angle_deg: float = 30.0,
    max_distance: float = 5000.0,
) -> Bool[np.ndarray, "h w"]:
    """Rasterize an analytical downwind sector mask.

    Marks pixels whose center lies within ``max_distance`` of ``source``
    and whose bearing from the source is within ``half_angle_deg`` of the
    wind direction ``(wind_u, wind_v)`` — a geometric prior for where an
    advected plume can be. The source pixel itself is included.

    With ``d = (x − x₀, y − y₀)`` the offset of a pixel center from the
    source and ``ŵ = (u, v) / ‖(u, v)‖`` the unit wind vector, a pixel is
    inside when

        ‖d‖ ≤ max_distance  and  d·ŵ ≥ ‖d‖ · cos(half_angle_deg)

    i.e. the angle between ``d`` and ``ŵ`` is at most ``half_angle_deg``.
    For ``half_angle_deg ≤ 90`` the angle test alone keeps the sector in
    the downwind half-plane (``cos ≥ 0 ⇒ d·ŵ ≥ 0``); ``half_angle_deg > 90``
    widens it past the crosswind line, and ``half_angle_deg = 180`` is the
    full disc of radius ``max_distance``, upwind pixels included.

    Args:
        shape: Raster shape ``(H, W)``.
        transform: Affine-like geotransform of the raster; its CRS units
            must match ``source`` and ``max_distance``.
        source: ``(x, y)`` source coordinates in CRS units.
        wind_u: Eastward wind component.
        wind_v: Northward wind component.
        half_angle_deg: Half-angle of the sector in degrees, in [0, 180].
        max_distance: Sector radius in CRS units.

    Returns:
        Boolean ``(H, W)`` mask, True inside the downwind sector.

    Raises:
        ValueError: If the wind vector is zero, ``half_angle_deg`` is
            outside [0, 180], or ``max_distance`` is not positive.
    """
    wind_norm = float(np.hypot(wind_u, wind_v))
    if wind_norm == 0.0:
        raise ValueError("wind vector must be non-zero")
    if not 0.0 <= half_angle_deg <= 180.0:
        raise ValueError("half_angle_deg must be in [0, 180]")
    require_positive("max_distance", max_distance)

    easting, northing = pixel_centers(shape, transform)
    # Δx = x − x_source
    offset_x = easting - source[0]
    # Δy = y − y_source
    offset_y = northing - source[1]
    # d = √(Δx² + Δy²)
    distances = np.hypot(offset_x, offset_y)
    # s = (Δx u + Δy v) / ‖w‖
    projection = (offset_x * wind_u + offset_y * wind_v) / wind_norm
    cos_angle = np.divide(
        projection,
        distances,
        out=np.ones_like(distances, dtype=float),
        where=distances > 0,
    )
    # Clip rounding overshoot so half_angle_deg=180 (cos = −1) is the full disc.
    cos_angle = np.clip(cos_angle, -1.0, 1.0)
    min_cos = np.cos(np.deg2rad(half_angle_deg))
    return (distances <= max_distance) & (cos_angle >= min_cos)

convert_column_units

convert_column_units(values: Num[ndarray, '*dims'], *, gas: str = 'CH4', units_in: ColumnUnit = 'ppm_m', units_out: ColumnUnit = 'kg_m2', pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD) -> Float[np.ndarray, '*dims']

Convert column enhancement among ppm m, mol/m^2, and kg/m^2.

A ppm m enhancement is a mixing ratio integrated along the path, so its amount of gas depends on the air number density there, :math:p / (k_B T):

.. math::

\Omega_{\mathrm{mol/m^2}} \;=\; \frac{X \cdot 10^{-6}\, p}{k_B T N_A},
\qquad
\Omega_{\mathrm{kg/m^2}}  \;=\; M_{\mathrm{gas}}
                                \cdot \Omega_{\mathrm{mol/m^2}}

where X is the enhancement in ppm m, :math:p and :math:T the pressure and temperature of the layer, :math:k_B the Boltzmann constant, :math:N_A Avogadro's number and :math:M_{\mathrm{gas}} the molar mass (CH4: 0.0160425 kg/mol; CO2: 0.0440095 kg/mol). It is the same relation as :func:plumax.obs.ppm_m_to_column_mass, and both default to the ISA sea-level 101 325 Pa and 288.15 K; pass the scene's values when known.

Parameters:

Name Type Description Default
values Num[ndarray, '*dims']

The column enhancement, in units_in.

required
gas str

"CH4" or "CO2".

'CH4'
units_in ColumnUnit

Units of values.

'ppm_m'
units_out ColumnUnit

Units of the result.

'kg_m2'
pressure_pa float

Layer pressure p [Pa], used by the ppm m conversions.

P_STANDARD
temperature_k float

Layer temperature T [K], used by the ppm m conversions.

T_STANDARD

Returns:

Type Description
Float[ndarray, '*dims']

The enhancement in units_out.

Raises:

Type Description
ValueError

If gas is not supported.

UnitError

If a unit is unknown; a ValueError.

Source code in src/plumax/geo/_src/plume_array.py
def convert_column_units(
    values: Num[np.ndarray, "*dims"],
    *,
    gas: str = "CH4",
    units_in: ColumnUnit = "ppm_m",
    units_out: ColumnUnit = "kg_m2",
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
) -> Float[np.ndarray, "*dims"]:
    r"""Convert column enhancement among ppm m, mol/m^2, and kg/m^2.

    A ppm m enhancement is a mixing ratio integrated along the path, so its
    amount of gas depends on the air number density there, :math:`p / (k_B T)`:

    .. math::

        \Omega_{\mathrm{mol/m^2}} \;=\; \frac{X \cdot 10^{-6}\, p}{k_B T N_A},
        \qquad
        \Omega_{\mathrm{kg/m^2}}  \;=\; M_{\mathrm{gas}}
                                        \cdot \Omega_{\mathrm{mol/m^2}}

    where ``X`` is the enhancement in ppm m, :math:`p` and :math:`T` the
    pressure and temperature of the layer, :math:`k_B` the Boltzmann constant,
    :math:`N_A` Avogadro's number and :math:`M_{\mathrm{gas}}` the molar mass
    (CH4: 0.0160425 kg/mol; CO2: 0.0440095 kg/mol). It is the same relation as
    :func:`plumax.obs.ppm_m_to_column_mass`, and both default to the ISA
    sea-level 101 325 Pa and 288.15 K; pass the scene's values when known.

    Args:
        values: The column enhancement, in ``units_in``.
        gas: ``"CH4"`` or ``"CO2"``.
        units_in: Units of ``values``.
        units_out: Units of the result.
        pressure_pa: Layer pressure p [Pa], used by the ppm m conversions.
        temperature_k: Layer temperature T [K], used by the ppm m conversions.

    Returns:
        The enhancement in ``units_out``.

    Raises:
        ValueError: If ``gas`` is not supported.
        geophysix.exceptions.UnitError: If a unit is unknown; a ``ValueError``.
    """
    gas_key = gas.upper()
    if gas_key not in _GASES:
        supported = ", ".join(sorted(_GASES))
        raise ValueError(f"unsupported gas {gas!r}; expected one of {supported}")
    # float64, since convert keeps a float32 input as float32
    arr = np.asarray(values, dtype=float)
    return convert(
        arr,
        units_in,
        units_out,
        gas=_GASES[gas_key],
        pressure=pressure_pa,
        temperature=temperature_k,
    )

plume_length

plume_length(mask: Bool[ndarray, 'h w'], transform: Any, *, method: Literal['max_axis', 'convex_hull', 'skeleton'] = 'max_axis') -> float

Estimate plume length L from active pixel centers.

L is the effective length used by Varon et al. (2018) in the IME method Q = U_eff * IME / L. Three estimators are supported:

  • "max_axis": maximum pairwise distance between active pixels, taken over the vertices of their convex hull (the same value as over every pair, in memory that does not grow with N²). Fast and robust; matches the original Varon 2018 definition for reasonably linear plumes.
  • "convex_hull": max diameter of the convex hull of the active pixels, which is the "max_axis" value, since that already runs over the hull's vertices. Collinear points, which have no 2-D hull, give the point-set diameter.
  • "skeleton": length of the plume centreline, via :func:geoops.measure.skeleton_length with the transform as the pixel step. The mask is skeletonised and L is the longest geodesic path through the 8-connected skeleton, with each step weighted by its Euclidean length in CRS units (so diagonal steps and anisotropic pixels are measured correctly). Better than the chord for curved plumes. The path runs between skeleton pixel centres, so for thick plumes it is shorter than the mask extent by roughly the plume width.

Lengths are in CRS units (m for a projected metric CRS) and measured between pixel centres.

A single-pixel mask returns one linear pixel size, sqrt(pixel_area), for every method: it has no geometry to measure, and the one-pixel proxy is the documented convention.

Parameters:

Name Type Description Default
mask Bool[ndarray, 'h w']

Boolean (H, W) plume mask.

required
transform Any

Affine-like geotransform (a, b, d, e coefficients) mapping pixel indices to CRS coordinates.

required
method Literal['max_axis', 'convex_hull', 'skeleton']

Length estimator (see above).

'max_axis'

Returns:

Type Description
float

The plume length in CRS units; 0.0 for an empty mask.

Raises:

Type Description
ValueError

If method is unknown, or if method="skeleton" and a multi-pixel mask yields L == 0 (every skeleton component collapses to a single pixel, e.g. a compact blob a few pixels across or scattered isolated pixels). A one-pixel proxy would badly under-estimate L (and over-estimate Q) there, so use "max_axis" or "convex_hull".

Source code in src/plumax/geo/_src/plume_array.py
def plume_length(
    mask: Bool[np.ndarray, "h w"],
    transform: Any,
    *,
    method: Literal["max_axis", "convex_hull", "skeleton"] = "max_axis",
) -> float:
    """Estimate plume length ``L`` from active pixel centers.

    ``L`` is the effective length used by Varon et al. (2018) in the IME
    method ``Q = U_eff * IME / L``. Three estimators are supported:

    - ``"max_axis"``: maximum pairwise distance between active pixels,
      taken over the vertices of their convex hull (the same value as over
      every pair, in memory that does not grow with ``N²``). Fast and robust; matches the original Varon 2018 definition for
      reasonably linear plumes.
    - ``"convex_hull"``: max diameter of the convex hull of the active
      pixels, which is the ``"max_axis"`` value, since that already runs
      over the hull's vertices. Collinear points, which have no 2-D hull,
      give the point-set diameter.
    - ``"skeleton"``: length of the plume centreline, via
      :func:`geoops.measure.skeleton_length` with the transform as the
      pixel step. The mask is skeletonised and ``L`` is the longest
      geodesic path through the 8-connected skeleton,
      with each step weighted by its Euclidean length in CRS units
      (so diagonal steps and anisotropic pixels are measured
      correctly). Better than the chord for curved plumes. The path
      runs between skeleton pixel centres, so for thick plumes it is
      shorter than the mask extent by roughly the plume width.

    Lengths are in CRS units (m for a projected metric CRS) and measured
    between pixel centres.

    A single-pixel mask returns one linear pixel size,
    ``sqrt(pixel_area)``, for every method: it has no geometry to
    measure, and the one-pixel proxy is the documented convention.

    Args:
        mask: Boolean ``(H, W)`` plume mask.
        transform: Affine-like geotransform (``a``, ``b``, ``d``, ``e``
            coefficients) mapping pixel indices to CRS coordinates.
        method: Length estimator (see above).

    Returns:
        The plume length in CRS units; ``0.0`` for an empty mask.

    Raises:
        ValueError: If ``method`` is unknown, or if ``method="skeleton"``
            and a multi-pixel mask yields ``L == 0`` (every skeleton
            component collapses to a single pixel, e.g. a compact blob a
            few pixels across or scattered isolated pixels). A one-pixel
            proxy would badly under-estimate ``L`` (and over-estimate
            ``Q``) there, so use ``"max_axis"`` or ``"convex_hull"``.
    """
    active = np.asarray(mask, dtype=bool)
    if not active.any():
        return 0.0
    easting, northing = pixel_centers(active.shape, transform)
    # p = (x, y) at the active pixel centres
    points = einx.id("point, point -> point (1 + 1)", easting[active], northing[active])
    if points.shape[0] == 1:
        # Single pixel: use one linear pixel size as the length proxy.
        return float(np.sqrt(pixel_area(transform)))
    if method == "max_axis":
        return _diameter(points)
    if method == "convex_hull":
        # the diameter of the hull is that of its vertices, as for max_axis
        return _diameter(points)
    if method == "skeleton":
        length = skeleton_length(active, step=transform)
        if length <= 0.0:
            raise ValueError(
                f"skeleton plume length is 0 for a non-empty {int(active.sum())}-"
                "pixel mask: every skeleton component collapses to a single "
                "pixel (compact blob or isolated pixels). Use "
                "length_method='max_axis' or 'convex_hull' for such plumes."
            )
        return length
    raise ValueError("length_method must be 'max_axis', 'convex_hull', or 'skeleton'")

pixel_area

pixel_area(transform: Any) -> float

Return pixel area from an affine-like transform determinant.

Parameters:

Name Type Description Default
transform Any

Affine-like object exposing a, b, d, e coefficients (e.g. rasterio.Affine).

required

Returns:

Type Description
float

|a*e - b*d| — the pixel area in squared CRS units (m^2 for a

float

projected metric CRS).

Source code in src/plumax/geo/_src/plume_array.py
def pixel_area(transform: Any) -> float:
    """Return pixel area from an affine-like transform determinant.

    Args:
        transform: Affine-like object exposing ``a``, ``b``, ``d``, ``e``
            coefficients (e.g. ``rasterio.Affine``).

    Returns:
        ``|a*e - b*d|`` — the pixel area in squared CRS units (m^2 for a
        projected metric CRS).
    """
    return float(abs(transform.a * transform.e - transform.b * transform.d))

pixel_centers

pixel_centers(shape: tuple[int, int], transform: Any) -> tuple[Float[np.ndarray, 'h w'], Float[np.ndarray, 'h w']]

Return x/y coordinate grids for pixel centers.

Parameters:

Name Type Description Default
shape tuple[int, int]

Raster shape (H, W).

required
transform Any

Affine-like geotransform mapping (col, row) pixel indices to CRS coordinates.

required

Returns:

Type Description
Float[ndarray, 'h w']

Tuple (xs, ys) of (H, W) float arrays holding the CRS

Float[ndarray, 'h w']

coordinates of each pixel center.

Source code in src/plumax/geo/_src/plume_array.py
def pixel_centers(
    shape: tuple[int, int], transform: Any
) -> tuple[Float[np.ndarray, "h w"], Float[np.ndarray, "h w"]]:
    """Return x/y coordinate grids for pixel centers.

    Args:
        shape: Raster shape ``(H, W)``.
        transform: Affine-like geotransform mapping ``(col, row)`` pixel
            indices to CRS coordinates.

    Returns:
        Tuple ``(xs, ys)`` of ``(H, W)`` float arrays holding the CRS
        coordinates of each pixel center.
    """
    rows, cols = np.indices(shape, dtype=float)
    return pixel_xy(transform, rows, cols)

squeeze_single_band

squeeze_single_band(values: Shaped[ndarray, 'h w'] | Shaped[ndarray, '1 h w']) -> Shaped[np.ndarray, 'h w']

Return a 2-D plume map from a 2-D or singleton-band array.

Thin delegate to :func:geoops.carrier.single_band, kept under geotoolz's historical public name.

Parameters:

Name Type Description Default
values Shaped[ndarray, 'h w'] | Shaped[ndarray, '1 h w']

A (H, W) array or a (1, H, W) singleton-band cube. Any array-like is accepted.

required

Returns:

Type Description
Shaped[ndarray, 'h w']

The (H, W) array. No copy is made for ndarray input.

Raises:

Type Description
ValueError

If values is neither (H, W) nor (1, H, W).

Source code in src/plumax/geo/_src/plume_array.py
def squeeze_single_band(
    values: Shaped[np.ndarray, "h w"] | Shaped[np.ndarray, "1 h w"],
) -> Shaped[np.ndarray, "h w"]:
    """Return a 2-D plume map from a 2-D or singleton-band array.

    Thin delegate to :func:`geoops.carrier.single_band`, kept under
    geotoolz's historical public name.

    Args:
        values: A ``(H, W)`` array or a ``(1, H, W)`` singleton-band
            cube. Any array-like is accepted.

    Returns:
        The ``(H, W)`` array. No copy is made for ndarray input.

    Raises:
        ValueError: If ``values`` is neither ``(H, W)`` nor ``(1, H, W)``.
    """
    return single_band(values, name="plume")