[Git][debian-gis-team/xradarsat2][master] 8 commits: New upstream version 2026.11.18+ds
Antonio Valentino (@antonio.valentino)
gitlab at salsa.debian.org
Sun Nov 22 11:13:48 GMT 2026
Antonio Valentino pushed to branch master at Debian GIS Project / xradarsat2
Commits:
55584211 by Antonio Valentino at 2026-11-22T10:06:38+00:00
New upstream version 2026.11.18+ds
- - - - -
516b20b5 by Antonio Valentino at 2026-11-22T10:06:39+00:00
Update upstream source from tag 'upstream/2026.11.18+ds'
Update to upstream version '2026.11.18+ds'
with Debian dir d15fa649b1694699c65b513bc45d4e0da3cb84b9
- - - - -
a05fb718 by Antonio Valentino at 2026-11-22T10:07:15+00:00
New upstream release
- - - - -
e0a8466f by Antonio Valentino at 2026-11-22T10:07:59+00:00
Update dates in d/copyright
- - - - -
c762640f by Antonio Valentino at 2026-11-22T11:12:32+00:00
Add dependency on python3-pytest
- - - - -
27a671e9 by Antonio Valentino at 2026-11-22T11:12:33+00:00
New 0003-no-network.patch
- - - - -
5e02432d by Antonio Valentino at 2026-11-22T11:12:40+00:00
Skip tests requiring access to the internet
- - - - -
ca08a446 by Antonio Valentino at 2026-11-22T11:12:40+00:00
Set distribution to unstable
- - - - -
14 changed files:
- .git_archival.txt
- .github/workflows/ci.yaml
- .github/workflows/publish.yml
- .github/workflows/upstream-dev.yaml
- debian/changelog
- debian/control
- debian/copyright
- + debian/patches/0003-no-network.patch
- debian/patches/series
- debian/rules
- docs/doc_xradarsat2.ipynb
- src/xradarsat2/radarSat2_xarray_reader.py
- + test/test_resampled_read.py
- + test/test_resampled_read_product.py
Changes:
=====================================
.git_archival.txt
=====================================
@@ -1,4 +1,4 @@
-node: 4391409af1c60cb29670a1c3ff849b40dd88fe0b
-node-date: 2025-10-15T12:08:45+02:00
-describe-name: 2025.10.15
-ref-names: tag: 2025.10.15
+node: 2c285a82ac68da590029044fd90f44ba69caf98c
+node-date: 2026-11-18T11:42:00+01:00
+describe-name: 2026.11.18
+ref-names: HEAD -> main, tag: 2026.11.18
=====================================
.github/workflows/ci.yaml
=====================================
@@ -23,7 +23,7 @@ jobs:
outputs:
triggered: ${{ steps.detect-trigger.outputs.trigger-found }}
steps:
- - uses: actions/checkout at v4
+ - 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 v4
+ 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: xradarsat2-tests
=====================================
.github/workflows/publish.yml
=====================================
@@ -12,7 +12,7 @@ jobs:
contents: 'read'
id-token: 'write'
steps:
- - uses: actions/checkout at v5
+ - uses: actions/checkout at v7
- name: Set up Python
uses: actions/setup-python at v6
with:
@@ -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 cef221092ed1bacb1cc03d23a2d87d1d172e277b
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 v4
+ - 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 v4
+ 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 v1
+ uses: mamba-org/setup-micromamba at v3
with:
environment-file: ci/requirements/environment.yaml
environment-name: tests
=====================================
debian/changelog
=====================================
@@ -1,11 +1,21 @@
-xradarsat2 (2025.10.15+ds-2) UNRELEASED; urgency=medium
+xradarsat2 (2026.11.18+ds-1) unstable; urgency=medium
- * Team upload.
+ [ Bas Couwenberg ]
* Use test-build-validate-cleanup instead of test-build-twice.
* Drop Priority: optional, default since dpkg 1.22.13.
* Bump Standards-Version to 4.7.4, changes: priority.
- -- Bas Couwenberg <sebastic at debian.org> Sat, 25 Oct 2025 13:10:53 +0200
+ [ Antonio Valentino ]
+ * New upstream release.
+ * Update dates in d/copyright.
+ * debian/control:
+ - Add dependency on python3-pytest.
+ * debian/patches:
+ - New 0003-no-network.patch.
+ * debian/rules:
+ - Skip tests requiring access to the internet.
+
+ -- Antonio Valentino <antonio.valentino at tiscali.it> Sun, 22 Nov 2026 10:08:18 +0000
xradarsat2 (2025.10.15+ds-1) unstable; urgency=medium
=====================================
debian/control
=====================================
@@ -14,6 +14,7 @@ Build-Depends: debhelper-compat (= 13),
python3-dask,
python3-fsspec,
python3-numpy,
+ python3-pytest <!nocheck>,
python3-rasterio,
python3-regex,
python3-rioxarray,
=====================================
debian/copyright
=====================================
@@ -13,7 +13,7 @@ Copyright: 2022, Ifremer
License: Expat
Files: debian/*
-Copyright: 2023-2025, Antonio Valentino <antonio.valentino at tiscali.it>
+Copyright: 2023-2026, Antonio Valentino <antonio.valentino at tiscali.it>
License: Expat
License: Expat
=====================================
debian/patches/0003-no-network.patch
=====================================
@@ -0,0 +1,65 @@
+From: Antonio Valentino <antonio.valentino at tiscali.it>
+Date: Sun, 22 Nov 2026 10:59:59 +0000
+Subject: no-network
+
+Disable tests that require access to the internet.
+---
+ pyproject.toml | 3 +++
+ test/test_resampled_read_product.py | 5 +++++
+ 2 files changed, 8 insertions(+)
+
+diff --git a/pyproject.toml b/pyproject.toml
+index d5168aa..559870c 100644
+--- a/pyproject.toml
++++ b/pyproject.toml
+@@ -77,3 +77,6 @@ known-third-party = ["xarray", "toolz", "construct"]
+ [tool.ruff.lint.flake8-tidy-imports]
+ # Disallow all relative imports.
+ ban-relative-imports = "all"
++
++[tool.pytest.ini_options]
++markers = ["network"]
+diff --git a/test/test_resampled_read_product.py b/test/test_resampled_read_product.py
+index c274516..7c6ba89 100644
+--- a/test/test_resampled_read_product.py
++++ b/test/test_resampled_read_product.py
+@@ -47,6 +47,7 @@ def rms_of_valid_pixels(pixels):
+ return np.sqrt(np.mean(valid**2)) if valid.size else 0
+
+
++ at pytest.mark.network
+ def test_full_resolution_is_the_file_itself(product):
+ """Without resolution, the pixels are the ones of the file, in uint16, no valid_pixel_fraction."""
+ ds = load(product, None)
+@@ -65,6 +66,7 @@ def test_full_resolution_is_the_file_itself(product):
+ )
+
+
++ at pytest.mark.network
+ def test_grid_at_1000m(at_1000m):
+ """10 277 x 10 618 pixels of 50 m at 1000 m: 513 x 530 whole cells of 20 x 20 pixels.
+
+@@ -85,6 +87,7 @@ def test_grid_at_1000m(at_1000m):
+ assert ds.valid_pixel_fraction.attrs["units"] == "1"
+
+
++ at pytest.mark.network
+ def test_four_cells_checked_by_hand(at_1000m):
+ """Four cells of the scene, with their values (rms of the valid pixels):
+
+@@ -114,6 +117,7 @@ def test_four_cells_checked_by_hand(at_1000m):
+ np.testing.assert_allclose(fraction_vh[200, 6], 0.5375)
+
+
++ at pytest.mark.network
+ 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
+@@ -145,6 +149,7 @@ def test_any_cell_is_the_rms_of_its_own_pixels(at_1000m, product):
+ )
+
+
++ at pytest.mark.network
+ @pytest.mark.parametrize(
+ "resolution",
+ [1000, {"line": 20, "sample": 20}],
=====================================
debian/patches/series
=====================================
@@ -1,2 +1,3 @@
0001-Fix-privacy-breach.patch
0002-No-nbsphinx-execution.patch
+0003-no-network.patch
=====================================
debian/rules
=====================================
@@ -1,6 +1,7 @@
#! /usr/bin/make -f
export PYBUILD_NAME=xradarsat2
+export PYBUILD_TEST_ARGS=-m "not network" --ignore=test/test_opening_datatree_radarsat2.py
%:
dh $@ --buildsystem=pybuild
=====================================
docs/doc_xradarsat2.ipynb
=====================================
@@ -71,6 +71,16 @@
")\n",
"dt"
]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ae88e483-da74-462e-aaa0-822c2a2abdc5",
+ "metadata": {},
+ "source": [
+ "Here the image is averaged on whole cells of 50 x 50 pixels: the pixels at 0, outside the swath, are not counted, and the cell values are kept in float32.\n",
+ "The `valid_pixel_fraction` variable gives the share of each cell inside the swath, for each polarisation (0: outside the swath, 1: full cell).\n",
+ "See `load_digital_number` in the API reference for the details of the grid."
+ ]
}
],
"metadata": {
=====================================
src/xradarsat2/radarSat2_xarray_reader.py
=====================================
@@ -5,6 +5,7 @@ import os
import re
import traceback
from datetime import datetime
+from xml.sax.saxutils import escape
import dask
import numpy as np
@@ -1847,6 +1848,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 load_digital_number(
dt,
resolution=None,
@@ -1857,24 +1947,48 @@ def load_digital_number(
Add to the initial datatree (that contains all datasets) a new dataset with digital numbers
(name of the dataset = `digital_numbers`)
+ With `resolution=None`, the imagery 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. 50 m pixels at "125m" 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), computed for each polarisation
+ (the swath borders of the polarisations can differ by a few pixels).
+
Parameters
----------
dt: xr.Datatree
datatree containing every dataset
resolution: str, dict[str, int], None or number
- 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 str, it must end with 'm' (meters), like '100m'. dict will be computed from sensor pixel size
+ cell size, None by default:
+
+ * None: full resolution, no resampling;
+ * str ending with "m", like "1000m": size in meters, converted to pixels with
+ the sampled line and pixel spacings of the product;
+ * number: size in meters, as for a str;
+ * dict like `{"line": 20, "sample": 20}`: size in pixels.
chunks: dict[str, int]
- dict with keys ['pol','line','sample'] (dask chunks)
+ dask chunks, with keys "line" and "sample". A "pol" key is set to 1.
resampling: rasterio.enums.Resampling
- Only used if `resolution` is not None.
- ` rasterio.enums.Resampling.rms` by default. `rasterio.enums.Resampling.nearest` (decimation) is fastest
+ mean used for the cells, only with a `resolution`. `rasterio.enums.Resampling.rms` by default.
Returns
-------
xr.Datatree
- Initial datatree + dataset (possibly dual-pol), with basic coords/dims naming convention
+ Initial datatree + dataset with `digital_number` and, if resampled,
+ `valid_pixel_fraction` (dims "pol", "line", "sample").
"""
# This func permit to calculate the resampling with Gaussian filter and xtiling (for the posting)
@@ -1948,36 +2062,20 @@ def load_digital_number(
],
)
- # 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()),
@@ -1987,14 +2085,16 @@ def load_digital_number(
],
"pol",
).chunk(chunks)
- # create coordinates at box center
+ # one fraction per polarisation: the swath borders can differ by a few pixels
+ valid_fraction = np.stack(
+ [read_valid_fraction(f, resolution, out_shape) for f in tiff_files]
+ )
+
+ # 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})
@@ -2029,6 +2129,19 @@ def load_digital_number(
),
}
ds = dn.to_dataset(name=var_name)
+ if resolution is not None:
+ ds["valid_pixel_fraction"] = xr.DataArray(
+ valid_fraction,
+ dims=("pol", "line", "sample"),
+ coords={"pol": ds.pol, "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 for each polarisation",
+ },
+ )
dt["digital_numbers"] = xr.DataTree(ds)
return dt
@@ -2245,6 +2358,17 @@ def rs2_reader(folder_path):
ds_radar_parameters = create_dataset_radar_parameters(
radar_parameters_dic, folder_path
)
+ try:
+ noise_subtraction_performed = dic["product"]["imageGenerationParameters"][
+ "sarProcessingInformation"
+ ]["noiseSubtractionPerformed"]
+ except KeyError:
+ # field absent from the product.xml
+ noise_subtraction_performed = None
+ dt["imageGenerationParameters"].attrs[
+ "noiseSubtractionPerformed"
+ ] = noise_subtraction_performed
+
dt["radarParameters"] = xr.DataTree(ds_radar_parameters)
ds_lut = create_dataset_lut(list_lut_files(folder_path), dt, folder_path)
dt["lut"] = xr.DataTree(ds_lut)
=====================================
test/test_resampled_read.py
=====================================
@@ -0,0 +1,140 @@
+"""Resampled read (`resolution` given), on small synthetic GeoTIFFs.
+
+Each test is a concrete case met with RadarSAT-2 products, with the expected values
+computed by hand in the docstring:
+
+* a ScanSAR Wide image (50 m pixels) of 10 277 lines read at 1000 m: the last cell
+ must hold its own lines;
+* the same pixels read at 125 m: cells of 2.5 pixels;
+* a cell straddling the swath border: the zeros outside the swath must not darken it;
+* a low wind cross-pol 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 xradarsat2.radarSat2_xarray_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_a_scansar_image_holds_its_own_lines(tmp_path):
+ """ScanSAR Wide image of 10 277 lines of 50 m, read at 1000 m: 513 cells of 20 lines.
+
+ Cell k holds lines 20 k to 20 k + 19, so with pixels = line number + 1:
+ first cell 10.5, last cell (lines 10 240 to 10 259) 10 250.5.
+ The 17 last lines (less than one cell) are not used."""
+ path = write_tiff(tmp_path / "scw.tif", line_numbers(10277, 20))
+ resolution = {"line": 20.0, "sample": 20.0}
+
+ cells = read_cells(path, resolution, (513, 1), Resampling.average)[0]
+
+ assert cells[0, 0] == 10.5
+ assert cells[-1, 0] == 10250.5
+
+
+def test_scansar_image_read_at_125m_has_cells_of_two_and_a_half_pixels(tmp_path):
+ """50 m pixels read at 125 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 / "scw.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", ["range", "azimuth"])
+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 or in azimuth. 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 == "azimuth":
+ 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 == "azimuth":
+ 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_a_cell_of_two_and_a_half_pixels_across_the_border(
+ tmp_path,
+):
+ """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_cross_pol_cell_is_not_rounded(tmp_path):
+ """Low wind cross-pol 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 / "vh.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,162 @@
+"""End-to-end tests of the resampled read, on the test product used by the CI.
+
+RS2 ScanSAR Wide 2022-04-07, 10 277 lines x 10 618 samples of 50 m, VV and VH.
+At 1000 m, a cell is 20 x 20 pixels: 513 x 530 cells.
+The swath is tilted in the image: the corners are outside the swath (zeros),
+and many cells straddle its border.
+
+The cells read by `load_digital_number` are compared with the pixels of the
+imagery files, recomputed with numpy."""
+
+import numpy as np
+import pytest
+import rasterio
+from rasterio.windows import Window
+
+import xradarsat2
+from xradarsat2.utils import get_test_file, load_config
+
+CHUNKS = {"line": 5000, "sample": 5000}
+CELL = 20 # pixels per cell at 1000 m
+
+
+ at pytest.fixture(scope="module")
+def product():
+ return get_test_file(load_config()["folder_path"])
+
+
+def load(product, resolution):
+ dt = xradarsat2.rs2_reader(product)
+ dt = xradarsat2.load_digital_number(dt, resolution=resolution, chunks=dict(CHUNKS))
+ return dt["digital_numbers"].to_dataset()
+
+
+ at pytest.fixture(scope="module")
+def at_1000m(product):
+ return load(product, "1000m")
+
+
+def pixels_of_cell(product, pol, i, j):
+ """The 20 x 20 full resolution pixels of cell (i, j)."""
+ with rasterio.open(f"{product}/imagery_{pol}.tif") 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(product):
+ """Without resolution, the pixels are the ones of the file, in uint16, no valid_pixel_fraction."""
+ ds = load(product, None)
+
+ assert "valid_pixel_fraction" not in ds
+ assert ds.sizes["line"] == 10277
+ assert ds.sizes["sample"] == 10618
+ assert ds.digital_number.dtype == np.uint16
+ with rasterio.open(f"{product}/imagery_VV.tif") as src:
+ pixels = src.read(1, window=Window(5000, 5000, 50, 50))
+ np.testing.assert_array_equal(
+ ds.digital_number.sel(
+ pol="VV", line=slice(5000, 5049), sample=slice(5000, 5049)
+ ),
+ pixels,
+ )
+
+
+def test_grid_at_1000m(at_1000m):
+ """10 277 x 10 618 pixels of 50 m at 1000 m: 513 x 530 whole cells of 20 x 20 pixels.
+
+ Cell coordinates are the cell centers: 9.5 for the first cell, and
+ 512 x 20 + 9.5 = 10 249.5 (line), 529 x 20 + 9.5 = 10 589.5 (sample) for the last.
+ The 17 last lines and 18 last samples (less than one cell) are not used."""
+ ds = at_1000m
+
+ assert ds.sizes["line"] == 513
+ assert ds.sizes["sample"] == 530
+ assert ds.line[0] == 9.5
+ assert ds.line[-1] == 10249.5
+ assert ds.sample[0] == 9.5
+ assert ds.sample[-1] == 10589.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 (512, 529), outside the swath too: 0, valid_pixel_fraction 0;
+ * cell in the middle of the scene (256, 265), full: VV 1796.11, VH 1014.68;
+ * cell (200, 6) on the swath border, about 10 columns of zeros then 10 of sea.
+ The border is not exactly the same in both polarisations:
+ VV 200 valid pixels out of 400 (0.5), VV 680.41;
+ VH 215 valid pixels out of 400 (0.5375), VH 192.28."""
+ ds = at_1000m
+ vv = ds.digital_number.sel(pol="VV").values
+ vh = ds.digital_number.sel(pol="VH").values
+ fraction_vv = ds.valid_pixel_fraction.sel(pol="VV").values
+ fraction_vh = ds.valid_pixel_fraction.sel(pol="VH").values
+
+ assert vv[0, 0] == 0
+ assert fraction_vv[0, 0] == 0
+ assert vv[512, 529] == 0
+ assert fraction_vv[512, 529] == 0
+ np.testing.assert_allclose(vv[256, 265], 1796.11, atol=0.01)
+ np.testing.assert_allclose(vh[256, 265], 1014.68, atol=0.01)
+ np.testing.assert_allclose(fraction_vv[256, 265], 1)
+ np.testing.assert_allclose(vv[200, 6], 680.41, atol=0.01)
+ np.testing.assert_allclose(fraction_vv[200, 6], 0.5)
+ np.testing.assert_allclose(vh[200, 6], 192.28, atol=0.01)
+ np.testing.assert_allclose(fraction_vh[200, 6], 0.5375)
+
+
+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, in each polarisation."""
+ ds = at_1000m
+ fraction = ds.valid_pixel_fraction.sel(pol="VV").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)]
+
+ for pol in ["VV", "VH"]:
+ 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(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)}",
+ )
+
+
+ at pytest.mark.parametrize(
+ "resolution",
+ [1000, {"line": 20, "sample": 20}],
+ ids=["1000_is_in_meters", "dict_is_in_pixels"],
+)
+def test_1000m_can_be_written_three_ways(product, at_1000m, resolution):
+ """ "1000m", 1000 (meters) and {"line": 20, "sample": 20} (pixels) give the same cells."""
+ ds = load(product, resolution)
+
+ np.testing.assert_array_equal(ds.line, at_1000m.line)
+ np.testing.assert_array_equal(ds.sample, at_1000m.sample)
+ np.testing.assert_array_equal(ds.digital_number, at_1000m.digital_number)
+ np.testing.assert_array_equal(
+ ds.valid_pixel_fraction, at_1000m.valid_pixel_fraction
+ )
View it on GitLab: https://salsa.debian.org/debian-gis-team/xradarsat2/-/compare/74b754449809df719dc1f1cde4459789ae8523e1...ca08a446d70d39ae559848e24708b12bb37f9cf6
--
View it on GitLab: https://salsa.debian.org/debian-gis-team/xradarsat2/-/compare/74b754449809df719dc1f1cde4459789ae8523e1...ca08a446d70d39ae559848e24708b12bb37f9cf6
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/5f1f82c6/attachment-0001.htm>
More information about the Pkg-grass-devel
mailing list