[Git][debian-gis-team/xsar][master] 5 commits: New upstream version 2026.11.19

Antonio Valentino (@antonio.valentino) gitlab at salsa.debian.org
Sun Nov 22 11:54:26 GMT 2026



Antonio Valentino pushed to branch master at Debian GIS Project / xsar


Commits:
fed1655b by Antonio Valentino at 2026-11-22T11:47:48+00:00
New upstream version 2026.11.19
- - - - -
246baf46 by Antonio Valentino at 2026-11-22T11:47:52+00:00
Update upstream source from tag 'upstream/2026.11.19'

Update to upstream version '2026.11.19'
with Debian dir 3e45da2af8c5b988e831d2ff41292f0ff76013cb
- - - - -
de9f3f1a by Antonio Valentino at 2026-11-22T11:48:30+00:00
New upstream release

- - - - -
dc5755b6 by Antonio Valentino at 2026-11-22T11:51:34+00:00
Update dependency version

- - - - -
ad66f56e by Antonio Valentino at 2026-11-22T11:51:58+00:00
Set ditribution to unstable

- - - - -


21 changed files:

- .git_archival.txt
- .github/workflows/publish.yml
- ci/requirements/docs.yaml
- ci/requirements/environment.yaml
- debian/changelog
- debian/control
- docs/index.rst
- pyproject.toml
- src/xsar/base_dataset.py
- src/xsar/base_meta.py
- src/xsar/radarsat2_dataset.py
- src/xsar/radarsat2_meta.py
- src/xsar/rcm_dataset.py
- src/xsar/rcm_meta.py
- src/xsar/sentinel1_dataset.py
- src/xsar/sentinel1_meta.py
- src/xsar/utils.py
- test/test_antimeridian.py
- + test/test_antimeridian_sentinel1.py
- + test/test_flip_coords.py
- + test/test_resampled_read_rcm.py


Changes:

=====================================
.git_archival.txt
=====================================
@@ -1 +1 @@
-ref-names: HEAD -> main, tag: 2026.08.31
\ No newline at end of file
+ref-names: HEAD -> main, tag: 2026.11.19
\ No newline at end of file


=====================================
.github/workflows/publish.yml
=====================================
@@ -51,4 +51,4 @@ jobs:
           path: dist/
 
       - name: Publish to PyPI
-        uses: pypa/gh-action-pypi-publish at dc37677b2e1c63e2034f94d8a5b11f265b73ba33
+        uses: pypa/gh-action-pypi-publish at 7245906fb61fa33a13554f9d5fb856fe61758086


=====================================
ci/requirements/docs.yaml
=====================================
@@ -6,3 +6,4 @@ dependencies:
   - sphinx>=4
   - sphinx_book_theme
   - ipython
+  
\ No newline at end of file


=====================================
ci/requirements/environment.yaml
=====================================
@@ -27,6 +27,6 @@ dependencies:
   - rioxarray
   - mapraster
   - xmlschema <4.0.0
-  - xarray-safe-s1
-  - xradarsat2
+  - xarray-safe-s1>=2026.11.18
+  - xradarsat2>=2026.11.18
   - xarray-safe-rcm


=====================================
debian/changelog
=====================================
@@ -1,3 +1,11 @@
+xsar (2026.11.19-1) unstable; urgency=medium
+
+  * New upstream release.
+  * debian/control:
+    - Update dependency versions.
+
+ -- Antonio Valentino <antonio.valentino at tiscali.it>  Sun, 22 Nov 2026 11:51:40 +0000
+
 xsar (2026.08.31-1) unstable; urgency=medium
 
   [ Bas Couwenberg ]


=====================================
debian/control
=====================================
@@ -27,8 +27,8 @@ Build-Depends: debhelper-compat (= 13),
                python3-shapely,
                python3-xarray (>= 2024.10.0),
                python3-xarray-safe-rcm,
-               python3-xarray-safe-s1,
-               python3-xradarsat2,
+               python3-xarray-safe-s1 (>=2026.11.18),
+               python3-xradarsat2 (>= 2026.11.18),
                python3-yaml
 Standards-Version: 4.7.4
 Testsuite: autopkgtest-pkg-pybuild


=====================================
docs/index.rst
=====================================
@@ -32,6 +32,35 @@ Overview
     * `open a dataset at lower resolution`_
     * `convert lon/lat to dataset coordinates`_
 
+Readers
+.......
+
+    **xsar** relies on one reader per mission for the metadata. The *digital_number* is read by
+    the reader for Sentinel-1 and RadarSAT-2, and by **xsar** itself for RCM:
+
+    .. list-table::
+       :header-rows: 1
+
+       * - mission
+         - metadata
+         - *digital_number*
+         - image flipped by **xsar**
+       * - Sentinel-1
+         - `xarray-safe-s1`_
+         - `xarray-safe-s1`_
+         - never: ESA products are in acquisition order
+       * - RadarSAT-2
+         - `xradarsat2`_
+         - `xradarsat2`_
+         - depending on pass direction and antenna pointing
+       * - RCM
+         - `xarray-safe-rcm`_
+         - **xsar** (``RcmDataset.load_digital_number``)
+         - depending on pass direction and antenna pointing
+
+    So the reading of *digital_number* (full or lower resolution) is tested in `xarray-safe-s1`_
+    for Sentinel-1, in `xradarsat2`_ for RadarSAT-2, and in **xsar** for RCM.
+
 Examples
 ........
 
@@ -118,6 +147,9 @@ Last documentation build: |today|
    basic_api
 
 .. _on github: https://github.com/umr-lops/xsar
+.. _xarray-safe-s1: https://github.com/umr-lops/xarray-safe-s1
+.. _xradarsat2: https://github.com/umr-lops/xradarsat2
+.. _xarray-safe-rcm: https://github.com/umr-lops/xarray-safe-rcm
 .. _xarray: http://xarray.pydata.org
 .. _dask: http://dask.org
 .. _xarray.open_dataset: http://xarray.pydata.org/en/stable/generated/xarray.open_dataset.html


=====================================
pyproject.toml
=====================================
@@ -52,9 +52,9 @@ dependencies = [
   'mapraster'
 ]
 [project.optional-dependencies]
-RS2 = ["xradarsat2"]
+RS2 = ["xradarsat2>=2026.11.18"]
 RCM = ["xarray-safe-rcm"]
-S1 = ["xarray-safe-s1"]
+S1 = ["xarray-safe-s1>=2026.11.18"]
 
 
 


=====================================
src/xsar/base_dataset.py
=====================================
@@ -129,8 +129,13 @@ class BaseDataset(ABC):
     def geometry(self):
         """
         geometry of this dataset, as a `shapely.geometry.Polygon` (lon/lat coordinates)
+
+        If `self.sar_meta.cross_antimeridian` is True, longitudes are in the continuous [0, 360] range.
         """
-        return Polygon(zip(*self._bbox_ll))
+        lon, lat = self._bbox_ll
+        if self.sar_meta.cross_antimeridian:
+            lon = np.asarray(lon) % 360
+        return Polygon(zip(lon, lat))
 
     def load_ground_heading(self):
         """
@@ -348,6 +353,9 @@ class BaseDataset(ABC):
                 #         print('lat',lat)
                 # else:
                 lon, lat = self.sar_meta.coords2ll(line, sample)
+                if self.sar_meta.cross_antimeridian:
+                    # continuous longitudes, as the footprint (no jump from 180 to -180 between gcps)
+                    lon = lon % 360
                 gcp = GroundControlPoint(x=lon, y=lat, z=0, col=icol, row=irow)
                 local_gcps.append(gcp)
                 cpt += 1


=====================================
src/xsar/base_meta.py
=====================================
@@ -15,7 +15,14 @@ from .raster_readers import available_rasters
 from .base_dataset import BaseDataset
 import geopandas as gpd
 
-from .utils import class_or_instancemethod, to_lon180, haversine, config
+from .utils import (
+    class_or_instancemethod,
+    to_lon180,
+    geometry_to_lon180,
+    geometry_to_lon360,
+    haversine,
+    config,
+)
 
 logger = logging.getLogger("xsar.base_meta")
 logger.addHandler(logging.NullHandler())
@@ -59,6 +66,7 @@ class BaseMeta(BaseDataset):
     _mask_intersecting_geometries = {}
     _mask_geometry = {}
     _geoloc = None
+    _cross_antimeridian = None
     _rasterized_masks = None
     manifest_attrs = None
     _time_range = None
@@ -104,7 +112,9 @@ class BaseMeta(BaseDataset):
                 proj_transform = pyproj.Transformer.from_crs(
                     pyproj.CRS("EPSG:4326"), crs_in, always_xy=True
                 ).transform
-                footprint_crs = transform(proj_transform, self.footprint)
+                # the shapefile is in [-180, 180]: a footprint crossing the antimeridian
+                # (continuous [0, 360] longitudes) is split in two parts
+                footprint_crs = transform(proj_transform, geometry_to_lon180(self.footprint))
 
                 with warnings.catch_warnings():
                     # ignore "RuntimeWarning: Sequential read of iterator was interrupted. Resetting iterator."
@@ -229,7 +239,12 @@ class BaseMeta(BaseDataset):
                 union_geom = make_valid(union_geom)
 
             if union_geom and not union_geom.is_empty:
-                poly = union_geom.intersection(self.footprint)
+                footprint = self.footprint
+                if footprint.bounds[2] > 180:
+                    # footprint crossing the antimeridian: it is in the continuous
+                    # [0, 360] longitude range, so the mask is expressed in the same range
+                    union_geom = geometry_to_lon360(union_geom)
+                poly = union_geom.intersection(footprint)
             else:
                 poly = Polygon()
 
@@ -260,13 +275,41 @@ class BaseMeta(BaseDataset):
     def footprint(self):
         pass
 
+    def _continuous_longitude(self, longitude):
+        """
+        Set `self.cross_antimeridian` from the longitudes of the geolocation grid, as given
+        by the product ([-180, 180]), and return them in a continuous range.
+
+        This has to be done once, when the geolocation grid is read: everything derived from
+        this grid (footprint, approx_transform, interpolators) needs continuous longitudes.
+
+        Parameters
+        ----------
+        longitude: xarray.DataArray or numpy.ndarray
+            longitudes of the geolocation grid, in [-180, 180] range
+
+        Returns
+        -------
+        xarray.DataArray or numpy.ndarray
+            longitudes in [0, 360] range if the footprint cross antimeridian, unchanged otherwise.
+        """
+        self._cross_antimeridian = ((np.max(longitude) - np.min(longitude)) > 180).item()
+        if self._cross_antimeridian:
+            attrs = getattr(longitude, "attrs", {})
+            longitude = longitude % 360
+            if attrs:
+                longitude.attrs.update(attrs)
+        return longitude
+
     @property
     def cross_antimeridian(self):
         """True if footprint cross antimeridian"""
-        return (
-            (np.max(self.geoloc["longitude"]) -
-             np.min(self.geoloc["longitude"])) > 180
-        ).item()
+        if self._cross_antimeridian is None:
+            # reading the geolocation grid sets the flag (see `_continuous_longitude`)
+            geoloc = self.geoloc
+            if self._cross_antimeridian is None:
+                self._continuous_longitude(geoloc["longitude"])
+        return self._cross_antimeridian
 
     @property
     def swath(self):
@@ -312,6 +355,11 @@ class BaseMeta(BaseDataset):
         tuple of np.array or tuple of float
             (longitude, latitude) , with shape depending on `to_grid` keyword.
 
+        Notes
+        -----
+        longitudes are in [-180, 180] range. For a shapely object, if `self.cross_antimeridian` is True,
+        longitudes are in the continuous [0, 360] range (a geometry can't jump from 180 to -180).
+
         See Also
         --------
         xsar.BaseMeta.ll2coords
@@ -369,7 +417,15 @@ class BaseMeta(BaseDataset):
             (xoff, a, b, yoff, d, e) = self.approx_transform.to_gdal()
             return shapely.affinity.affine_transform(shape, (a, b, d, e, xoff, yoff))
         else:
-            return shapely.ops.transform(self.coords2ll, shape)
+
+            def coords2ll_continuous(lines, samples):
+                lon, lat = self.coords2ll(np.asarray(lines), np.asarray(samples))
+                if self.cross_antimeridian:
+                    # keep the geometry in one piece
+                    lon = lon % 360
+                return lon, lat
+
+            return shapely.ops.transform(coords2ll_continuous, shape)
 
     def ll2coords(self, *args):
         """
@@ -404,17 +460,26 @@ class BaseMeta(BaseDataset):
             return self._ll2coords_shapely(args[0])
 
         lon, lat = args
+        lon = np.asarray(lon)
+        lat = np.asarray(lat)
+        
+        cross_antimeridian = self.cross_antimeridian
+        if cross_antimeridian:
+            # define approx transform continuous longitudes
+            lon = lon % 360
 
         # approximation with global inaccurate transform
         line_approx, sample_approx = ~self.approx_transform * (
-            np.asarray(lon),
-            np.asarray(lat),
+            lon,
+            lat
         )
 
         # Theoretical identity. It should be the same, but the difference show the error.
         lon_identity, lat_identity = self.coords2ll(
             line_approx, sample_approx, to_grid=False
         )
+        if cross_antimeridian:
+            lon_identity = lon_identity % 360
         line_identity, sample_identity = ~self.approx_transform * (
             lon_identity,
             lat_identity,


=====================================
src/xsar/radarsat2_dataset.py
=====================================
@@ -40,10 +40,14 @@ class RadarSat2Dataset(BaseDataset):
     resolution: dict, number or string, optional
         resampling dict like `{'line': 20, 'sample': 20}` where 20 is in pixels.
 
-        if a number, dict will be constructed from `{'line': number, 'sample': number}`
+        if a number, it is a size in meters, as for a str, but `sampleSpacing` and `lineSpacing`
+        then keep the full resolution pixel size (a warning is logged): prefer a str.
 
         if str, it must end with 'm' (meters), like '100m'. dict will be computed from sensor pixel size.
 
+        The image is averaged on whole cells: the zeros outside the swath are not counted, and
+        `valid_pixel_fraction` gives the share of each cell inside the swath (0 to 1).
+
     resampling: rasterio.enums.Resampling or str, optional
 
         Only used if `resolution` is not None.
@@ -711,11 +715,12 @@ class RadarSat2Dataset(BaseDataset):
         pass_direction = self.sar_meta.dt.attrs["passDirection"]
         flipped_cases = [("Left", "Ascending"), ("Right", "Descending")]
         if (antenna_pointing, pass_direction) in flipped_cases:
-            new_ds = (
-                ds.copy()
-                .isel(sample=slice(None, None, -1))
-                .assign_coords(sample=ds.sample)
-            )
+            # mirror the coordinates with the last pixel of the geolocation grid
+            # (same flip as the metadata): at reduced resolution, the cells keep
+            # their true centers
+            last = int(round(float(self.sar_meta.geoloc.pixel.max())))
+            flipped = ds.copy().isel(sample=slice(None, None, -1))
+            new_ds = flipped.assign_coords(sample=last - flipped.sample.values)
         else:
             new_ds = ds
         return new_ds
@@ -741,9 +746,12 @@ class RadarSat2Dataset(BaseDataset):
         """
         pass_direction = self.sar_meta.dt.attrs["passDirection"]
         if pass_direction == "Ascending":
-            new_ds = (
-                ds.copy().isel(line=slice(None, None, -1)).assign_coords(line=ds.line)
-            )
+            # mirror the coordinates with the last line of the geolocation grid
+            # (same flip as the metadata): at reduced resolution, the cells keep
+            # their true centers
+            last = int(round(float(self.sar_meta.geoloc.line.max())))
+            flipped = ds.copy().isel(line=slice(None, None, -1))
+            new_ds = flipped.assign_coords(line=last - flipped.line.values)
         else:
             new_ds = ds.copy()
         return new_ds


=====================================
src/xsar/radarsat2_meta.py
=====================================
@@ -76,6 +76,9 @@ class RadarSat2Meta(BaseMeta):
         self.subdatasets = gpd.GeoDataFrame(geometry=[], index=[])
         """Subdatasets as GeodataFrame (empty if single dataset)"""
         self.geoloc = self.dt["geolocationGrid"].to_dataset()
+        # if the footprint cross antimeridian, footprint, approx_transform and interpolators
+        # need continuous longitudes
+        self.geoloc["longitude"] = self._continuous_longitude(self.geoloc["longitude"])
 
         self.orbit_and_attitude = self.dt["orbitAndAttitude"].ds
         self.doppler_centroid = self.dt["imageGenerationParameters"]["doppler"][
@@ -297,8 +300,6 @@ class RadarSat2Meta(BaseMeta):
         """
         resdict = {}
         geoloc = self.geoloc
-        if self.cross_antimeridian:
-            geoloc["longitude"] = geoloc["longitude"] % 360
 
         idx_sample = np.array(geoloc.pixel)
         idx_line = np.array(geoloc.line)


=====================================
src/xsar/rcm_dataset.py
=====================================
@@ -10,7 +10,15 @@ from affine import Affine
 
 from .rcm_meta import RcmMeta
 import numpy as np
-from .utils import timing, map_blocks_coords, BlockingActorProxy, to_lon180, get_glob
+from .utils import (
+    timing,
+    map_blocks_coords,
+    BlockingActorProxy,
+    to_lon180,
+    get_glob,
+    read_cells,
+    read_valid_fraction,
+)
 from scipy.interpolate import RectBivariateSpline, interp1d
 import dask
 import xarray as xr
@@ -45,10 +53,14 @@ class RcmDataset(BaseDataset):
     resolution: dict, number or string, optional
         resampling dict like `{'line': 20, 'sample': 20}` where 20 is in pixels.
 
-        if a number, dict will be constructed from `{'line': number, 'sample': number}`
+        if a number, it is a size in meters, as for a str, but `sampleSpacing` and `lineSpacing`
+        then keep the full resolution pixel size (a warning is logged): prefer a str.
 
         if str, it must end with 'm' (meters), like '100m'. dict will be computed from sensor pixel size.
 
+        The image is averaged on whole cells: the zeros outside the swath are not counted, and
+        `valid_pixel_fraction` gives the share of each cell inside the swath (0 to 1).
+
     resampling: rasterio.enums.Resampling or str, optional
 
         Only used if `resolution` is not None.
@@ -771,6 +783,27 @@ class RcmDataset(BaseDataset):
         """
         load digital_number from tiff files, as an `xarray.Dataset`.
 
+        With `resolution=None`, the files are read lazily at full resolution, in uint16.
+
+        Otherwise, the files are resampled while reading, on a grid of whole cells of
+        `r_line` x `r_sample` pixels (`r` is the cell size in pixels):
+
+        * cell `k` covers the pixels `[k * r, (k + 1) * r)`, and its coordinate is the
+          cell center `k * r + (r - 1) / 2`, in pixels of the full resolution image;
+        * there are `int(size / r)` cells: the pixels left over at the bottom and right
+          edges of the image (less than one cell) are not used;
+        * the pixels at 0 (outside the swath) are not counted: a cell straddling the
+          swath border is the `resampling` mean of its valid pixels only, and a cell
+          without any valid pixel is 0;
+        * the cell values are kept in float32, they are not rounded to integers;
+        * `r` may be non-integer: a pixel cut by a cell edge is weighted by the part
+          of it inside the cell.
+
+        The dataset also holds `valid_pixel_fraction`: the fraction of non-zero pixels in
+        each cell (0: outside the swath, 1: full cell). The swath border is the same in all
+        polarisations: the fraction is computed on the co-polarisation and given for each
+        polarisation.
+
         Parameters
         ----------
         resolution: None, number, str or dict
@@ -781,7 +814,8 @@ class RcmDataset(BaseDataset):
         Returns
         -------
         xarray.Dataset
-            dataset (possibly dual-pol), with basic coords/dims naming convention
+            dataset (possibly dual-pol) with `digital_number` and, if resampled,
+            `valid_pixel_fraction` (dims "pol", "line", "sample")
         """
 
         def _list_tiff_files():
@@ -879,36 +913,20 @@ class RcmDataset(BaseDataset):
                 # resolution = dict(line=resolution / self.dataset['sampleSpacing'].values,
                 #                   sample=resolution / self.dataset['lineSpacing'].values)
 
-            # resample the DN at gdal level, before feeding it to the dataset
+            # resample the DN at gdal level, before feeding it to the dataset.
+            # Whole cells only: the pixels left over at the bottom and right edges
+            # (less than one cell) are not used.
             out_shape = (
                 int(rio.height / resolution["line"]),
                 int(rio.width / resolution["sample"]),
             )
-            out_shape_pol = (1,) + out_shape
             # read resampled array in one chunk, and rechunk
             # this doesn't optimize memory, but total size remain quite small
-
-            if isinstance(resolution["line"], int):
-                # legacy behaviour: winsize is the maximum full image size that can be divided  by resolution (int)
-                winsize = (
-                    0,
-                    0,
-                    rio.width // resolution["sample"] * resolution["sample"],
-                    rio.height // resolution["line"] * resolution["line"],
-                )
-                window = rasterio.windows.Window(*winsize)
-            else:
-                window = None
-
             dn = xr.concat(
                 [
                     xr.DataArray(
                         dask.array.from_array(
-                            rasterio.open(f).read(
-                                out_shape=out_shape_pol,
-                                resampling=resampling,
-                                window=window,
-                            ),
+                            read_cells(f, resolution, out_shape, resampling),
                             chunks=chunks_rio,
                         ),
                         dims=tuple(map_dims.keys()),
@@ -918,17 +936,20 @@ class RcmDataset(BaseDataset):
                 ],
                 "pol",
             ).chunk(chunks)
+            # the swath border is the same in all polarisations: one read, on the
+            # co-polarisation, which has the strongest signal
+            co_pol_file = next(
+                (f for f, p in zip(tiff_files, pols) if p[0] == p[1]),
+                tiff_files[0],
+            )
+            valid_fraction = read_valid_fraction(
+                co_pol_file, resolution, out_shape)
 
-            # create coordinates at box center
+            # coordinates at cell center: cell k covers pixels [k r, (k + 1) r)
             translate = Affine.translation(
                 (resolution["sample"] - 1) / 2, (resolution["line"] - 1) / 2
             )
-            scale = Affine.scale(
-                rio.width // resolution["sample"] *
-                resolution["sample"] / out_shape[1],
-                rio.height // resolution["line"] *
-                resolution["line"] / out_shape[0],
-            )
+            scale = Affine.scale(resolution["sample"], resolution["line"])
             sample, _ = translate * scale * (dn.sample, 0)
             _, line = translate * scale * (0, dn.line)
             dn = dn.assign_coords({"line": line, "sample": sample})
@@ -954,6 +975,19 @@ class RcmDataset(BaseDataset):
         astype = self._dtypes.get(var_name)
         if astype is not None:
             ds = ds.astype(self._dtypes[var_name])
+        if resolution is not None:
+            ds["valid_pixel_fraction"] = xr.DataArray(
+                valid_fraction,
+                dims=("line", "sample"),
+                coords={"line": ds.line, "sample": ds.sample},
+                attrs={
+                    "long_name": "fraction of valid pixels in the cell",
+                    "units": "1",
+                    "comment": "pixels at 0 (outside the swath) are not valid; "
+                    "0: outside the swath, 1: full cell; "
+                    "computed on the co-polarisation, the same for all polarisations",
+                },
+            ).expand_dims(pol=ds.pol.values).copy()
 
         return ds
 
@@ -989,11 +1023,12 @@ class RcmDataset(BaseDataset):
         ].attrs["passDirection"]
         flipped_cases = [("Left", "Ascending"), ("Right", "Descending")]
         if (antenna_pointing, pass_direction) in flipped_cases:
-            new_ds = (
-                ds.copy()
-                .isel(sample=slice(None, None, -1))
-                .assign_coords(sample=ds.sample)
-            )
+            # mirror the coordinates with the last pixel of the geolocation grid
+            # (same flip as the metadata): at reduced resolution, the cells keep
+            # their true centers
+            last = int(round(float(self.sar_meta.geoloc.pixel.max())))
+            flipped = ds.copy().isel(sample=slice(None, None, -1))
+            new_ds = flipped.assign_coords(sample=last - flipped.sample.values)
         else:
             new_ds = ds
         return new_ds
@@ -1019,9 +1054,12 @@ class RcmDataset(BaseDataset):
             "sourceAttributes/orbitAndAttitude/orbitInformation"
         ].attrs["passDirection"]
         if pass_direction == "Ascending":
-            new_ds = (
-                ds.copy().isel(line=slice(None, None, -1)).assign_coords(line=ds.line)
-            )
+            # mirror the coordinates with the last line of the geolocation grid
+            # (same flip as the metadata): at reduced resolution, the cells keep
+            # their true centers
+            last = int(round(float(self.sar_meta.geoloc.line.max())))
+            flipped = ds.copy().isel(line=slice(None, None, -1))
+            new_ds = flipped.assign_coords(line=last - flipped.line.values)
         else:
             new_ds = ds.copy()
         return new_ds


=====================================
src/xsar/rcm_meta.py
=====================================
@@ -90,6 +90,9 @@ class RcmMeta(BaseMeta):
         self.subdatasets = gpd.GeoDataFrame(geometry=[], index=[])
         """Subdatasets as GeodataFrame (empty if single dataset)"""
         self.geoloc = self.dt[self._xpath["geolocationGrid"]].to_dataset()
+        # if the footprint cross antimeridian, footprint, approx_transform and interpolators
+        # need continuous longitudes
+        self.geoloc["longitude"] = self._continuous_longitude(self.geoloc["longitude"])
 
         self.orbit = self.dt[self._xpath["orbit"]].ds
         self.attitude = self.dt[self._xpath["attitude"]].ds
@@ -383,8 +386,6 @@ class RcmMeta(BaseMeta):
         """
         resdict = {}
         geoloc = self.geoloc
-        if self.cross_antimeridian:
-            geoloc["longitude"] = geoloc["longitude"] % 360
 
         idx_sample = np.array(geoloc.pixel)
         idx_line = np.array(geoloc.line)


=====================================
src/xsar/sentinel1_dataset.py
=====================================
@@ -73,10 +73,14 @@ class Sentinel1Dataset(BaseDataset):
     resolution: dict, number or string, optional
         resampling dict like `{'line': 20, 'sample': 20}` where 20 is in pixels.
 
-        if a number, dict will be constructed from `{'line': number, 'sample': number}`
+        if a number, it is a size in meters, as for a str, but `sampleSpacing` and `lineSpacing`
+        then keep the full resolution pixel size (a warning is logged): prefer a str.
 
         if str, it must end with 'm' (meters), like '100m'. dict will be computed from sensor pixel size.
 
+        The image is averaged on whole cells: the zeros outside the swath are not counted, and
+        `valid_pixel_fraction` gives the share of each cell inside the swath (0 to 1).
+
     resampling: rasterio.enums.Resampling or str, optional
 
         Only used if `resolution` is not None.


=====================================
src/xsar/sentinel1_meta.py
=====================================
@@ -250,6 +250,9 @@ class Sentinel1Meta(BaseMeta):
         if self._geoloc is None:
             self._geoloc = self.dt["geolocationGrid"].to_dataset()
             self._geoloc.attrs = {}
+            # if the footprint cross antimeridian, footprint, approx_transform and interpolators
+            # below need continuous longitudes
+            self._geoloc["longitude"] = self._continuous_longitude(self._geoloc["longitude"])
             # compute attributes (footprint, coverage, pixel_size)
             footprint_dict = {}
             for ll in ["longitude", "latitude"]:
@@ -394,8 +397,6 @@ class Sentinel1Meta(BaseMeta):
         """
         resdict = {}
         geoloc = self.geoloc
-        if self.cross_antimeridian:
-            geoloc["longitude"] = geoloc["longitude"] % 360
 
         idx_sample = np.array(geoloc.sample)
         idx_line = np.array(geoloc.line)


=====================================
src/xsar/utils.py
=====================================
@@ -23,6 +23,10 @@ from pathlib import Path
 import fsspec
 import aiohttp
 from lxml import objectify
+from shapely.affinity import translate
+from shapely.geometry import box
+from shapely.ops import unary_union
+from xml.sax.saxutils import escape
 
 logger = logging.getLogger("xsar.utils")
 logger.addHandler(logging.NullHandler())
@@ -135,6 +139,62 @@ def to_lon180(lon):
     return lon
 
 
+def geometry_to_lon360(geom):
+    """
+    Express a lon/lat geometry in the continuous [0, 360] longitude range.
+
+    A footprint crossing the antimeridian is continuous in this range, whereas
+    its longitudes jump by 360 in [-180, 180].
+
+    Parameters
+    ----------
+    geom: shapely.geometry.base.BaseGeometry
+        longitudes in [-180, 180] or [0, 360] range
+
+    Returns
+    -------
+    shapely.geometry.base.BaseGeometry
+        same geometry, where the part with negative longitudes is shifted by +360.
+        A geometry already in [0, 360] is returned unchanged.
+
+    """
+    if geom.is_empty or geom.bounds[0] >= 0:
+        return geom
+    return unary_union(
+        [
+            geom.intersection(box(0, -90, 360, 90)),
+            translate(geom.intersection(box(-180, -90, 0, 90)), xoff=360),
+        ]
+    )
+
+
+def geometry_to_lon180(geom):
+    """
+    Express a lon/lat geometry in the [-180, 180] longitude range.
+
+    Parameters
+    ----------
+    geom: shapely.geometry.base.BaseGeometry
+        longitudes in [0, 360] or [-180, 180] range
+
+    Returns
+    -------
+    shapely.geometry.base.BaseGeometry
+        same geometry, where the part beyond 180 is shifted by -360.
+        If `geom` crosses the antimeridian, the result is split in two parts.
+        A geometry already in [-180, 180] is returned unchanged.
+
+    """
+    if geom.is_empty or geom.bounds[2] <= 180:
+        return geom
+    return unary_union(
+        [
+            geom.intersection(box(-180, -90, 180, 90)),
+            translate(geom.intersection(box(180, -90, 360, 90)), xoff=-360),
+        ]
+    )
+
+
 def haversine(lon1, lat1, lon2, lat2):
     """
     Compute distance in meters, and bearing in degrees from point1 to point2, assuming spherical earth.
@@ -599,6 +659,95 @@ def get_glob(strlist):
     return strglob
 
 
+def _float_vrt(path, nodata):
+    """
+    VRT (XML string) of the first band of `path`, as float32, with a nodata value.
+
+    Declaring a nodata value makes GDAL average the pixels itself, in float32.
+    Without it, GDAL delegates the resampling to the file, in its own dtype
+    (uint16), and the cell means are rounded to the nearest integer.
+    """
+    with rasterio.open(path) as src:
+        width = src.width
+        height = src.height
+    return f"""<VRTDataset rasterXSize="{width}" rasterYSize="{height}">
+  <VRTRasterBand dataType="Float32" band="1">
+    <NoDataValue>{nodata}</NoDataValue>
+    <SimpleSource>
+      <SourceFilename relativeToVRT="0">{escape(str(path))}</SourceFilename>
+      <SourceBand>1</SourceBand>
+    </SimpleSource>
+  </VRTRasterBand>
+</VRTDataset>"""
+
+
+def _read_on_cells(path, resolution, out_shape, resampling, nodata):
+    """
+    Resample `path` on `out_shape` cells of exactly
+    `resolution["line"]` x `resolution["sample"]` pixels, starting at pixel (0, 0).
+
+    The window is cropped to the whole cells, so that cell k covers pixels
+    [k r, (k + 1) r). Non-integer ratios are supported: GDAL weights the pixels
+    cut by a cell edge.
+    """
+    window = rasterio.windows.Window(
+        0,
+        0,
+        out_shape[1] * resolution["sample"],
+        out_shape[0] * resolution["line"],
+    )
+    with rasterio.open(_float_vrt(path, nodata)) as vrt:
+        return vrt.read(1, out_shape=out_shape, window=window, resampling=resampling)
+
+
+def read_cells(path, resolution, out_shape, resampling):
+    """
+    Resample a measurement file on a grid of whole cells.
+
+    Each cell is the `resampling` mean of the valid pixels it covers, in float32.
+    Pixels at 0 (outside the swath) are not counted; a cell without any valid
+    pixel is 0.
+
+    Parameters
+    ----------
+    path: str
+        measurement file
+    resolution: dict
+        cell size in pixels, like `{"line": 100.0, "sample": 100.0}`
+    out_shape: tuple
+        number of cells `(line, sample)`
+    resampling: rasterio.enums.Resampling
+
+    Returns
+    -------
+    numpy.ndarray
+        shape `(1, line, sample)`, float32
+    """
+    cells = _read_on_cells(path, resolution, out_shape, resampling, nodata=0)
+    return cells[np.newaxis]
+
+
+def read_valid_fraction(path, resolution, out_shape):
+    """
+    Fraction of non-zero pixels in each cell of the grid used by `read_cells`.
+
+    It is the mean with the zeros counted divided by the mean without them
+    (= valid pixels / all pixels). For the mean with the zeros counted, the nodata
+    value is -1, which never occurs in the file, so that GDAL still averages in
+    float32.
+
+    Returns
+    -------
+    numpy.ndarray
+        shape `(line, sample)`, float32, 0 outside the swath, 1 for a full cell
+    """
+    average = rasterio.enums.Resampling.average
+    mean_all = _read_on_cells(path, resolution, out_shape, average, nodata=-1)
+    mean_valid = _read_on_cells(path, resolution, out_shape, average, nodata=0)
+    fraction = mean_all / np.where(mean_valid > 0, mean_valid, 1)
+    return np.where(mean_valid > 0, fraction, 0).astype("float32")
+
+
 def safe_dir(filename, path=".", only_exists=False):
     """
     get dir path from safe filename.


=====================================
test/test_antimeridian.py
=====================================
@@ -1,11 +1,13 @@
-
+import geopandas as gpd
 import numpy as np
 import pandas as pd
 import pytest
 import xarray as xr
+from shapely.geometry import box
+from shapely.ops import unary_union
 
-from xsar.base_meta import BaseMeta
-
+from xsar.base_meta import BaseMeta, _ShapefileFeature
+from xsar.utils import geometry_to_lon180, geometry_to_lon360
 
 class DummyMeta(BaseMeta):
     @property
@@ -39,3 +41,75 @@ def test_cross_antimeridian_from_geoloc(longitudes, expected):
     meta = DummyMeta()
     meta.geoloc = xr.Dataset({"longitude": (("x",), np.array(longitudes))})
     assert meta.cross_antimeridian is expected
+
+
+ at pytest.mark.parametrize(
+    "longitudes, expected_flag, expected_longitudes",
+    [
+        ([175.0, 179.0, -179.0], True, [175.0, 179.0, 181.0]),
+        ([-10.0, 0.0, 10.0], False, [-10.0, 0.0, 10.0]),
+    ],
+)
+def test_continuous_longitude(longitudes, expected_flag, expected_longitudes):
+    meta = DummyMeta()
+    lon = xr.DataArray(np.array(longitudes), dims="x", attrs={"units": "degrees"})
+    continuous = meta._continuous_longitude(lon)
+    assert meta.cross_antimeridian is expected_flag
+    np.testing.assert_allclose(continuous.values, expected_longitudes)
+    assert continuous.attrs == {"units": "degrees"}
+
+
+def test_geometry_to_lon360_and_back():
+    # a footprint crossing the antimeridian, given in two parts in [-180, 180]
+    split = unary_union([box(170, -45, 180, -40), box(-180, -45, -175, -40)])
+
+    continuous = geometry_to_lon360(split)
+    assert continuous.geom_type == "Polygon"
+    assert continuous.bounds == (170.0, -45.0, 185.0, -40.0)
+    assert continuous.area == pytest.approx(split.area)
+    # already continuous: unchanged
+    assert geometry_to_lon360(continuous) is continuous
+
+    back = geometry_to_lon180(continuous)
+    assert back.geom_type == "MultiPolygon"
+    assert back.bounds == (-180.0, -45.0, 180.0, -40.0)
+    assert back.area == pytest.approx(split.area)
+    # already in [-180, 180]: unchanged
+    assert geometry_to_lon180(back) is back
+
+    # a geometry far from the antimeridian is never modified
+    europe = box(-5, 45, 10, 50)
+    assert geometry_to_lon180(europe) is europe
+    assert geometry_to_lon360(box(5, 45, 10, 50)).bounds == (5.0, 45.0, 10.0, 50.0)
+
+
+class DummyMetaWithFootprint(DummyMeta):
+    def __init__(self, footprint):
+        super().__init__()
+        self._footprint = footprint
+        self._mask_features = {}
+        self._mask_intersecting_geometries = {}
+        self._mask_geometry = {}
+
+    @property
+    def footprint(self):
+        return self._footprint
+
+
+def test_get_mask_on_both_sides_of_antimeridian():
+    # footprint crossing the antimeridian, in the continuous [0, 360] range
+    meta = DummyMetaWithFootprint(box(176, -42, 183, -37))
+    # land on both sides, as given by a [-180, 180] coastline file
+    west_of_180 = box(178, -40, 179, -39)
+    east_of_180 = box(-179, -40, -178, -39)  # i.e. [181, 182]
+    outside = box(-70, -40, -69, -39)
+    meta.set_mask_feature(
+        "land_test",
+        _ShapefileFeature(gpd.GeoSeries([west_of_180, east_of_180, outside])),
+    )
+
+    mask = meta.get_mask("land_test")
+
+    assert mask.is_valid
+    assert mask.area == pytest.approx(2.0)
+    assert mask.bounds == (178.0, -40.0, 182.0, -39.0)


=====================================
test/test_antimeridian_sentinel1.py
=====================================
@@ -0,0 +1,81 @@
+"""
+Sentinel1Meta on a geolocation grid crossing the antimeridian, without any SAFE.
+
+The grid covers about 179E..181E (written 179 ... 179.8, -180 ... -179 as in the product),
+40S..38S, tilted like a real orbit. Before the fix: footprint was a band around the globe,
+approx_transform was meaningless, cross_antimeridian changed after the first coords2ll call,
+the land mask was empty and the ground heading was wrong by about 100 deg.
+"""
+import geopandas as gpd
+import numpy as np
+import pytest
+import xarray as xr
+from shapely.geometry import box
+
+from xsar.base_meta import _ShapefileFeature
+from xsar.sentinel1_meta import Sentinel1Meta
+
+
+class _FakeNode:
+    """Stands for the 'geolocationGrid' node of the datatree."""
+
+    def __init__(self, ds):
+        self.ds = ds
+
+    def to_dataset(self):
+        return self.ds.copy(deep=True)
+
+
+ at pytest.fixture
+def meta():
+    lines = np.arange(0.0, 1001.0, 100.0)
+    samples = np.arange(0.0, 1001.0, 100.0)
+    L, S = np.meshgrid(lines, samples, indexing="ij")
+    lon = 179.0 + S * 0.002 - L * 0.0005
+    lon = (lon + 180) % 360 - 180  # as given by the product
+    lat = -40.0 + L * 0.002
+    grid = xr.Dataset(
+        {
+            "longitude": (("line", "sample"), lon),
+            "latitude": (("line", "sample"), lat),
+            "height": (("line", "sample"), np.zeros_like(lon)),
+        },
+        coords={"line": lines, "sample": samples},
+    )
+    m = Sentinel1Meta.__new__(Sentinel1Meta)
+    m.dt = {"geolocationGrid": _FakeNode(grid)}
+    m.multidataset = False
+    m.xsd_definitions = {}
+    m._geoloc = None
+    m._mask_features, m._mask_intersecting_geometries, m._mask_geometry = {}, {}, {}
+    # island astride 180, stored in two pieces as in a [-180, 180] coastline file
+    island = [box(179.8, -39.2, 180.0, -38.8), box(-180.0, -39.2, -179.8, -38.8)]
+    m.set_mask_feature("island", _ShapefileFeature(gpd.GeoSeries(island)))
+    return m
+
+
+def test_footprint_and_approx_transform(meta):
+    assert meta.cross_antimeridian is True
+    assert meta.footprint.area == pytest.approx(4.0)
+    lon, _ = meta.approx_transform * (0, 1000)
+    assert (lon - 181 + 180) % 360 - 180 == pytest.approx(0, abs=1e-6)
+
+
+def test_flag_does_not_change(meta):
+    lon, _ = meta.coords2ll(0, 1000)
+    assert lon == pytest.approx(-179.0)
+    assert meta.cross_antimeridian is True
+
+
+def test_ll2coords(meta):
+    line, sample = meta.ll2coords(-179.75, -39.0)
+    assert (line, sample) == (pytest.approx(500), pytest.approx(750))
+
+
+def test_land_mask_astride_antimeridian(meta):
+    assert meta.get_mask("island").area == pytest.approx(0.16)
+
+
+def test_ground_heading(meta):
+    heading = meta.coords2heading(np.array([500.0]), np.array([500.0]), approx=True)
+    assert float(np.ravel(heading)[0]) == pytest.approx(-11.0, abs=0.05)


=====================================
test/test_flip_coords.py
=====================================
@@ -0,0 +1,111 @@
+"""RS2 and RCM images flipped by xsar: each cell must be at its coordinate.
+
+xsar flips the lines (ascending pass) or the samples (left-looking ascending or
+right-looking descending pass) so that the line increases with the azimuth time and
+the sample with the range. At reduced resolution, the pixels left over (less than
+one cell) are at the end of the file, so at the start of a flipped axis.
+
+For cells at both ends of the flipped axis, the cell value is compared with the rms of
+the non-zero pixels found at its coordinate in the full resolution image."""
+
+import glob
+import logging
+
+import numpy as np
+import pytest
+import rasterio
+from rasterio.windows import Window
+
+import xsar
+
+logging.getLogger("xsar").setLevel(logging.WARNING)
+
+PRODUCTS = {
+    # right-looking, descending: samples flipped
+    "rcm_samples_flipped": (
+        xsar.RcmDataset,
+        "RCM1_OK1050603_PK1050605_1_SC50MB_20200214_115905_HH_HV_Z010",
+        "imagery/*_{pol}.tif",
+    ),
+    # right-looking, ascending: lines flipped
+    "rcm_lines_flipped": (
+        xsar.RcmDataset,
+        "RCM1_OK2460179_PK2462841_1_SCLND_20230301_072431_VV_VH_GRD",
+        "imagery/*_{pol}.tif",
+    ),
+    # right-looking, descending: samples flipped
+    "rs2_samples_flipped": (
+        xsar.RadarSat2Dataset,
+        "RS2_OK135107_PK1187782_DK1151894_SCWA_20220407_182127_VV_VH_SGF",
+        "imagery_{pol}.tif",
+    ),
+}
+
+
+def fixed_rs2_reader():
+    from xradarsat2 import radarSat2_xarray_reader
+
+    return hasattr(radarSat2_xarray_reader, "read_cells")
+
+
+def file_start(coord, r, flipped, last):
+    """First file pixel of the cell centered on `coord` (xsar convention)."""
+    start = int(round(coord - (r - 1) / 2))
+    return last - (start + int(r) - 1) if flipped else start
+
+
+def rms_of_valid_pixels(pixels):
+    valid = pixels[pixels > 0].astype(np.float64)
+    return np.sqrt(np.mean(valid**2)) if valid.size else 0
+
+
+ at pytest.mark.parametrize("case", list(PRODUCTS))
+def test_cells_are_at_their_coordinates(case):
+    cls, name, pattern = PRODUCTS[case]
+    if cls is xsar.RadarSat2Dataset and not fixed_rs2_reader():
+        pytest.skip("needs xradarsat2 with the fixed resampled read")
+    path = xsar.get_test_file(name)
+    sar = cls(path, resolution="1000m")
+    ds = sar.dataset
+    pol = str(ds.pol.values[0])
+    dn = ds.digital_number.sel(pol=pol).values
+    tiff = glob.glob(f"{path}/{pattern.format(pol=pol)}")[0]
+    with rasterio.open(tiff) as src:
+        height, width = src.shape
+    flipped = {"line": sar.sar_meta.lines_flipped, "sample": sar.sar_meta.samples_flipped}
+    last = {"line": height - 1, "sample": width - 1}
+    r = {d: float(ds[d].values[1] - ds[d].values[0]) for d in ("line", "sample")}
+    assert flipped["line"] or flipped["sample"]
+
+    axis = "sample" if flipped["sample"] else "line"
+    other = "line" if axis == "sample" else "sample"
+    n = ds.sizes[axis]
+    k = ds.sizes[other] // 2
+    cells = list(range(5, 15)) + list(range(n - 15, n - 5))
+    with rasterio.open(tiff) as src:
+        for q in cells:
+            index = {axis: q, other: k}
+            start = {
+                d: file_start(ds[d].values[index[d]], r[d], flipped[d], last[d])
+                for d in ("line", "sample")
+            }
+            pixels = src.read(
+                1,
+                window=Window(start["sample"], start["line"], int(r["sample"]), int(r["line"])),
+            )
+            np.testing.assert_allclose(
+                dn[index["line"], index["sample"]],
+                rms_of_valid_pixels(pixels),
+                rtol=1e-5,
+                err_msg=f"{case}: cell {index}",
+            )
+
+
+ at pytest.mark.parametrize("case", ["rcm_samples_flipped", "rcm_lines_flipped"])
+def test_full_resolution_coordinates_unchanged(case):
+    """At full resolution, the flipped coordinates are still 0, 1, 2, ..."""
+    cls, name, _ = PRODUCTS[case]
+    ds = cls(xsar.get_test_file(name)).dataset
+
+    np.testing.assert_array_equal(ds.line, np.arange(ds.sizes["line"]))
+    np.testing.assert_array_equal(ds.sample, np.arange(ds.sizes["sample"]))


=====================================
test/test_resampled_read_rcm.py
=====================================
@@ -0,0 +1,134 @@
+"""End-to-end tests of the resampled read of RCM products (`RcmDataset.load_digital_number`).
+
+Test product: RCM1 ScanSAR 50 m (SC50MB) 2020-02-14, 19 127 lines x 18 042 samples
+of 20 m, HH and HV. At 1000 m, a cell is 50 x 50 pixels: 382 x 360 cells.
+The corners of the image are outside the swath (zeros).
+
+The cells are read in the order of the tiff files (before the flips done by xsar),
+and compared with the pixels of the tiff files, recomputed with numpy."""
+
+import glob
+import logging
+
+import numpy as np
+import pytest
+import rasterio
+from rasterio.windows import Window
+
+import xsar
+
+PRODUCT = "RCM1_OK1050603_PK1050605_1_SC50MB_20200214_115905_HH_HV_Z010"
+CHUNKS = {"line": 5000, "sample": 5000}
+CELL = 50  # pixels per cell at 1000 m
+
+logging.getLogger("xsar").setLevel(logging.WARNING)
+
+
+ at pytest.fixture(scope="module")
+def product():
+    return xsar.get_test_file(PRODUCT)
+
+
+ at pytest.fixture(scope="module")
+def rcm(product):
+    return xsar.RcmDataset(product, resolution="1000m")
+
+
+ at pytest.fixture(scope="module")
+def at_1000m(rcm):
+    return rcm.load_digital_number(resolution="1000m", chunks=dict(CHUNKS))
+
+
+def pixels_of_cell(product, pol, i, j):
+    """The 50 x 50 full resolution pixels of cell (i, j)."""
+    path = glob.glob(f"{product}/imagery/*_{pol}.tif")[0]
+    with rasterio.open(path) as src:
+        return src.read(1, window=Window(CELL * j, CELL * i, CELL, CELL))
+
+
+def rms_of_valid_pixels(pixels):
+    valid = pixels[pixels > 0].astype(np.float64)
+    return np.sqrt(np.mean(valid**2)) if valid.size else 0
+
+
+def test_grid_at_1000m(at_1000m):
+    """19 127 x 18 042 pixels of 20 m at 1000 m: 382 x 360 whole cells of 50 x 50 pixels.
+
+    Cell coordinates are the cell centers: 24.5 for the first cell, and
+    381 x 50 + 24.5 = 19 074.5 (line), 359 x 50 + 24.5 = 17 974.5 (sample) for the last.
+    The 27 last lines and 42 last samples (less than one cell) are not used."""
+    ds = at_1000m
+
+    assert ds.sizes["line"] == 382
+    assert ds.sizes["sample"] == 360
+    assert ds.line[0] == 24.5
+    assert ds.line[-1] == 19074.5
+    assert ds.sample[0] == 24.5
+    assert ds.sample[-1] == 17974.5
+    assert ds.digital_number.dtype == np.float32
+    assert ds.valid_pixel_fraction.dtype == np.float32
+    assert ds.valid_pixel_fraction.dims == ("pol", "line", "sample")
+    assert ds.valid_pixel_fraction.attrs["units"] == "1"
+
+
+def test_four_cells_checked_by_hand(at_1000m):
+    """Four cells of the scene, with their values (rms of the valid pixels):
+
+    * corner cell (0, 0), outside the swath: 0, valid_pixel_fraction 0;
+    * last cell (381, 359), outside the swath too: 0, valid_pixel_fraction 0;
+    * cell in the middle of the scene (191, 180), full: HH 4791.75, HV 1494.51;
+    * cell (379, 226) on the swath border: 1270 valid pixels out of 2500,
+      valid_pixel_fraction 0.508, HH 16921.15, HV 6852.39."""
+    ds = at_1000m
+    hh = ds.digital_number.sel(pol="HH").values
+    hv = ds.digital_number.sel(pol="HV").values
+    fraction = ds.valid_pixel_fraction.sel(pol="HH").values
+
+    assert hh[0, 0] == 0
+    assert fraction[0, 0] == 0
+    assert hh[381, 359] == 0
+    assert fraction[381, 359] == 0
+    np.testing.assert_allclose(hh[191, 180], 4791.75, atol=0.01)
+    np.testing.assert_allclose(hv[191, 180], 1494.51, atol=0.01)
+    np.testing.assert_allclose(fraction[191, 180], 1)
+    np.testing.assert_allclose(hh[379, 226], 16921.15, atol=0.01)
+    np.testing.assert_allclose(hv[379, 226], 6852.39, atol=0.01)
+    np.testing.assert_allclose(fraction[379, 226], 0.508, atol=1e-6)
+
+
+def test_any_cell_is_the_rms_of_its_own_pixels(at_1000m, product):
+    """Same check on 20 cells straddling the swath border and 20 cells taken at random:
+    each cell is the rms of the non-zero pixels it covers, and valid_pixel_fraction
+    the fraction of these pixels (the same in HH and HV)."""
+    ds = at_1000m
+    fraction = ds.valid_pixel_fraction.sel(pol="HH").values
+    n, m = fraction.shape
+    rng = np.random.default_rng(0)
+    border = np.argwhere((fraction > 0) & (fraction < 1))
+    cells = [tuple(c) for c in border[rng.choice(len(border), 20, replace=False)]]
+    cells += [(rng.integers(n), rng.integers(m)) for _ in range(20)]
+
+    np.testing.assert_array_equal(ds.valid_pixel_fraction.sel(pol="HV"), fraction)
+    for pol in ["HH", "HV"]:
+        dn = ds.digital_number.sel(pol=pol).values
+        for i, j in cells:
+            pixels = pixels_of_cell(product, pol, i, j)
+            np.testing.assert_allclose(
+                dn[i, j],
+                rms_of_valid_pixels(pixels),
+                rtol=1e-5,
+                err_msg=f"{pol} cell {(i, j)}",
+            )
+            np.testing.assert_allclose(
+                fraction[i, j],
+                np.mean(pixels > 0),
+                atol=1e-6,
+                err_msg=f"{pol} cell {(i, j)}",
+            )
+
+
+def test_valid_pixel_fraction_is_in_the_xsar_dataset(rcm):
+    ds = rcm.dataset
+
+    assert ds.valid_pixel_fraction.dims == ("pol", "line", "sample")
+    assert ds.valid_pixel_fraction.shape == ds.digital_number.shape



View it on GitLab: https://salsa.debian.org/debian-gis-team/xsar/-/compare/481486f43daf9595eaf918de64f61c7b3784a452...ad66f56e920b593e845659efa1fda87240e03bf3

-- 
View it on GitLab: https://salsa.debian.org/debian-gis-team/xsar/-/compare/481486f43daf9595eaf918de64f61c7b3784a452...ad66f56e920b593e845659efa1fda87240e03bf3
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-grass-devel/attachments/20261122/72fe78e1/attachment-0001.htm>


More information about the Pkg-grass-devel mailing list