[Git][debian-gis-team/xarray-safe-s1][upstream] New upstream version 2026.11.18

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



Antonio Valentino pushed to branch upstream at Debian GIS Project / xarray-safe-s1


Commits:
bfb209ae by Antonio Valentino at 2026-11-22T11:18:32+00:00
New upstream version 2026.11.18
- - - - -


9 changed files:

- .github/workflows/ci.yaml
- .github/workflows/publish.yml
- .github/workflows/upstream-dev.yaml
- + docs/examples/resampled_read.ipynb
- docs/examples/simple_tutorial.ipynb
- docs/index.rst
- safe_s1/reader.py
- + test/test_resampled_read.py
- + test/test_resampled_read_product.py


Changes:

=====================================
.github/workflows/ci.yaml
=====================================
@@ -23,7 +23,7 @@ jobs:
     outputs:
       triggered: ${{ steps.detect-trigger.outputs.trigger-found }}
     steps:
-      - uses: actions/checkout at v6
+      - uses: actions/checkout at v7
         with:
           fetch-depth: 2
       - uses: xarray-contrib/ci-trigger at v1
@@ -50,7 +50,7 @@ jobs:
 
     steps:
       - name: Checkout the repository
-        uses: actions/checkout at v6
+        uses: actions/checkout at v7
         with:
           # need to fetch all tags to get a correct version
           fetch-depth: 0 # fetch all branches and tags
@@ -62,7 +62,7 @@ jobs:
           echo "CONDA_ENV_FILE=ci/requirements/environment.yaml" >> $GITHUB_ENV
 
       - name: Setup micromamba
-        uses: mamba-org/setup-micromamba at v2
+        uses: mamba-org/setup-micromamba at v3
         with:
           environment-file: ${{ env.CONDA_ENV_FILE }}
           environment-name: xarray-safe-s1-tests


=====================================
.github/workflows/publish.yml
=====================================
@@ -12,9 +12,9 @@ jobs:
       contents: "read"
       id-token: "write"
     steps:
-      - uses: actions/checkout at v6
+      - uses: actions/checkout at v7
       - name: Set up Python
-        uses: actions/setup-python at v6
+        uses: actions/setup-python at v7
         with:
           python-version: "3.x"
       - name: Install dependencies
@@ -28,7 +28,7 @@ jobs:
           twine check dist/*
           pip install dist/*.whl
       - name: Publish to PyPI
-        uses: pypa/gh-action-pypi-publish at ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e
+        uses: pypa/gh-action-pypi-publish at 7245906fb61fa33a13554f9d5fb856fe61758086
         with:
           password: ${{ secrets.pypi_token }}
           repository_url: https://upload.pypi.org/legacy/


=====================================
.github/workflows/upstream-dev.yaml
=====================================
@@ -21,7 +21,7 @@ jobs:
     outputs:
       triggered: ${{ steps.detect-trigger.outputs.trigger-found }}
     steps:
-      - uses: actions/checkout at v6
+      - uses: actions/checkout at v7
         with:
           fetch-depth: 2
       - uses: xarray-contrib/ci-trigger at v1.2
@@ -55,13 +55,13 @@ jobs:
 
     steps:
       - name: checkout the repository
-        uses: actions/checkout at v6
+        uses: actions/checkout at v7
         with:
           # need to fetch all tags to get a correct version
           fetch-depth: 0 # fetch all branches and tags
 
       - name: set up conda environment
-        uses: mamba-org/setup-micromamba at v2
+        uses: mamba-org/setup-micromamba at v3
         with:
           environment-file: ci/requirements/environment.yaml
           environment-name: tests


=====================================
docs/examples/resampled_read.ipynb
=====================================
@@ -0,0 +1,195 @@
+{
+ "cells": [
+  {
+   "cell_type": "markdown",
+   "id": "71376320",
+   "metadata": {},
+   "source": [
+    "# Reading at lower resolution\n",
+    "\n",
+    "What does `load_digital_number(resolution=\"1000m\")` actually give you?\n",
+    "Let's open the test product at 1 km and check a few cells by hand."
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "da5c0f22",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "import os\n",
+    "import warnings\n",
+    "\n",
+    "import numpy as np\n",
+    "import rasterio\n",
+    "from rasterio.windows import Window\n",
+    "\n",
+    "from safe_s1 import Sentinel1Reader, sentinel1_xml_mappings\n",
+    "from safe_s1.reader import _float_vrt\n",
+    "\n",
+    "warnings.filterwarnings(\"ignore\", category=rasterio.errors.NotGeoreferencedWarning)\n",
+    "\n",
+    "filename = sentinel1_xml_mappings.get_test_file(\n",
+    "    \"S1A_IW_GRDH_1SDV_20170907T103020_20170907T103045_018268_01EB76_Z010.SAFE\"\n",
+    ")\n",
+    "reader = Sentinel1Reader(name=filename)\n",
+    "res, ds = reader.load_digital_number(\n",
+    "    resolution=\"1000m\",\n",
+    "    chunks={\"line\": 5000, \"sample\": 5000},\n",
+    ")\n",
+    "ds"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "b837a686",
+   "metadata": {},
+   "source": [
+    "## Cells of 100 x 100 pixels\n",
+    "\n",
+    "The pixels are 10 m, so a 1 km cell is 100 x 100 pixels.\n",
+    "The image is 16 778 lines long: that makes 167 whole cells, and the last 78 lines are left out.\n",
+    "\n",
+    "Cell `k` covers pixels `100 k` to `100 k + 99`, and its coordinate is its center:\n",
+    "49.5, 149.5, 249.5..."
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "321bd4e2",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "ds.line.values[:3], ds.line.values[-1]"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "698e8899",
+   "metadata": {},
+   "source": [
+    "## One cell, by hand\n",
+    "\n",
+    "Let's take cell (83, 125), in the middle of the scene, read its 100 x 100 pixels\n",
+    "in the measurement file, and compute their rms (sigma0 goes with DN², so the rms of the DN\n",
+    "is the DN of the mean intensity). Same number:"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "08f8232e",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "vv_file = os.path.join(reader.path, reader.files[\"measurement\"].iloc[0])\n",
+    "\n",
+    "with rasterio.open(vv_file) as src:\n",
+    "    pixels = src.read(1, window=Window(125 * 100, 83 * 100, 100, 100)).astype(float)\n",
+    "\n",
+    "print(\"by hand:\", np.sqrt(np.mean(pixels**2)).round(2))\n",
+    "print(\"read:   \", ds.digital_number.sel(pol=\"VV\").values[83, 125].round(2))"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "99e4d0a5",
+   "metadata": {},
+   "source": [
+    "## The edge of the swath\n",
+    "\n",
+    "Outside the swath, the file holds zeros. This product starts with 5 lines and 5 columns of them:"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "dce9bc7b",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "with rasterio.open(vv_file) as src:\n",
+    "    corner = src.read(1, window=Window(0, 0, 100, 100)).astype(float)\n",
+    "\n",
+    "corner[:8, :8].astype(int)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "513ce155",
+   "metadata": {},
+   "source": [
+    "These zeros are not signal, so they are left out of the mean: the corner cell is the rms of its\n",
+    "95 x 95 real pixels. `valid_pixel_fraction` tells how much of the cell is inside the swath,\n",
+    "here 95 x 95 / 100 x 100 = 0.9025. Handy to keep only full cells: `ds.where(ds.valid_pixel_fraction == 1)`."
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "c405cd6d",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "valid = corner > 0\n",
+    "print(\"by hand:       \", np.sqrt(np.mean(corner[valid] ** 2)).round(2))\n",
+    "print(\"read:          \", ds.digital_number.sel(pol=\"VV\").values[0, 0].round(2))\n",
+    "print(\"valid_pixel_fraction:\", ds.valid_pixel_fraction.sel(pol=\"VV\").values[0, 0])"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "201cc1a4",
+   "metadata": {},
+   "source": [
+    "## How it's done\n",
+    "\n",
+    "The file is uint16. Under the hood, safe_s1 hands GDAL a tiny VRT that says\n",
+    "\"read this file as float32, and 0 means no data\":"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "3eaba7a9",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "print(_float_vrt(vv_file, nodata=0))"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "acff5d4b",
+   "metadata": {},
+   "source": [
+    "GDAL then averages each cell itself, in float32 (no rounding to integers) and skipping the zeros.\n",
+    "The read window stops at the last whole cell, so every cell is exactly 100 x 100 pixels.\n",
+    "\n",
+    "`valid_pixel_fraction` comes from two averages of the same cell: one counting the zeros, one without.\n",
+    "Their ratio is the share of valid pixels.\n",
+    "\n",
+    "For non-integer cells (an EW product at 40 m read at `\"100m\"` gives 2.5 pixels),\n",
+    "a pixel cut by the cell edge counts for the part of it inside the cell.\n",
+    "All the details are in [load_digital_number](../api.rst#safe_s1.Sentinel1Reader.load_digital_number)."
+   ]
+  }
+ ],
+ "metadata": {
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}


=====================================
docs/examples/simple_tutorial.ipynb
=====================================
@@ -326,6 +326,16 @@
     "dn"
    ]
   },
+  {
+   "cell_type": "markdown",
+   "id": "1fc45159-ddc7-4836-8d14-5d67a68df438",
+   "metadata": {},
+   "source": [
+    "The image is resampled on whole cells of 1000 m (100 x 100 pixels here): the pixels at 0, outside the swath, are not counted, and the cell values are kept in float32. ",
+    "The `valid_pixel_fraction` variable gives the fraction of valid pixels in each cell (0: outside the swath, 1: full cell). ",
+    "See [load_digital_number](../api.rst#safe_s1.Sentinel1Reader.load_digital_number) for the details of the grid."
+   ]
+  },
   {
    "cell_type": "markdown",
    "id": "daed8449-c296-4b76-8934-19c297430a67",


=====================================
docs/index.rst
=====================================
@@ -32,6 +32,7 @@ Examples
     Don't use them for real science !
 
 * :doc:`examples/simple_tutorial`
+* :doc:`examples/resampled_read`
 
 
 Reference
@@ -61,6 +62,7 @@ Last documentation build: |today|
    :caption: Examples
 
    examples/simple_tutorial
+   examples/resampled_read
 
 
 .. toctree::


=====================================
safe_s1/reader.py
=====================================
@@ -1,6 +1,7 @@
 import logging
 import os
 import re
+from xml.sax.saxutils import escape
 
 import dask
 import fsspec
@@ -16,6 +17,95 @@ from safe_s1 import sentinel1_xml_mappings
 from safe_s1.xml_parser import XmlParser
 
 
+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")
+
+
 class Sentinel1Reader:
     def __init__(self, name, backend_kwargs=None):
         logging.debug("input name: %s", name)
@@ -127,17 +217,53 @@ class Sentinel1Reader:
         self, resolution=None, chunks=None, resampling=rasterio.enums.Resampling.rms
     ):
         """
-        load digital_number from self.sar_meta.files['measurement'], as an `xarray.Dataset`.
+        Load the digital numbers of the measurement files (all polarisations) 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 (e.g. 40 m pixels at "100m" give 2.5 pixels): 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). Since IPF 2.90, the pixels outside
+        the swath are set to 0 by the IPF, the same in all polarisations: the fraction is
+        computed on the co-polarisation (VV or HH) and given for each polarisation.
+        Before IPF 2.90, the near range border holds low non-zero values, counted as valid.
 
         Parameters
         ----------
         resolution: None, numbers.Number, str or dict
+            cell size, None by default:
+
+            * None: full resolution, no resampling;
+            * str ending with "m", like "1000m": size in meters, converted to pixels with
+              `pixel_line_m` and `pixel_sample_m`;
+            * number: size in meters, as for a str;
+            * dict like `{"line": 100, "sample": 100}`: size in pixels.
+        chunks: dict
+            dask chunks, with keys "line" and "sample", like `{"line": 5000, "sample": 5000}`.
+            A "pol" key is set to 1.
         resampling: rasterio.enums.Resampling
+            mean used for the cells, only with a `resolution`. `rasterio.enums.Resampling.rms` by default.
 
         Returns
         -------
-        (float, xarray.Dataset)
-            tuple that contains resolution and dataset (possibly dual-pol), with basic coords/dims naming convention
+        (float or None, xarray.Dataset)
+
+            * the resolution in meters if `resolution` is a str, None otherwise;
+            * dataset with `digital_number` and, if resampled, `valid_pixel_fraction`
+              (dims "pol", "line", "sample").
         """
 
         def get_glob(strlist):
@@ -240,36 +366,20 @@ class Sentinel1Reader:
                 # 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()),
@@ -281,15 +391,20 @@ class Sentinel1Reader:
                 ],
                 "pol",
             ).chunk(chunks)
+            # the swath border is the same in all polarisations (zeros set by the
+            # IPF): one read, on the co-polarisation, which has the strongest signal
+            pols = [str(p) for p in self.manifest_attrs["polarizations"]]
+            co_pol_file = next(
+                (f for f, p in zip(files_measurement, pols) if p[0] == p[1]),
+                files_measurement[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})
@@ -319,6 +434,23 @@ class Sentinel1Reader:
         astype = _dtypes.get(var_name)
         if astype is not None:
             ds = ds.astype(_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 res, ds
 


=====================================
test/test_resampled_read.py
=====================================
@@ -0,0 +1,137 @@
+"""Resampled read (`resolution` given), on small synthetic GeoTIFFs.
+
+Each test is a concrete case met with Sentinel-1 products, with the expected values
+computed by hand in the docstring:
+
+* an IW GRDH image of 16 778 lines read at 1000 m: the last cell must hold its own lines;
+* an EW image (40 m pixels) read at 100 m: cells of 2.5 pixels;
+* a cell straddling the swath border: the zeros outside the swath must not darken it;
+* a low wind HV cell: the mean must not be rounded to an integer.
+"""
+
+import warnings
+
+import numpy as np
+import pytest
+import rasterio
+from rasterio.enums import Resampling
+
+from safe_s1.reader import read_cells, read_valid_fraction
+
+warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
+
+
+def write_tiff(path, array):
+    with rasterio.open(
+        path,
+        "w",
+        driver="GTiff",
+        height=array.shape[0],
+        width=array.shape[1],
+        count=1,
+        dtype=array.dtype,
+    ) as dst:
+        dst.write(array, 1)
+    return str(path)
+
+
+def line_numbers(height, width):
+    """Image whose pixels hold their line number + 1 (0 would be read as outside the swath)."""
+    return np.repeat(np.arange(1, height + 1, dtype=np.uint16)[:, None], width, axis=1)
+
+
+def test_last_cell_of_an_iw_image_holds_its_own_lines(tmp_path):
+    """IW GRDH image of 16 778 lines of 10 m, read at 1000 m: 167 cells of 100 lines.
+
+    Cell k holds lines 100 k to 100 k + 99, so with pixels = line number + 1:
+    first cell 50.5, last cell (lines 16 600 to 16 699) 16 650.5.
+    The 78 last lines (less than one cell) are not used."""
+    path = write_tiff(tmp_path / "iw.tif", line_numbers(16778, 20))
+    resolution = {"line": 100.0, "sample": 10.0}
+
+    cells = read_cells(path, resolution, (167, 2), Resampling.average)[0]
+
+    assert cells[0, 0] == 50.5
+    assert cells[-1, 0] == 16650.5
+
+
+def test_ew_image_read_at_100m_has_cells_of_two_and_a_half_pixels(tmp_path):
+    """EW image (40 m pixels) read at 100 m: 2.5 pixels per cell.
+
+    The pixels hold their sample number + 1. The pixel cut by a cell edge counts
+    for the part of it inside the cell:
+    cell 0 = samples 0, 1 and half of 2 = (1 + 2 + 0.5 x 3) / 2.5 = 1.8
+    cell 1 = half of 2, 3 and 4 = (0.5 x 3 + 4 + 5) / 2.5 = 4.2
+    cell 2 = 5, 6 and half of 7 = (6 + 7 + 0.5 x 8) / 2.5 = 6.8
+
+    1003 samples give 401 cells, the last one (cell 400) on samples 1000, 1001 and
+    half of 1002 = (1001 + 1002 + 0.5 x 1003) / 2.5 = 1001.8."""
+    path = write_tiff(tmp_path / "ew.tif", line_numbers(1003, 10).T.copy())
+    resolution = {"line": 2.5, "sample": 2.5}
+
+    cells = read_cells(path, resolution, (4, 401), Resampling.average)[0]
+
+    np.testing.assert_allclose(cells[0, :3], [1.8, 4.2, 6.8], rtol=1e-6)
+    np.testing.assert_allclose(cells[0, -1], 1001.8, rtol=1e-6)
+
+
+ at pytest.mark.parametrize("border", ["far_range", "end_of_datatake"])
+def test_cell_across_the_swath_border_is_not_darkened(tmp_path, border):
+    """Sea at DN = 50, and the swath ends at pixel 135 (zeros after it), either in
+    range (far range) or in azimuth (end of the datatake). Cells of 10 pixels.
+
+    Cell 13 (pixels 130 to 139) is half in the swath: its value is the sea value, 50,
+    and its valid_pixel_fraction 0.5. Cells 14 to 19 are outside the swath: 0."""
+    array = np.full((200, 200), 50, dtype=np.uint16)
+    array[:, 135:] = 0
+    if border == "end_of_datatake":
+        array = array.T.copy()
+    path = write_tiff(tmp_path / "border.tif", array)
+    resolution = {"line": 10.0, "sample": 10.0}
+
+    cells = read_cells(path, resolution, (20, 20), Resampling.rms)[0]
+    fraction = read_valid_fraction(path, resolution, (20, 20))
+    if border == "end_of_datatake":
+        cells = cells.T
+        fraction = fraction.T
+
+    np.testing.assert_allclose(cells[:, 13], 50)
+    np.testing.assert_allclose(fraction[:, 13], 0.5)
+    np.testing.assert_allclose(cells[:, :13], 50)
+    np.testing.assert_allclose(fraction[:, :13], 1)
+    np.testing.assert_array_equal(cells[:, 14:], 0)
+    np.testing.assert_array_equal(fraction[:, 14:], 0)
+
+
+def test_valid_pixel_fraction_of_an_ew_cell_across_the_swath_border(tmp_path):
+    """EW at 100 m (2.5 pixels per cell), the swath ends at sample 136.
+
+    Cell 54 covers samples 135 to 137.5: pixel 135 is valid, pixel 136 and half of
+    pixel 137 are outside the swath. 1 valid pixel out of 2.5: valid_pixel_fraction = 0.4.
+    Its value is still the sea value, 50."""
+    array = np.full((200, 200), 50, dtype=np.uint16)
+    array[:, 136:] = 0
+    path = write_tiff(tmp_path / "border.tif", array)
+    resolution = {"line": 2.5, "sample": 2.5}
+
+    cells = read_cells(path, resolution, (80, 80), Resampling.rms)[0]
+    fraction = read_valid_fraction(path, resolution, (80, 80))
+
+    np.testing.assert_allclose(cells[:, 54], 50)
+    np.testing.assert_allclose(fraction[:, 54], 0.4, rtol=1e-6)
+    np.testing.assert_allclose(fraction[:, 53], 1)
+    np.testing.assert_array_equal(fraction[:, 55], 0)
+
+
+def test_low_wind_hv_cell_is_not_rounded(tmp_path):
+    """Low wind HV over the ocean: DN around 20. Cell of 10 x 10 pixels alternating 20 and 21.
+
+    rms = sqrt((20^2 + 21^2) / 2) = 20.506, kept in float32 (rounding it to 20 would
+    lower sigma0 by 0.22 dB)."""
+    array = (20 + np.indices((100, 100)).sum(axis=0) % 2).astype(np.uint16)
+    path = write_tiff(tmp_path / "hv.tif", array)
+
+    cells = read_cells(path, {"line": 10.0, "sample": 10.0}, (10, 10), Resampling.rms)
+
+    assert cells.dtype == np.float32
+    np.testing.assert_allclose(cells, 20.506, atol=1e-3)


=====================================
test/test_resampled_read_product.py
=====================================
@@ -0,0 +1,169 @@
+"""End-to-end tests of the resampled read, on the test product used by the CI.
+
+S1A IW GRDH 2017-09-07, 16 778 lines x 25 187 samples of 10 m, VV and VH.
+It starts with 5 lines and 5 samples of zeros (outside the swath), so at 1000 m
+(cells of 100 x 100 pixels) the first row and the first column of cells are 95 %
+in the swath, and the corner cell 95 x 95 / 100 x 100 = 90.25 %.
+
+The cells read by `load_digital_number` are compared with the pixels of the
+measurement files, recomputed with numpy."""
+
+import os
+
+import numpy as np
+import pytest
+import rasterio
+from rasterio.windows import Window
+
+from safe_s1 import Sentinel1Reader, getconfig, sentinel1_xml_mappings
+
+CHUNKS = {"line": 5000, "sample": 5000}
+CELL = 100  # pixels per cell at 1000 m
+
+
+ at pytest.fixture(scope="module")
+def reader():
+    name = getconfig.get_config()["product_paths"][0]
+    return Sentinel1Reader(sentinel1_xml_mappings.get_test_file(name))
+
+
+ at pytest.fixture(scope="module")
+def measurement(reader):
+    """Measurement file of each polarisation."""
+    files = [os.path.join(reader.path, f) for f in reader.files["measurement"]]
+    pols = [str(p) for p in reader.manifest_attrs["polarizations"]]
+    return dict(zip(pols, files))
+
+
+ at pytest.fixture(scope="module")
+def at_1000m(reader):
+    return reader.load_digital_number(resolution="1000m", chunks=dict(CHUNKS))
+
+
+def pixels_of_cell(path, i, j):
+    """The 100 x 100 full resolution pixels of cell (i, j)."""
+    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_full_resolution_is_the_file_itself(reader, measurement):
+    """Without resolution, the pixels are the ones of the file, in uint16, no valid_pixel_fraction."""
+    res, ds = reader.load_digital_number(resolution=None, chunks=dict(CHUNKS))
+
+    assert res is None
+    assert "valid_pixel_fraction" not in ds
+    assert ds.sizes["line"] == 16778
+    assert ds.sizes["sample"] == 25187
+    assert ds.digital_number.dtype == np.uint16
+    with rasterio.open(measurement["VV"]) as src:
+        pixels = src.read(1, window=Window(1000, 2000, 50, 50))
+    np.testing.assert_array_equal(
+        ds.digital_number.sel(
+            pol="VV", line=slice(2000, 2049), sample=slice(1000, 1049)
+        ),
+        pixels,
+    )
+
+
+def test_grid_at_1000m(at_1000m):
+    """16 778 x 25 187 pixels at 1000 m: 167 x 251 whole cells of 100 x 100 pixels.
+
+    Cell coordinates are the cell centers: 49.5 for the first cell, and
+    166 x 100 + 49.5 = 16 649.5 (line), 250 x 100 + 49.5 = 25 049.5 (sample) for the last.
+    The 78 last lines and 87 last samples (less than one cell) are not used."""
+    res, ds = at_1000m
+
+    assert res == 1000
+    assert ds.sizes["line"] == 167
+    assert ds.sizes["sample"] == 251
+    assert ds.line[0] == 49.5
+    assert ds.line[-1] == 16649.5
+    assert ds.sample[0] == 49.5
+    assert ds.sample[-1] == 25049.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_valid_pixel_fraction_along_the_zeros_at_the_image_start(at_1000m):
+    """5 lines and 5 samples of zeros at the start of the image:
+    corner cell 90.25 % valid, rest of the first row and column 95 %, all other cells 100 %.
+    The swath border is the same in VV and VH: one fraction for both."""
+    _, ds = at_1000m
+    fraction = ds.valid_pixel_fraction.sel(pol="VV").values
+
+    np.testing.assert_array_equal(ds.valid_pixel_fraction.sel(pol="VH"), fraction)
+
+    np.testing.assert_allclose(fraction[0, 0], 0.9025, atol=1e-6)
+    np.testing.assert_allclose(fraction[0, 1:], 0.95, atol=1e-6)
+    np.testing.assert_allclose(fraction[1:, 0], 0.95, atol=1e-6)
+    np.testing.assert_allclose(fraction[1:, 1:], 1, atol=1e-6)
+
+
+def test_three_cells_checked_by_hand(at_1000m):
+    """Three cells of the scene, with their values (rms of the valid pixels):
+
+    * corner cell (0, 0), 90.25 % valid (the zeros are not counted): VV 326.24, VH 64.74;
+    * cell in the middle of the scene (83, 125): VV 225.72, VH 66.42;
+    * last cell (166, 250), pixels 16 600 to 16 699 x 25 000 to 25 099:
+      VV 204.23, VH 106.92."""
+    _, ds = at_1000m
+    dn = ds.digital_number
+
+    np.testing.assert_allclose(dn.sel(pol="VV")[0, 0], 326.24, atol=0.01)
+    np.testing.assert_allclose(dn.sel(pol="VH")[0, 0], 64.74, atol=0.01)
+    np.testing.assert_allclose(dn.sel(pol="VV")[83, 125], 225.72, atol=0.01)
+    np.testing.assert_allclose(dn.sel(pol="VH")[83, 125], 66.42, atol=0.01)
+    np.testing.assert_allclose(dn.sel(pol="VV")[166, 250], 204.23, atol=0.01)
+    np.testing.assert_allclose(dn.sel(pol="VH")[166, 250], 106.92, atol=0.01)
+
+
+def test_any_cell_is_the_rms_of_its_own_pixels(at_1000m, measurement):
+    """Same check on the borders of the scene and on 20 cells taken at random:
+    each cell is the rms of the non-zero pixels it covers, and valid_pixel_fraction is
+    the fraction of these pixels."""
+    _, ds = at_1000m
+    n = ds.sizes["line"]
+    m = ds.sizes["sample"]
+    rng = np.random.default_rng(0)
+    cells = [(0, 0), (0, m - 1), (n - 1, 0), (n - 1, m - 1), (0, m // 2), (n // 2, 0)]
+    cells += [(rng.integers(n), rng.integers(m)) for _ in range(20)]
+    for pol, path in measurement.items():
+        dn = ds.digital_number.sel(pol=pol).values
+        fraction = ds.valid_pixel_fraction.sel(pol=pol).values
+        for i, j in cells:
+            pixels = pixels_of_cell(path, 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"cell {(i, j)}"
+            )
+
+
+ at pytest.mark.parametrize(
+    "resolution",
+    [1000, {"line": 100, "sample": 100}],
+    ids=["1000_is_in_meters", "dict_is_in_pixels"],
+)
+def test_1000m_can_be_written_three_ways(reader, at_1000m, resolution):
+    """ "1000m", 1000 (meters) and {"line": 100, "sample": 100} (pixels) give the same cells."""
+    _, expected = at_1000m
+    res, ds = reader.load_digital_number(resolution=resolution, chunks=dict(CHUNKS))
+
+    assert res is None
+    np.testing.assert_array_equal(ds.line, expected.line)
+    np.testing.assert_array_equal(ds.sample, expected.sample)
+    np.testing.assert_array_equal(ds.digital_number, expected.digital_number)
+    np.testing.assert_array_equal(
+        ds.valid_pixel_fraction, expected.valid_pixel_fraction
+    )



View it on GitLab: https://salsa.debian.org/debian-gis-team/xarray-safe-s1/-/commit/bfb209ae005b7b79328d38df131990d9e9be8cc6

-- 
View it on GitLab: https://salsa.debian.org/debian-gis-team/xarray-safe-s1/-/commit/bfb209ae005b7b79328d38df131990d9e9be8cc6
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/89fb82c3/attachment-0001.htm>


More information about the Pkg-grass-devel mailing list