diff --git a/scripts/ridge-bake/README.md b/scripts/ridge-bake/README.md index 97b02a77..ddb17abf 100644 --- a/scripts/ridge-bake/README.md +++ b/scripts/ridge-bake/README.md @@ -8,9 +8,9 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffe python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] ``` -Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin. +Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. -Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice). +Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh` ## Tiles per preset (`places.json`) diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 42769221..c9dd030b 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -1,14 +1,12 @@ """Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index. python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] - python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below) -The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour +The runtime reads manifest.json and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit). -The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN.""" +The pure parts (budget, bake_id, index) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN.""" import os, sys, json, math, shutil, hashlib, argparse, tempfile from pathlib import Path -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from refusal import Refusal @@ -39,57 +37,14 @@ ATTRIBUTION = dict( dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model') -# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) -_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} -_numnull = {'type': ['number', 'null']} -_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it -def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props} -def _objnull(**props): return dict(_obj(**props), type=['object', 'null']) -_file = _obj(file=_str, bytes=_int) -SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': { - 'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str, - place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz), - view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num), - curvature=_obj(r_earth_m=_num, k_ref=_num), - encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), - camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured."), - cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull), - 'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."}, - tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)}, - 'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."}, - bytes=_int, - attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)), - 'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}} def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp' -def validate(x, s, path='$'): - """The subset of JSON Schema SCHEMA uses; raises Refusal naming the path.""" - if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) - tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} - if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise Refusal(f'{path}: not a {"/".join(tys)}') - if s.get('format') == 'iana-tz': - try: ZoneInfo(x) - except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f'{path}: {x!r} is not a time zone the system knows') - if 'const' in s and x != s['const']: raise Refusal(f"{path}: must be {s['const']!r}") - if 'enum' in s and x not in s['enum']: raise Refusal(f'{path}: not one of {s["enum"]}') - if 'maximum' in s and x > s['maximum']: raise Refusal(f'{path}: above {s["maximum"]}') - if isinstance(x, list): - if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise Refusal(f'{path}: wrong length') - for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]') - if isinstance(x, dict): - props = s.get('properties', {}); extra = s.get('additionalProperties', True) - for k in s.get('required', []): - if k not in x: raise Refusal(f'{path}: missing {k}') - for k, v in x.items(): - if k in props: validate(v, props[k], f'{path}.{k}') - elif extra is False: raise Refusal(f'{path}: extra key {k}') - elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}') - def validate_manifest(m): - """The schema plus what it cannot say: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" + """Check the baked manifest's structural invariants: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, there are TILES tiles of one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" import ridge - validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards']); v = m['view'] + k = len(m['cards']); v = m['view'] if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise Refusal(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)") + if len(m['tiles']) != TILES: raise Refusal(f"$.tiles: {len(m['tiles'])} tiles, expected {TILES}") for t, row in enumerate(m['tiles']): if len(row) != k: raise Refusal(f'$.tiles[{t}]: {len(row)} entries for {k} cards') for i, e in enumerate(row): @@ -226,7 +181,6 @@ def write_bake(out, place, view, meta, packed, opaque, default=None): (tmp / 'manifest.json').write_bytes(text.encode('utf-8')) # bytes, so the platform's newline cannot move the file under its id idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={}) old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id']) - validate(idx, SCHEMA['$defs']['index']) if dest.exists(): shutil.rmtree(dest) os.rename(tmp, dest); (out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\n').encode('utf-8')); os.replace(out / '.index.tmp', idx_path) if old and old != name: shutil.rmtree(out / old, ignore_errors=True) @@ -300,10 +254,8 @@ def sheet(bake): return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0)))) def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true') + ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place'); ap.add_argument('--tiles', required=True); ap.add_argument('--out', required=True); ap.add_argument('--work'); ap.add_argument('--sheet') a = ap.parse_args(argv) - if a.write_schema: (HERE / 'ridge-bake.schema.json').write_bytes((json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n').encode('utf-8')); return 0 - if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required') os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True) bake = bake_place(a.place) if a.sheet: Path(a.sheet).write_bytes(sheet(bake)) diff --git a/scripts/ridge-bake/refusal.py b/scripts/ridge-bake/refusal.py index 213d8369..26423721 100644 --- a/scripts/ridge-bake/refusal.py +++ b/scripts/ridge-bake/refusal.py @@ -1,2 +1,2 @@ -"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake. The fixtures catch this class only, so an exception from numpy or the standard library reaching them is a crash (mutate.py: CRASHED), never a kill.""" +"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake.""" class Refusal(ValueError): pass diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json deleted file mode 100644 index 3f7f9b41..00000000 --- a/scripts/ridge-bake/ridge-bake.schema.json +++ /dev/null @@ -1,327 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "ridge-bake manifest v3 and index v1", - "$defs": { - "manifest": { - "type": "object", - "required": [ - "schema", - "baker_version", - "bake_id", - "place", - "view", - "curvature", - "encoding", - "camera", - "cards", - "tiles", - "bytes", - "attribution" - ], - "additionalProperties": false, - "properties": { - "schema": { - "const": 3 - }, - "baker_version": { - "type": "integer" - }, - "bake_id": { - "type": "string" - }, - "place": { - "type": "object", - "required": [ - "id", - "name", - "lat", - "lon", - "altitude_km", - "eye_m", - "tz" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "lat": { - "type": "number" - }, - "lon": { - "type": "number" - }, - "altitude_km": { - "type": "number" - }, - "eye_m": { - "type": "number" - }, - "tz": { - "type": "string", - "format": "iana-tz" - } - } - }, - "view": { - "type": "object", - "required": [ - "look_az_deg", - "ring_w", - "tile_w", - "tiles", - "apron", - "plane_h", - "px_per_deg_h", - "px_per_deg_v", - "exaggeration", - "horizon_row", - "sky_row", - "near_row" - ], - "additionalProperties": false, - "properties": { - "look_az_deg": { - "type": "number" - }, - "ring_w": { - "const": 6400 - }, - "tile_w": { - "const": 200 - }, - "tiles": { - "const": 32 - }, - "apron": { - "const": 2 - }, - "plane_h": { - "type": "integer" - }, - "px_per_deg_h": { - "type": "number" - }, - "px_per_deg_v": { - "type": "number" - }, - "exaggeration": { - "type": "number" - }, - "horizon_row": { - "type": "number" - }, - "sky_row": { - "type": "number" - }, - "near_row": { - "type": "number" - } - } - }, - "curvature": { - "type": "object", - "required": [ - "r_earth_m", - "k_ref" - ], - "additionalProperties": false, - "properties": { - "r_earth_m": { - "type": "number" - }, - "k_ref": { - "type": "number" - } - } - }, - "encoding": { - "type": "object", - "required": [ - "log_d_min", - "log_d_max", - "normal" - ], - "additionalProperties": false, - "properties": { - "log_d_min": { - "type": "number" - }, - "log_d_max": { - "type": "number" - }, - "normal": { - "const": "rt8" - } - } - }, - "camera": { - "type": "object", - "required": [ - "r_max_m", - "r_max_forward_m" - ], - "additionalProperties": false, - "properties": { - "r_max_m": { - "type": "number" - }, - "r_max_forward_m": { - "type": "number" - } - }, - "description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured." - }, - "cards": { - "type": "array", - "minItems": 1, - "maxItems": 6, - "items": { - "type": "object", - "required": [ - "near_m", - "far_m" - ], - "additionalProperties": false, - "properties": { - "near_m": { - "type": [ - "number", - "null" - ] - }, - "far_m": { - "type": [ - "number", - "null" - ] - } - } - }, - "description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends." - }, - "tiles": { - "type": "array", - "minItems": 32, - "maxItems": 32, - "items": { - "type": "array", - "minItems": 1, - "maxItems": 6, - "items": { - "type": [ - "object", - "null" - ], - "required": [ - "top", - "h", - "distance_m", - "colour", - "geometry" - ], - "additionalProperties": false, - "properties": { - "top": { - "type": "integer" - }, - "h": { - "type": "integer" - }, - "distance_m": { - "type": "number" - }, - "colour": { - "type": "object", - "required": [ - "file", - "bytes" - ], - "additionalProperties": false, - "properties": { - "file": { - "type": "string" - }, - "bytes": { - "type": "integer" - } - } - }, - "geometry": { - "type": "object", - "required": [ - "file", - "bytes" - ], - "additionalProperties": false, - "properties": { - "file": { - "type": "string" - }, - "bytes": { - "type": "integer" - } - } - } - } - } - }, - "description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance." - }, - "bytes": { - "type": "integer" - }, - "attribution": { - "type": "object", - "required": [ - "credit_line", - "licence", - "dem_source", - "url" - ], - "additionalProperties": false, - "properties": { - "credit_line": { - "type": "string" - }, - "licence": { - "type": "string" - }, - "dem_source": { - "type": "string" - }, - "url": { - "type": "string" - } - } - } - } - }, - "index": { - "type": "object", - "required": [ - "schema", - "default", - "places" - ], - "additionalProperties": false, - "properties": { - "schema": { - "const": 1 - }, - "default": { - "type": "string" - }, - "places": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - } -} diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py deleted file mode 100644 index 94702e0d..00000000 --- a/scripts/ridge-bake/tests/mutate.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails. - venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError raised by the fixtures' own code)""" -import os, shutil, subprocess, sys, tempfile -HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..') -MUTANTS = { # name -> (text in ridge.py or export.py, replacement) - 'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"), - 'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "), - 'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"), - 'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"), - 'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"), - 'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"), - 'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"), - 'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"), - 'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"), - 'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"), - 'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"), - 'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""), - 'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"), - 'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"), - 'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"), - 'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"), - 'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "), - 'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"), - 'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"), - 'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"), - 'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"), - 'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"), - 'wall: no row is flagged (the flag is dropped)': ("Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = False"), - 'near: the cap to the silhouette of the terrain at the clip is dropped': ("an = np.minimum(an, a[0][None, :])", "an = an"), - 'near: rows under the clip are flagged wall': ("Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn)", "Wl[i, :, x] = hit & ((idx == 0) | (kp < kn)); Nr[i, :, x] = hit & (kp < kn)"), - 'near: albedo takes the face up (the wall rule on near rows)': ("albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz), material)", "albedo(g[1], np.where(Wl[i, sl] | Nr[i, sl], 1.0, g[4] / nz), material)"), - 'near: albedo reads the height of the far march first sample': ("albedo(g[1], np.where(Wl[i, sl]", "albedo(np.where(Nr[i, sl], h[int(np.searchsorted(d, NEAR_CLIP_M))][None, :], g[1]), np.where(Wl[i, sl]"), - 'near: the march starts at 20 m': ("NEAR_START_M = 1.0 ", "NEAR_START_M = 20.0 "), - 'near: the heights are stored float32': (", np.float64) for dk in d])", ", np.float32) for dk in d])"), - 'near: the place prefilter is not applied': ("; a, h = prefilter(d, h, sigma_m)\n", "; a, h = prefilter(d, h, 0.0)\n"), - 'near: the far normals are computed over the joined march (not apart)': ("nn, nf = normals(dn, hn), normals(d, h)", "nj_ = normals(np.concatenate([dn, d]), np.concatenate([hn, h])); nn, nf = tuple(x[:len(dn)] for x in nj_), tuple(x[len(dn):] for x in nj_)"), - 'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise Refusal", "if False: raise Refusal"), - 'pack: near pixels count as solid terrain': ("solid = (al >= 0.5) & ~wl & ~nr;", "solid = (al >= 0.5) & ~wl;"), - 'pack: the non-wall fallback pool reads near pixels': ("((al > 0) & ~wl & ~nr, ld)", "((al > 0) & ~wl, ld)"), - 'pack: the lit fallback pool reads near pixels': ("((al > 0) & ~nr, ld)", "(al > 0, ld)"), - 'pack: the apron fallback pool reads near pixels': ("((c['alpha'] > 0) & ~c['near'], c['logd'])", "(c['alpha'] > 0, c['logd'])"), - 'pack: a tile with nothing outside the near ground is not at the clip': ("if pool else ridge.NEAR_CLIP_M", "if pool else 0.0"), - 'r_max: the tile median binds, not the nearest terrain': ("r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1)"), - 'r_max: near pixels do not bind at the clip': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "None"), - 'r_max: near pixels bind only in a tile with no other solid pixel': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() and not solid.any() else None"), - 'r_max: near pixels bind only where they outnumber the solid ones': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).sum() > solid.sum() else None"), - 'r_max: the nearest pixel is the farthest solid one': ("float(np.exp(ld[solid].min())) if solid.any() else None, ridge", "float(np.exp(ld[solid].max())) if solid.any() else None, ridge"), - 'near clip: the writer compares the float32 distance strictly': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if rmin < ridge.NEAR_CLIP_M: raise"), - 'near clip: the march starts nearer than the clip': ("d = [NEAR_CLIP_M]", "d = [100.0]"), - 'near clip: a card 0 inside the clip is accepted by the writer': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if False: raise"), - 'view: the 1x floor is back': ("lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG", "lo, hi = HPX_DEG, 10 * HPX_DEG"), - 'view: the horizon anchor is dropped (the scale is the skyline fit alone)': ("ppd = float(np.clip(min(fit, hold), lo, hi))", "ppd = float(np.clip(fit, lo, hi))"), - 'view: a skyline that cannot hold the ground rows is not refused': ("if hold < lo: raise", "if False: raise"), - 'view: the ground rows are not asked for (GROUND_ROWS_MIN 0)': ("GROUND_ROWS_MIN = 150 ", "GROUND_ROWS_MIN = 0 "), - 'validate_manifest: a plane short of its ground rows is accepted': ("if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise", "if False: raise"), - 'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"), - 'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"), - 'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"), - 'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"), - 'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"), - 'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"), - 'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"), - 'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"), - 'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"), - 'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"), - 'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["), - 'write: the per-tile cover check is dropped': ("except Refusal as ex: raise Refusal(f'tile {t}: {ex}')", "except Refusal as ex: pass"), - 'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"), - 'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"), - 'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"), - 'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"), - 'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"), - 'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"), - 'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "), - 'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg, phis) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg, phis) for d in row"), - 'r_max_forward: the forward offset is searched over the whole circle': ("r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_fwd = solve_r_max(near, bands, ppd)"), - 'r_max_forward: the resident gate is not checked at the forward offset': ("for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget", "for r in (camera['r_max_m'],): check_budget"), - 'r_max_forward: a forward offset below r_max_m is accepted': ("if camera['r_max_forward_m'] < camera['r_max_m']: raise", "if False: raise"), - 'fit: the line is the least squares of 33 uniform samples, as the first gate drew it': ("x, w = np.polynomial.legendre.leggauss(FIT_QUAD)", "x = np.linspace(-1, 1, 33); w = np.full(33, 2 / 33)"), - 'fit: the line is a two-node quadrature': ("FIT_QUAD = 48 ", "FIT_QUAD = 2 "), - 'write: the manifest is written as platform text (CRLF on Windows)': ("(tmp / 'manifest.json').write_bytes(text.encode('utf-8'))", "(tmp / 'manifest.json').write_text(text)"), - 'write: the index is written as platform text (CRLF on Windows)': ("(out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\\n').encode('utf-8'))", "(out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\\n')"), - 'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"), - 'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"), - 'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"), - 'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl & ~nr; any_solid", "solid = (al >= 0.5) & ~nr; any_solid"), - 'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"), - 'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"), - 'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"), - 'material: a null steep override still paints steep faces rock grey (strata do not hold on cliffs)': ("if material['steep']: c = c + (np.asarray(material['steep']['colour'])", "if True: c = c + (np.asarray((material['steep'] or dict(colour=[0.47, 0.44, 0.41]))['colour'])"), - 'material: the ramps apply in reverse order': ("for r in material['ramps']:", "for r in reversed(material['ramps']):"), - 'material: a null snow still snows': ("sn = material['snow']", "sn = material['snow'] or dict(from_m=1900, to_m=2300, colour=[0.93, 0.95, 0.97])"), - 'material: an unknown name falls back to alpine': ("if name not in tab: raise Refusal(", "if name not in tab: name = 'alpine'; ("), - 'material: the cards take the alpine colours whatever the place names': ("ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=material)", "ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=ridge.load_material('alpine'))"), - 'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"), - 'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""), - 'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"), -} -EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run) -def execute(edit): - """Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class, directory of the innermost traceback frame)] of every FAIL line, last stderr line).""" - d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')) - try: - if edit: - a, b = edit; p = next((q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()), None) - if p is None: return None, [], 'the mutant text is in neither ridge.py nor export.py' - s = open(p).read(); open(p, 'w').write(s.replace(a, b)) - r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True) - finally: shutil.rmtree(d) - fails = [(f[0][4:].strip(), f[1].strip(), os.path.dirname(os.path.abspath(f[2].strip()))) for f in (l.split(' | ', 3) for l in r.stdout.splitlines() if l.startswith('FAIL')) if len(f) == 4] - return r.returncode, fails, (r.stderr.strip().splitlines() or ['no output'])[-1][:200] -def run(item): - """KILLED: at least one fixture failed on an assertion the test code itself raised (an AssertionError whose innermost traceback frame lies in the tests directory). CRASHED: the run failed but no fixture did that (every FAIL is another exception, NameError or a numpy error and the like, or an assert inside the baker, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed.""" - name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c, w in fails if c == 'AssertionError' and w == HERE] - state = 'CRASHED ' if rc is None or (rc and not asserts) else 'KILLED ' if rc else 'SURVIVED ' - why = ', '.join(f'{n}[{c}{"" if w == HERE else " in " + os.path.basename(w)}]' for n, c, w in fails) if fails else err - line = state + name + ' -> ' + why; print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished - return line, state != 'KILLED ' -def baseline(): - """The unmutated copy must pass every fixture before any mutant means anything: a broken environment would kill them all.""" - rc, fails, err = execute(None) - if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c, w in fails) or err), file=sys.stderr, flush=True); sys.exit(2) - print('BASELINE ok: the unmutated copy passes every fixture', file=sys.stderr, flush=True) -if __name__ == '__main__': - from concurrent.futures import ThreadPoolExecutor - baseline() - with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])])) - for line, _ in res: print(line, flush=True) - for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why) - sys.exit(1 if any(sv for _, sv in res) else 0) diff --git a/scripts/ridge-bake/tests/run.sh b/scripts/ridge-bake/tests/run.sh index f97a126c..71e2eb76 100755 --- a/scripts/ridge-bake/tests/run.sh +++ b/scripts/ridge-bake/tests/run.sh @@ -1,7 +1,7 @@ #!/bin/sh -# Usage: RIDGE_PY= RIDGE_TILES= tests/run.sh [test_ridge.py|mutate.py] +# Usage: RIDGE_PY= RIDGE_TILES= tests/run.sh # RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR. : "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}" export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK" HERE=$(cd "$(dirname "$0")" && pwd) -exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}" +exec "$RIDGE_PY" -I "$HERE/test_ridge.py" diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index 2979947e..25a8c2d4 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -1,5 +1,5 @@ """Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure). -RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy). +RIDGE_SRC selects the source directory (default ..). Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist).""" import os, sys, math, json, shutil, tempfile, traceback SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them) @@ -226,7 +226,7 @@ def _pins(): assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12 def test_schema3(): - """The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned.""" + """The manifest validates; a tile array of the wrong length, a missing card, a file named for another tile, an all-null card, and a wrong byte total are refused; the layout constants are pinned.""" _pins(); d = tempfile.mkdtemp() try: b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m)) @@ -236,15 +236,9 @@ def test_schema3(): try: export.validate_manifest(x) except export.Refusal: return raise AssertionError(why) - bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated') - bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated') - bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated') + bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated') + bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated') bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated') - for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them - bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated') - bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated') - bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated') - assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)' finally: shutil.rmtree(d) def test_manifest_v3_writer(): """Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a @@ -268,7 +262,7 @@ def test_manifest_v3_writer(): for i, e in enumerate(row): for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind) assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF) - idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='toy', places={'toy': a.name}) + idx = json.load(open(d + '/a/index.json')); assert idx == dict(schema=1, default='toy', places={'toy': a.name}) want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.', licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution'] c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy' @@ -721,5 +715,5 @@ if __name__ == '__main__': fails = 0 for t in TESTS: try: t(); print("PASS", t.__name__) - except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) # name | class | file of the innermost frame | repr: mutate.py kills only on an AssertionError raised in this directory + except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) print("failures:", fails); sys.exit(1 if fails else 0)