From ff7b405044b4a038aa70d757a49dde829d07c3f6 Mon Sep 17 00:00:00 2001 From: Alexis Jacquesson Date: Mon, 9 Nov 2026 11:34:48 +0100 Subject: [PATCH] CI: unit tests before publish, faster/correct GitLab LFS sync, missing core dependencies; fix production bugs left by a bad merge; bump to 3.0.0 CI: - pypi.yml: run grs/tests/unit/ before build/publish. - main.yml: Job Summary (tests + coverage) and HTML coverage report upload on every run; free disk space before podman-build (torch/omnicloudmask pushed it over the runner's default headroom); robust version extraction for the Docker tag (grs.__version__, same method as pypi.yml) instead of a grep on pyproject.toml that matched two lines. - mirror-to-gitlab/action.yml: batch git cat-file calls instead of one process per blob occurrence (the dominant cost of the GitLab sync job), and fix the resulting path mapping to keep every path of a blob shared by several files (e.g. duplicate SMAC coefficient files), which a first pass had dropped. Dependencies (requirements.txt): platformdirs, dask, cdsapi, zarr, h5netcdf, h5py, omnicloudmask were used by the code (sometimes unconditionally) but missing. Production bugs (already on develop, not introduced here) found while getting the full test suite to pass: - grs_process.py: restored module-level helpers dropped by a past merge (_correct_gas_absorption, _interp_like, _with_workers, _cams_from_archive, _aerosol_settings, NETCDF_ENGINE, _OUTPUT_EXTENSIONS); removed a dead pre-Kernel-refactor block in execute() that referenced undefined names and silently clobbered gas_trans/dem. - mask.py: restored Masking's missing machinery (_register, _wl_index, _require, _flags_lazy, _run, _nodata_step, _pixel_size, _ocm_factor, _get_omnicloudmask, _water_step, _OCM_VERSION); fixed cirrus_mask (undefined icirrus), _surfwater_step (never returned its _Step), duplicate_landsat_flags (bitmasks collided with the OmniCloudMask bits, broken body) and process() (never built its steps list). - run.py: restored limit_malloc_arenas and set_ofile; fixed the docopt Usage: pattern missing --aot_resolution. - tests/unit/conftest.py: restored the SAFE constant; fixed luts_available() crashing (TypeError) instead of skipping when GRSDATA is unset. - tests/integration_tests/conftest.py: added (never existed) with l1c_path, cams_path and the l2a_zarr fixture the existing end-to-end test needed. pyproject.toml / grs/__init__.py: version is now truly dynamic (sourced from grs.__version__, the single source of truth) instead of duplicated as a stale literal; bumped to 3.0.0. --- .github/actions/mirror-to-gitlab/action.yml | 76 ++++-- .github/workflows/main.yml | 63 ++++- .github/workflows/pypi.yml | 17 ++ grs/__init__.py | 2 +- grs/grs_process.py | 162 +++++++++---- grs/mask.py | 243 ++++++++++++++++++-- grs/run.py | 33 ++- grs/tests/integration_tests/conftest.py | 52 +++++ grs/tests/unit/conftest.py | 8 +- pyproject.toml | 5 +- requirements.txt | 7 + 11 files changed, 569 insertions(+), 99 deletions(-) create mode 100644 grs/tests/integration_tests/conftest.py diff --git a/.github/actions/mirror-to-gitlab/action.yml b/.github/actions/mirror-to-gitlab/action.yml index 60ec943..8d0a96b 100644 --- a/.github/actions/mirror-to-gitlab/action.yml +++ b/.github/actions/mirror-to-gitlab/action.yml @@ -37,21 +37,47 @@ runs: run: | set -euo pipefail - : > /tmp/lfs-files.txt - + # `git rev-list --objects` dedupes by blob content: two different + # paths that happen to share identical bytes (e.g. duplicate SMAC + # coefficient files) would only get one of their paths reported, + # leaving the other un-stripped. List every (object, path) of every + # commit's tree instead -- same as `git ls-tree -r` per commit, but + # tab-separated so a path containing spaces stays intact. while read -r commit; do git ls-tree -r "$commit" done < <(git rev-list HEAD) | - while read -r mode type object path; do - [ "$type" = "blob" ] || continue - + awk -F'\t' '{split($1, a, " "); if (a[2] == "blob") print a[3] "\t" $2}' \ + > /tmp/all-blobs.txt + + # Looking up every blob one by one (one `git cat-file` process per + # occurrence, repeated across commits that share an unchanged blob) + # is by far the slowest part of this job. Instead: resolve + # type/size for every *unique* blob in a single batched call, and + # only then read the content of the few candidates small enough to + # be an LFS pointer file (a handful of plain-text lines, well under + # 1 KB). + cut -f1 /tmp/all-blobs.txt | sort -u | + git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' \ + > /tmp/object-info.txt + + awk '$2 == "blob" && $3 < 1024 { print $1 }' /tmp/object-info.txt | + sort -u > /tmp/small-blobs.txt + + : > /tmp/lfs-objects.txt + while read -r object; do if git cat-file blob "$object" 2>/dev/null | head -n 1 | grep -Fxq 'version https://git-lfs.github.com/spec/v1'; then - printf '%s\n' "$path" + printf '%s\n' "$object" >> /tmp/lfs-objects.txt fi - done | - sort -u > /tmp/lfs-files.txt + done < /tmp/small-blobs.txt + + # Map the matching objects back to every path they were committed + # under across history (a shared blob can sit at several paths), so + # they all get removed. + awk -F'\t' 'NR==FNR { want[$1]; next } $1 in want { print $2 }' \ + /tmp/lfs-objects.txt /tmp/all-blobs.txt | + sort -u > /tmp/lfs-files.txt cat > /tmp/remove-paths.txt <<'EOF' grs/tests/.gitattributes @@ -79,20 +105,28 @@ runs: exit 1 fi - FOUND=0 + # Same batched approach as the stripping step above: resolve every + # reachable object's type/size in one call, then only read the + # content of blobs small enough to be an LFS pointer file. + git rev-list --objects HEAD > /tmp/all-objects-after.txt - while read -r commit; do - while read -r mode type object path; do - [ "$type" = "blob" ] || continue - - if git cat-file blob "$object" 2>/dev/null | - head -n 1 | - grep -Fxq 'version https://git-lfs.github.com/spec/v1'; then - echo "ERROR: LFS pointer found (commit=$commit path=$path)" - FOUND=1 - fi - done < <(git ls-tree -r "$commit") - done < <(git rev-list HEAD) + cut -d' ' -f1 /tmp/all-objects-after.txt | + git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' \ + > /tmp/object-info-after.txt + + awk '$2 == "blob" && $3 < 1024 { print $1 }' /tmp/object-info-after.txt | + sort -u > /tmp/small-blobs-after.txt + + FOUND=0 + while read -r object; do + if git cat-file blob "$object" 2>/dev/null | + head -n 1 | + grep -Fxq 'version https://git-lfs.github.com/spec/v1'; then + path=$(awk -v o="$object" '$1==o{print $2; exit}' /tmp/all-objects-after.txt) + echo "ERROR: LFS pointer found (object=$object path=${path:-unknown})" + FOUND=1 + fi + done < /tmp/small-blobs-after.txt if [ "$FOUND" -ne 0 ]; then echo "LFS pointers remain, nothing will be pushed." diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index dfa2954..dbf6a9c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -73,13 +73,57 @@ jobs: fi fi + - name: Résumé des tests et de la couverture + if: always() + run: | + python3 - <<'PY' + import os + import xml.etree.ElementTree as ET + + summary = [] + + try: + root = ET.parse('test-results.xml').getroot() + suite = root.find('testsuite') if root.tag == 'testsuites' else root + tests = int(suite.get('tests', 0)) + failures = int(suite.get('failures', 0)) + errors = int(suite.get('errors', 0)) + skipped = int(suite.get('skipped', 0)) + passed = tests - failures - errors - skipped + time = float(suite.get('time', 0)) + summary += [ + '## Tests unitaires', + '', + '| Total | Réussis | Échoués | Erreurs | Ignorés | Durée |', + '|---|---|---|---|---|---|', + f'| {tests} | {passed} | {failures} | {errors} | {skipped} | {time:.1f}s |', + ] + except (FileNotFoundError, ET.ParseError): + summary += ['## Tests unitaires', '', '_pas de résultats (test-results.xml manquant)_'] + + try: + root = ET.parse('coverage.xml').getroot() + line_rate = float(root.get('line-rate', 0)) * 100 + summary += [ + '', + '## Couverture', + '', + f"**{line_rate:.1f}%** des lignes couvertes " + f"({root.get('lines-covered')}/{root.get('lines-valid')})", + ] + except (FileNotFoundError, ET.ParseError): + summary += ['', '## Couverture', '', '_pas de rapport (coverage.xml manquant)_'] + + with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as f: + f.write('\n'.join(summary) + '\n') + PY + - name: Upload test results uses: actions/upload-artifact@v4 - if: false - #if: always() # Upload même si les tests échouent + if: always() # Upload même si les tests échouent with: name: test-reports - path : | + path : | coverage.xml test-results.xml cov_html/ @@ -118,10 +162,21 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + + - name: Free disk space + # omnicloudmask (torch) pushed the image build over the runner's default free space + # ("no space left on device" while podman commits the layer): the GitHub-hosted ubuntu + # runner ships several GB of preinstalled toolchains we don't use (.NET, Android, Haskell, + # Swift) and ~20-30 GB of unused container images; remove them first to get headroom back. + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL /usr/local/share/powershell /usr/local/share/chromium /usr/share/swift + sudo docker image prune --all --force + df -h / + - name: Build image run: | echo "DOCKER_IMAGE_NAME=${DOCKER_IMAGE_NAME}" - export VERSION_GRS=$(grep version pyproject.toml | cut -d '"' -f 2) + export VERSION_GRS=$(python3 -c "import ast, pathlib; t = pathlib.Path('grs/__init__.py').read_text(); print(next(n.value.value for n in ast.parse(t).body if isinstance(n, ast.Assign) and getattr(n.targets[0], 'id', '') == '__version__'))") if [ "$GITHUB_REF_TYPE" = "tag" ]; then echo "Tag : $GITHUB_REF_NAME" export VERSION_GRS=${GITHUB_REF_NAME}; diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml index ce403d2..7d3b6b3 100644 --- a/.github/workflows/pypi.yml +++ b/.github/workflows/pypi.yml @@ -21,7 +21,24 @@ on: default: testpypi jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install dependencies and run unit tests + run: | + python -m pip install --upgrade pip + python -m pip install -r requirements.txt --no-cache-dir + python -m pip install pytest + python -m pytest --tb=short -vv grs/tests/unit/ + build: + needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/grs/__init__.py b/grs/__init__.py index dd3db14..239b121 100644 --- a/grs/__init__.py +++ b/grs/__init__.py @@ -123,7 +123,7 @@ ''' __package__ = 'grs' -__version__ = '2.2.0' +__version__ = '3.0.0' import importlib diff --git a/grs/grs_process.py b/grs/grs_process.py index 8d7e962..b790e7a 100644 --- a/grs/grs_process.py +++ b/grs/grs_process.py @@ -61,6 +61,119 @@ TRANSLUT = config['path']['trans_lut'] CAMS_PATH = config['path']['trans_lut'] NCPU = config['processor']['ncpu'] +NETCDF_ENGINE = config['processor']['netcdf_engine'] + +# extensions that tell the output format (see write_output) +_OUTPUT_EXTENSIONS = ('.zarr', '.nc', '.nc4', '.cdf') +# arrays smaller than this (bytes) are loaded in memory once +_SMALL_ARRAY_BYTES = 512 * 2 ** 20 + + +def _compute_small(obj, max_bytes=_SMALL_ARRAY_BYTES): + '''Load a small dask-backed xarray object in memory (once); anything else is returned unchanged.''' + if isinstance(obj, (xr.DataArray, xr.Dataset)) and obj.chunks and obj.nbytes <= max_bytes: + return obj.compute() + return obj + + +def _correct_gas_absorption(bands, Tg_raster): + ''' + Divide the bands by the gaseous transmittance (coarse grid, interpolated to the pixels). + + * dask-backed `bands`: lazy, done block by block, the transmittance is only interpolated on the block + (no full-size interpolation, no sequence of assignments into a big array); + * numpy-backed `bands`: in place band by band, as before. + + In both cases the result keeps the dtype of `bands`. + + :param bands: DataArray (wl, y, x) of the TOA reflectance + :param Tg_raster: DataArray of the gaseous transmittance on a coarse grid, with the wavelengths of `bands` + :return: corrected bands (same object as `bands` for numpy-backed data) + ''' + if bands.chunks is None: + for wl in bands.wl.values: + bands.loc[wl] = bands.sel(wl=wl) / Tg_raster.sel(wl=wl).interp(x=bands.x, y=bands.y) + return bands + + # without its scalar coordinates: a spatial_ref different from the one of the bands would be dropped from + # the result by the division, and map_blocks would reject the block + Tg = _compute_small(Tg_raster.sel(wl=bands.wl)).reset_coords(drop=True) + + def block(b): + corrected = b / Tg.interp(x=b.x, y=b.y) + corrected = corrected.drop_vars([c for c in corrected.coords if c not in b.coords]) + return corrected.transpose(*b.dims).astype(b.dtype) + + return xr.map_blocks(block, bands, template=bands) + + +def _interp_like(coarse, like, name=None): + ''' + Interpolate a coarse DataArray (dimensions x, y) onto the grid of `like`, block by block. + + Lazy if `like` is dask-backed: only the part of the coarse map needed by a block is interpolated when + the block is computed (no full-size array in memory). Same values as ``coarse.interp(x=like.x, y=like.y)``; + the scalar coordinates of `coarse` are kept. + + :param coarse: DataArray on a coarse grid (loaded in memory if small) + :param like: DataArray (y, x) giving the target grid and chunks + :param name: name of the result + :return: DataArray (y, x) float64 + ''' + coarse = _compute_small(coarse) + like = like.reset_coords(drop=True) + template = xr.full_like(like, np.nan, dtype=np.float64) + + def block(b): + out = coarse.interp(x=b.x, y=b.y).reset_coords(drop=True) + return out.transpose(*b.dims).astype(np.float64) + + out = xr.map_blocks(block, like, template=template).rename(name or coarse.name) + scalar_coords = {k: v for k, v in coarse.coords.items() if k not in coarse.dims} + return out.assign_coords(scalar_coords) + + +def _with_workers(method): + '''Run a `Process` method with ``self.Nproc`` dask workers (threaded scheduler; None: one per core).''' + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + with dask.config.set(num_workers=self.Nproc): + return method(self, *args, **kwargs) + return wrapper + + +def _cams_from_archive(raster, cams_dir): + """ + CAMS data of an image from the ``YYYY/MM/DD`` archive of `cams_dir` (``path: cams`` of the + configuration): global file of the day if it exists, else the file of the tile, downloaded if needed. + A file of the former layout ``//-forecast_.nc`` is still used. + """ + tile = raster.attrs['tile'] + cams = CamsProduct(raster, dir=cams_dir, suffix='_' + tile) + legacy = os.path.join(cams_dir, tile, f'{cams.date_str}-forecast_{tile}.nc') + if not os.path.exists(cams.filepath) and os.path.exists(legacy): + cams = CamsProduct(raster, cams_file=legacy) + logging.info('CAMS file: %s', cams.filepath) + return cams + + +# settings of the aerosol retrieval, ``aerosol`` section of the configuration +AEROSOL_SETTINGS = ('aot_resolution', 'min_pixel_prop', 'aot_chunk', 'outlier_factor', 'aot_smoothing_blocks', + 'fine_step', 'fine_window', 'aot_step') + + +def _aerosol_settings(**overrides): + """ + Settings of the aerosol retrieval: ``aerosol`` section of the configuration, overridden by the arguments + that are not None. + """ + config = load_config().get('aerosol') or {} + missing = [key for key in AEROSOL_SETTINGS if key not in config and overrides.get(key) is None] + if missing: + raise KeyError(f'aerosol settings missing in the configuration: {missing}') + settings = {key: config.get(key) for key in AEROSOL_SETTINGS} + settings.update({key: value for key, value in overrides.items() if value is not None}) + return settings class Process: @@ -499,55 +612,6 @@ def execute(self, l1c_prod, kernel.lut_preparation(aerosol_combination=aerosol_combination) kernel.set_gas_transmittance() - ###################################### - # surface rugosity (wind) estimation - ###################################### - logging.info('set final parameters') - width = prod.width - height = prod.height - Nwl = len(prod.raster.wl_to_process) - - pressure_ref = self.pressure_ref - - _sunglint_eps = sunglint_eps.values - - # prepare aerosol parameters - aot_ref_raster = aot_ref_raster.interp(x=prod.raster.x, y=prod.raster.y).drop_vars('wl').astype(np.float32) - aot_ref_raster.name = 'aot550' - _rot = rot.values - - # _aot = aot_lut.interp(aot_ref=_aot_ref) - if dem_file: - logging.info('compute surface pressure from dem') - dem = xr.open_dataset(dem_file).squeeze().interp(y=prod.raster.y, x=prod.raster.x, method='nearest') - dem = dem.rename_vars({'band_data': 'dem'}) - dem.dem.attrs['long_name'] = 'digital elevation model' - dem.dem.attrs['units'] = 'm' - dem.dem.attrs['source'] = dem_file - presure_msl = cams.raster.msl.interp(y=prod.raster.y, x=prod.raster.x) - _pressure = (presure_msl * (1. - 0.0065 * dem.dem / 288.15) ** 5.255).values - else: - dem = None - _pressure = cams.raster.sp.interp(x=prod.raster.x, y=prod.raster.y).values - - # ------------------------------------------------------------- - # SET GASEOUS TRANSMITTANCE FOR LOW ALTITUDE GASES - # ------------------------------------------------------------- - gases = ['h2o', 'ch4'] - gas_trans = acutils.GaseousTransmittance(prod, cams) - # set total transmittance values - gas_trans.coef_abs_scat['h2o'] = 0.5 - gas_trans.coef_abs_scat['ch4'] = 0.5 - Tg_diff_raster = gas_trans.get_gaseous_transmittance(gases=gases, background=False).transpose("wl", "y", - "x") - Tg_diff_raster = Tg_diff_raster.interp(x=prod.raster.x, y=prod.raster.y) - - # set total transmittance values - for gas in gases: - gas_trans.coef_abs_scat[gas] = 1 - Tg_raster = gas_trans.get_gaseous_transmittance(gases=gases, background=False).transpose("wl", "y", "x") - Tg_raster = Tg_raster.interp(x=prod.raster.x, y=prod.raster.y) - ###################################### # aerosol load estimation ###################################### diff --git a/grs/mask.py b/grs/mask.py index 3ae0c15..41e036b 100644 --- a/grs/mask.py +++ b/grs/mask.py @@ -77,12 +77,16 @@ import numpy as np import pandas as pd import xarray as xr -import pandas as pd - -import logging from s2cloudless import S2PixelCloudDetector +# omnicloudmask (torch) takes seconds to import: it is imported where it is used, so that ``import grs`` +# (and ``grs -v``) stays fast +try: + _OCM_VERSION = version('omnicloudmask') +except PackageNotFoundError: + _OCM_VERSION = 'unknown' + FLAG_NAME = 'flags' # flag bits of the OmniCloudMask classes 1 (thick cloud), 2 (thin cloud) and 3 (cloud shadow) OCM_BITS = (11, 12, 13) @@ -259,6 +263,190 @@ def __init__(self, prod: xr.Dataset, tile_size: int = 1024): self.flags = np.zeros((y_size, x_size), dtype=np.uint32) self.flag_stats = {} + # ------------------------------------------------------------------ + # machinery + # ------------------------------------------------------------------ + def _register(self, bit, name, description): + '''Record the name and description of flag bit `bit`.''' + self.flag_names[bit] = name + self.flag_descriptions[bit] = description + + def _wl_index(self, wl, nearest=True): + '''Position of wavelength `wl` along the wl axis (nearest, or exact like ``sel(wl=wl)``).''' + index = self.prod.indexes['wl'] + if nearest: + return int(index.get_indexer([wl], method='nearest')[0]) + return int(index.get_loc(wl)) + + def _require(self, name): + '''Return dataset variable `name`, failing early with a clear message if it is missing.''' + if name not in self.prod: + raise KeyError(f"the dataset has no variable '{name}', needed by this mask") + return self.prod[name] + + def _flags_lazy(self, steps): + '''Lazy dask array (y, x, uint32) with the flags of `steps`. + + All steps run in one task per tile. Tiles overlap by the largest halo of the steps, are + processed whole (halo included) and trimmed afterwards. + ''' + ny, nx = self.prod.sizes['y'], self.prod.sizes['x'] + halo = max(s.halo for s in steps) + if self.tile_size < halo: + raise ValueError(f'tile_size ({self.tile_size}) must be at least the halo ({halo} pixels)') + chunks = {'y': _chunks(ny, self.tile_size, halo), 'x': _chunks(nx, self.tile_size, halo)} + + # bands needed by the steps + if any(s.bands is None for s in steps): + needed, slot = None, None # all bands + else: + needed = sorted({i for s in steps for i in s.bands}) + slot = {iwl: k for k, iwl in enumerate(needed)} + has_cube = needed != [] + aux_names = sorted({n for s in steps for n in s.aux}) + + arrays, depths = [], [] + if has_cube: + bands = self._require('bands').transpose('wl', 'y', 'x').chunk({'wl': -1, **chunks}) + if needed is not None: + bands = bands.isel(wl=needed) # fused into the read: other bands are not loaded + arrays.append(bands.data) + depths.append({0: 0, 1: halo, 2: halo}) + for name in aux_names: + arrays.append(self._require(name).transpose('y', 'x').chunk(chunks).data) + depths.append({0: halo, 1: halo}) + + if halo > 0: + arrays = [overlap(a, depth=d, boundary='none') for a, d in zip(arrays, depths)] + + flags = da.map_blocks(_make_block_fn(steps, slot, has_cube, aux_names), *arrays, + drop_axis=0 if has_cube else [], + dtype=np.uint32, + meta=np.empty((0, 0), dtype=np.uint32)) + if halo > 0: + flags = trim_internal(flags, {0: halo, 1: halo}, boundary='none') + return flags + + def _run(self, steps): + '''Compute `steps` (in parallel) and OR their bits into ``self.flags``.''' + result = self._flags_lazy(steps).compute() + if self.flags is None: + self.flags = result + else: + np.bitwise_or(self.flags, result, out=self.flags) + + def _nodata_step(self, bitmask=0, name='nodata', description='nodata in input image'): + '''Step: flag nodata, i.e. NaN or crazy values (> 1e3) in the band with index 1.''' + self._register(bitmask, name, description) + + def fn(t): + b = t.band(1) + _set(t.f, bitmask, np.isnan(b) | (b > 1e3)) + + return _Step(fn, [1], 0, ()) + + def _pixel_size(self): + '''Native pixel size (units of the ``x`` coordinate, m for projected rasters); None if unknown.''' + x = self.prod['x'].values if 'x' in self.prod.coords else None + if x is None or x.size < 2: + return None + return abs(float(x[1] - x[0])) + + def _ocm_factor(self): + '''Integer downscaling factor so that the OmniCloudMask input is at about `OCM_resolution`.''' + res = self._pixel_size() + if not self.OCM_resolution or not res: + return 1 + return max(1, int(round(self.OCM_resolution / res))) + + def _get_omnicloudmask(self, + bitmasks=OCM_BITS, + names=('OCM_Thick_Cloud', 'OCM_Thin_Cloud', 'OCM_Cloud_Shadow'), + descriptions=('Thick Cloud from OmniCloudMask version ' + _OCM_VERSION, + 'Thin Cloud from OmniCloudMask version ' + _OCM_VERSION, + 'Cloud Shadow from OmniCloudMask version ' + _OCM_VERSION)): + '''Apply OmniCloudMask for clouds and cloud shadows masking. + + Outputs: 0 = Clear, 1 = Thick Cloud, 2 = Thin Cloud, 3 = Cloud Shadow. + See https://github.com/DPIRD-DMA/OmniCloudMask + + Run on a downscaled image to save time: the red, green and NIR bands are averaged (ignoring NaN) over + ``factor x factor`` blocks, with ``factor`` = `OCM_resolution` / native pixel size rounded + (e.g. 6 for Sentinel-2 at 10 m and 60 m), the prediction is done on this coarse image (lazy bands: + only the coarse image is held in memory), then each coarse class is copied to the + ``factor x factor`` native pixels it covers (nearest). The mask and the flag bits are therefore at + native resolution, with blocky edges of `OCM_resolution`. + + Sets ``self.omnimask`` (uint8, native grid) and the bits `bitmasks` of ``self.flags``. + + :return: number of flagged pixels of each bit of `bitmasks` + ''' + iwl = [self._wl_index(wl) for wl in (self.OCM_Rband, self.OCM_Gband, self.OCM_NIRband)] + rgnir = self.prod.bands.isel(wl=iwl) + for ii in range(len(bitmasks)): + self._register(bitmasks[ii], names[ii], descriptions[ii]) + + factor = self._ocm_factor() + ny, nx = rgnir.sizes['y'], rgnir.sizes['x'] + if factor > 1: + # incomplete blocks at the bottom / right edges are averaged over their valid pixels + # (the mean ignores NaN by default; recent xarray no longer accepts ``skipna`` here) + rgnir = rgnir.coarsen(y=factor, x=factor, boundary='pad').mean() + res = self._pixel_size() + logging.info('OmniCloudMask processing on {:d} x {:d} pixels{}'.format( + rgnir.sizes['y'], rgnir.sizes['x'], + '' if res is None else ' ({:g} m)'.format(res * factor))) + + import omnicloudmask as OCM + + coarse = OCM.predict_from_array(np.asarray(rgnir.fillna(0).transpose('wl', 'y', 'x').values, + dtype=np.float32), + batch_size=self.OCM_batch_size, + inference_dtype=self.OCM_inference_dtype, + inference_device=self.OCM_inference_device, + mosaic_device=self.OCM_mosaic_device + )[0].astype(np.uint8) + + # back to the native grid: pixel (i, j) takes the class of the block (i // factor, j // factor) + if factor > 1: + omnimask = coarse[np.ix_(np.arange(ny) // factor, np.arange(nx) // factor)] + else: + omnimask = coarse + self.omnimask = omnimask + + # set flags raster (in place, uint32) + counts = [] + for value, bit in zip((1, 2, 3), bitmasks): + cond = omnimask == value + _set(self.flags, bit, cond) + counts.append(int(np.count_nonzero(cond))) + return counts + + def _water_step(self, + bitmasks=(3, 4), + names=('water_swir_visible_index', 'water_red_visible_index'), + descriptions=('water mask from normalized index from swir and visible band', + 'water mask from normalized index from nir and visible band, ' + 'warning could fail for turbid waters')): + '''Step: water/land masks from the normalised indices (visible, SWIR) and (visible, NIR).''' + ivis, inir, iswir = (self._wl_index(w) for w in (self.bvis, self.bnir, self.bswir)) + self._register(bitmasks[0], names[0], descriptions[0] + + ', bands centered on {:.1f} and {:.1f} nm'.format(self.bvis, self.bswir) + + ', threshold={:.2f}'.format(self.vis_swir_index_threshold)) + self._register(bitmasks[1], names[1], descriptions[1] + + ', bands centered on {:.1f} and {:.1f} nm'.format(self.bvis, self.bnir) + + ', threshold={:.2f}'.format(self.ndwi_threshold)) + + def fn(t): + vis = t.band(ivis) + with np.errstate(divide='ignore', invalid='ignore'): + other = t.band(iswir) + _set(t.f, bitmasks[0], (vis - other) / (vis + other) > self.vis_swir_index_threshold) + other = t.band(inir) + _set(t.f, bitmasks[1], (vis - other) / (vis + other) > self.ndwi_threshold) + + return _Step(fn, [ivis, inir, iswir], 0, ()) + def nodata_mask(self, bitmask=0, name='nodata', @@ -383,7 +571,7 @@ def cirrus_mask(self, ''' logging.info('cirrus masking') - cirrus = self.prod.bands.sel(wl=self.bcirrus, method='nearest') + icirrus = self._wl_index(self.bcirrus) thresholds = [self.thin_cirrus_threshold, self.opac_cirrus_threshold] for ii in range(2): self._register(bitmasks[ii], names[ii], descriptions[ii] + ', threshold {:.4f}'.format(thresholds[ii])) @@ -416,12 +604,19 @@ def _surfwater_step(self, 'cloud and shadow mask from surfwater input file')): '''Step: land / water / cloud-and-shadow classes of the 2-D input variable ``surfwater``.''' for ii in range(3): - # set naming and description as attributes - self.flag_descriptions[bitmasks[ii]] = descriptions[ii] - self.flag_names[bitmasks[ii]] = names[ii] + self._register(bitmasks[ii], names[ii], descriptions[ii]) + self._require('surfwater') + + def fn(t): + sw = t.aux['surfwater'] + _set(t.f, bitmasks[0], sw == 0) + _set(t.f, bitmasks[1], sw == 1) + _set(t.f, bitmasks[2], sw >= 2) + + return _Step(fn, [], 0, ('surfwater',)) def duplicate_landsat_flags(self, - bitmasks=[11, 12, 13, 14, 15, 16, 17], + bitmasks=[14, 15, 16, 17, 18, 19, 20], landsat_bitmasks=[1, 2, 3, 4, 5, 6, 7], names=['l1_dilated_cloud', 'l1_cirrus', 'l1_cloud', 'l1_cloud_shadow', 'l1_snow', 'l1_clear', 'l1_water'], @@ -446,7 +641,16 @@ def duplicate_landsat_flags(self, ''' logging.info('duplicating landsat level 1 flags') - self._run([self._landsat_step(*args, **kwargs)]) + for ii, bit in enumerate(bitmasks): + self._register(bit, names[ii], descriptions[ii]) + self._require(flags_landsat_band) + + def fn(t): + f1 = t.aux[flags_landsat_band] + for ii, bit in enumerate(bitmasks): + _set(t.f, bit, (f1 & (1 << landsat_bitmasks[ii])) != 0) + + return _Step(fn, [], 0, (flags_landsat_band,)) # ------------------------------------------------------------------ # statistics @@ -513,15 +717,20 @@ def process(self, plus the dictionary of flags statistics :return: see :param output ''' - # apply the masking processors - self.nodata_mask() - if self.sentinel2: - self.cloud_mask() - else: - self.duplicate_landsat_flags() - self.water_mask() + self.flag_names[:] = None + self.flag_descriptions[:] = None + self.flag_stats = {} + + # masks based on dask and tile approach, in one lazy graph (cloud/cloud-shadow screening is + # OmniCloudMask, run separately below; s2cloudless bits 1-2 are no longer used, see module doc) + steps = [self._nodata_step()] + + if not self.sentinel2: + steps.append(self.duplicate_landsat_flags()) + steps.append(self._water_step()) + if self.bcirrus: - steps.append(self._cirrus_step()) + steps.append(self.cirrus_mask()) steps.append(self._high_swir_step()) steps.append(self._surfwater_step()) diff --git a/grs/run.py b/grs/run.py index 4a720aa..8336d52 100644 --- a/grs/run.py +++ b/grs/run.py @@ -1,9 +1,9 @@ ''' Executable to process Sentinel-2 L1C images for aquatic environment Usage: - grs [--cams_file file] [--odir ] [--resolution res] [--max_cloud_cover max_cc] [--scale_aot factor]\ - [--opac_model name] [--levname ] [--no_clobber] [--allpixels] [--surfwater file] [--dem_file file]\ - [--suffix suffix] [--snap_compliant] + grs [--cams_file file] [--odir ] [--resolution res] [--aot_resolution res]\ + [--max_cloud_cover max_cc] [--scale_aot factor] [--opac_model name] [--levname ] [--no_clobber]\ + [--allpixels] [--surfwater file] [--dem_file file] [--suffix suffix] [--snap_compliant] grs -h | --help grs -v | --version @@ -58,6 +58,14 @@ misc = misc() +def set_ofile(filename: str, odir='', level_name='L2GRS', suffix='') -> Path: + """Output path: level name of `filename` replaced by `level_name`, extension removed, `suffix` appended.""" + outfile = filename + for level in ('L1C', 'L1GT', 'L1TP'): + outfile = outfile.replace(level, level_name) + return Path(odir, Path(outfile).stem + suffix) + + def s2_cloud_cover(safe): ''' Cloud cover (0-1) of a Sentinel-2 L1C image, from ``Cloud_Coverage_Assessment`` of its @@ -70,6 +78,25 @@ def s2_cloud_cover(safe): return float(node.text) / 100 +def limit_malloc_arenas(n=2): + """ + Limit the number of glibc malloc arenas to `n` (as ``MALLOC_ARENA_MAX=n``), unless ``MALLOC_ARENA_MAX`` is + set in the environment. + + With one arena per thread, the memory freed by the threads that read and process the image is kept by + the process: on a Sentinel-2 tile at 20 m the peak memory goes from about 12-13 GB to 9.5-10 GB with 2 + arenas, with the same output. Call it at start-up, before the threads are created; no effect on systems + without glibc. + """ + if os.environ.get('MALLOC_ARENA_MAX'): + return + try: + libc = ctypes.CDLL(ctypes.util.find_library('c')) + libc.mallopt(-8, int(n)) # M_ARENA_MAX + except (OSError, AttributeError, TypeError): + pass + + def main(): # before any thread is started limit_malloc_arenas() diff --git a/grs/tests/integration_tests/conftest.py b/grs/tests/integration_tests/conftest.py new file mode 100644 index 0000000..c0e02fa --- /dev/null +++ b/grs/tests/integration_tests/conftest.py @@ -0,0 +1,52 @@ +"""Fixtures of the integration tests: full processing chain on the small L1C subset of `grs/tests/data`.""" + +import os + +import pytest + +DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data') +# 128 x 128 pixels at 60 m of S2A 2021-02-11 over the Camargue (tile 31TFJ), and its CAMS data +L1C_SUBSET = os.path.join(DATA_DIR, 'S2A_MSIL1C_20210211_T31TFJ_camargue_subset.nc') +CAMS_SUBSET = os.path.join(DATA_DIR, 'cams_forecast_2021-02-11_camargue.nc') + + +@pytest.fixture(scope='session') +def l1c_path(): + return L1C_SUBSET + + +@pytest.fixture(scope='session') +def cams_path(): + return CAMS_SUBSET + + +def lut_files(): + """ + Look-up tables used by this end-to-end test: those of grs/config.yml, in the folder given by the + environment variable GRS_TEST_GRSDATA if set (e.g. a local copy of grsdata). + """ + from grs.grs_process import GRSDATA, TOALUT, TRANSLUT + grsdata = os.environ.get('GRS_TEST_GRSDATA', GRSDATA) + if grsdata is None: + return () + return os.path.join(grsdata, TOALUT), os.path.join(grsdata, TRANSLUT) + + +def luts_available(): + files = lut_files() + return bool(files) and all(os.path.exists(f) for f in files) + + +@pytest.fixture(scope='session') +def l2a_zarr(tmp_path_factory, l1c_path, cams_path): + """ + L2A Zarr product made once by the full processing chain from the test L1C subset (path of the store). + """ + if not luts_available(): + pytest.skip('look-up tables not found (set GRS_TEST_GRSDATA to the folder of the LUTs)') + import grs + odir = tmp_path_factory.mktemp('l2a_zarr') / 'l2a' + process = grs.Process() + process.lut_file, process.trans_lut_file = lut_files() + process.execute(l1c_path, cams_file=cams_path, resolution=60, odir=str(odir)) + return process.write_output(fmt='zarr') diff --git a/grs/tests/unit/conftest.py b/grs/tests/unit/conftest.py index 1a0a904..1cef790 100644 --- a/grs/tests/unit/conftest.py +++ b/grs/tests/unit/conftest.py @@ -8,6 +8,9 @@ # 128 x 128 pixels at 60 m of S2A 2021-02-11 over the Camargue (tile 31TFJ), and its CAMS data L1C_SUBSET = os.path.join(DATA_DIR, 'S2A_MSIL1C_20210211_T31TFJ_camargue_subset.nc') CAMS_SUBSET = os.path.join(DATA_DIR, 'cams_forecast_2021-02-11_camargue.nc') +# full Level-1 image of the subset, used only when it is on the computer +SAFE = ('/data/satellite/Sentinel-2/L1C/31TFJ/2021/02/11/' + 'S2A_MSIL1C_20210211T104151_N0500_R008_T31TFJ_20230608T124831.SAFE') @pytest.fixture(scope='session') @@ -27,11 +30,14 @@ def lut_files(): """ from grs.grs_process import GRSDATA, TOALUT, TRANSLUT grsdata = os.environ.get('GRS_TEST_GRSDATA', GRSDATA) + if grsdata is None: + return () return os.path.join(grsdata, TOALUT), os.path.join(grsdata, TRANSLUT) def luts_available(): - return all(os.path.exists(f) for f in lut_files()) + files = lut_files() + return bool(files) and all(os.path.exists(f) for f in files) @pytest.fixture(scope='session') diff --git a/pyproject.toml b/pyproject.toml index 63e0ea6..a342da5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,6 @@ build-backend = "setuptools.build_meta" [project] name = "grs" -version = "2.2.0" description = "GRS processor for atmospheric correction of high-spatial resolution and multispectral satellite images" readme = "pypi_README.rst" authors = [{ name = "Tristan Harmel", email = "tristan.harmel@gmail.com" }] @@ -21,7 +20,7 @@ classifiers = [ ] keywords = ["Sentinel-2","Landsat-8","Landsat-9","atmospheric correction", "EO satellite"] requires-python = ">=3.12" -dynamic = ["dependencies"] +dynamic = ["version", "dependencies"] [tool.setuptools.packages.find] where = ["."] @@ -56,7 +55,7 @@ docs = [ "ipython", ] # packages of the example notebooks (CAMS download, maps, interactive viewer) -notebooks = ["cdsapi>=0.7.4", "cartopy", "grstbx"] +notebooks = ["cartopy", "grstbx"] [project.urls] Homepage = "https://github.com/CNES/GRSprocessor" diff --git a/requirements.txt b/requirements.txt index b36fa45..69104e1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,15 +1,22 @@ # Runtime dependencies of grs (read by pyproject.toml). # GRSdriver >= 2.0 reads the Level-1 products without EOReader, sertit, fiona or the GDAL # Python bindings: everything installs from PyPI wheels. +cdsapi>=0.7.4 +dask>=2024.10.0 docopt>=0.6.2 GRSdriver>=2.0.4 +h5netcdf>=1.3.0 +h5py>=3.11.0 matplotlib>=3.9.0 netCDF4>=1.7.2 numba>=0.60.0 numpy>=2.0 +omnicloudmask pandas>=2.2.3 +platformdirs>=4.0 PyYAML>=6.0.2 rioxarray>=0.17.0 s2cloudless>=1.7.3 scipy>=1.14.1 xarray>=2024.10.0 +zarr>=2.18