Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 55 additions & 21 deletions .github/actions/mirror-to-gitlab/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."
Expand Down
63 changes: 59 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down Expand Up @@ -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};
Expand Down
17 changes: 17 additions & 0 deletions .github/workflows/pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion grs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@
'''

__package__ = 'grs'
__version__ = '2.2.0'
__version__ = '3.0.0'


import importlib
Expand Down
162 changes: 113 additions & 49 deletions grs/grs_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<cams_dir>/<tile>/<date>-forecast_<tile>.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:
Expand Down Expand Up @@ -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
######################################
Expand Down
Loading
Loading