Skip to content
Open
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
29 changes: 24 additions & 5 deletions astra.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2428,7 +2428,7 @@ analyses:
npoint, ntaken, nexp and nflagged HEALSparse maps, one file per
order-5 pixel.
inputs: [tile_final_cat_published]
decisions: [tile_universe, seam_realization, pixel_completeness]
decisions: [tile_universe, seam_realization, pixel_completeness, row_partitioning]
decisions:
tile_universe:
label: Dateline-redundant and polar-cap tiles are not in the catalogue
Expand Down Expand Up @@ -2471,10 +2471,11 @@ analyses:
rationale: >-
A pixel's tile list is every tile whose 0.4 deg enclosing cap
intersects it (exposures: those used by the listed tiles), fixed before
processing. The pixel is built when every listed source has a
terminal state in the run index. A source that failed after its
retries contributes no rows, as per_unit_completeness already
keeps a failed unit out. The file is written once.
processing. The pixel is built when every listed source has its
final success manifest in the product store or the operator has
named it in abandoned.txt. Abandoned sources contribute no rows;
all other missing manifests block publication. The file is written
once.
Values: TILE_CAP_DEG = 0.4.
default: wait_for_all
options:
Expand All @@ -2484,3 +2485,21 @@ analyses:
label: Publish early, replace as sources finish
excluded: true
excluded_reason: Readers would get a pixel whose rows change under them.
row_partitioning:
label: Each row goes to the order-5 pixel of its own position
rationale: >-
A row's pixel is _healpix_29 >> 48, computed from its own
XWIN_WORLD/YWIN_WORLD (galaxies) or star position, never from its
tile. Tile overlaps are kept (tile_overlap_handling), so an overlap
object appears once per tile, each copy in the pixel where it lies.
Values: HATS_ORDER = 5.
default: own_position
options:
own_position:
label: Pixel of the row's own position
tile_centre:
label: Whole tile in the pixel of its centre
excluded: true
excluded_reason: >-
13.6% of rows land outside their pixel; strict HATS validation
passes but cone searches silently miss them.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies = [
"canfar",
"cs_util>=0.2.1",
"galsim>=2.8",
"hats>=0.11.1",
"h5py",
"healsparse",
"hpgeom",
Expand Down
261 changes: 261 additions & 0 deletions tests/unit/test_publication_pixel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
"""Synthetic publication patch, including boundaries and source gating."""

import hashlib
import json
import sys
from pathlib import Path

import h5py
import healsparse as hsp
import numpy as np
import pyarrow.parquet as pq
import pytest
from hats.pixel_math import compute_spatial_index

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'workflow/scripts'))
import build_hats_pixel as builder
import build_map_pixel as maps


@pytest.fixture
def patch(tmp_path):
products = tmp_path / 'products'
mask = tmp_path / 'external.hsp'
mask.write_bytes(b'external mask')
# Points are spread over several order-5 pixels; each tile has overlapping
# sky with its neighbours and distinct values, which must not be deduped.
coords = [(10., 10.), (11., 10.), (12., 10.), (13., 10.)]
pixels = [int(x >> 48) for x in compute_spatial_index(
np.array([x for x, y in coords]), np.array([y for x, y in coords]))]
tiles = ['100.200', '101.200', '102.200', '103.200']
expected = []
for n, tile in enumerate(tiles):
d = products / 'tiles' / tile[:2] / tile
d.mkdir(parents=True)
(d / 'tile_make_cat.json').write_text('{}')
with h5py.File(d / f'final_cat-{tile}.hdf5', 'w') as f:
f['XWIN_WORLD'] = [coords[n][0], coords[(n + 1) % 4][0]]
f['YWIN_WORLD'] = [10., 10.]
f['VALUE'] = [n * 2, n * 2 + 1]
expected.extend([(n * 2, coords[n][0], 10.),
(n * 2 + 1, coords[(n + 1) % 4][0], 10.)])
listing = tmp_path / 'pixel_tiles.csv'
listing.write_text('pixel,tile_id\n' + ''.join(
f'{p},{tile}\n' for p in sorted(set(pixels)) for tile in tiles))
return tmp_path, products, mask, listing, sorted(set(pixels)), expected


def test_pixel_rows_exact(patch):
root, products, mask, listing, pixels, expected = patch
seen = []
for pixel in pixels:
path = builder.build_pixel(pixel, 'tiles', listing, products, root,
root / 'hats', 'abc123', mask)
tab = pq.ParquetFile(path).read()
hp = tab['_healpix_29'].to_numpy()
assert np.all(hp >> 48 == pixel)
assert np.all(hp[:-1] <= hp[1:])
seen.extend(zip(tab['VALUE'].to_pylist(), tab['XWIN_WORLD'].to_pylist(),
tab['YWIN_WORLD'].to_pylist()))
assert sorted(seen) == sorted(expected)
builder.write_catalogue_metadata(root / 'hats', path, 'tiles', 'test')
assert 'hats_nrows' not in (root / 'hats/properties').read_text()
assert pq.read_schema(root / 'hats/dataset/_common_metadata').names == tab.schema.names
with pytest.raises(FileExistsError):
builder.write_catalogue_metadata(root / 'hats', path, 'tiles', 'test')


def test_missing_source_then_abandoned(patch):
root, products, mask, listing, pixels, _ = patch
missing = '100.200'
(products / 'tiles/10' / missing / 'tile_make_cat.json').unlink()
with pytest.raises(RuntimeError, match=missing):
builder.build_pixel(pixels[0], 'tiles', listing, products, root, root / 'hats', 'abc', mask)
(root / 'abandoned.txt').write_text(missing + ' # no retry\n')
p = builder.build_pixel(pixels[0], 'tiles', listing, products, root, root / 'hats', 'abc', mask)
assert not set(pq.ParquetFile(p).read()['VALUE'].to_pylist()) & {0, 1}
(products / 'tiles/10' / missing / 'tile_make_cat.json').write_text('{}')
p = builder.build_pixel(pixels[0], 'tiles', listing, products, root,
root / 'conflict', 'abc', mask)
assert not set(pq.ParquetFile(p).read()['VALUE'].to_pylist()) & {0, 1}


def test_code_sha_in_file(patch):
root, products, mask, listing, pixels, _ = patch
p = builder.build_pixel(pixels[0], 'tiles', listing, products, root, root / 'hats', 'abc123', mask)
meta = pq.read_metadata(p).metadata
assert meta[b'SPSHA'] == b'abc123'
assert json.loads(meta[b'MASKS']) == [
{'path': str(mask), 'sha256': hashlib.sha256(mask.read_bytes()).hexdigest()}]


def test_vector_columns_empty_and_nonempty(patch):
import pyarrow as pa

root, products, mask, listing, pixels, _ = patch
for i, tile in enumerate(['100.200', '101.200', '102.200', '103.200']):
path = products / 'tiles' / tile[:2] / tile / f'final_cat-{tile}.hdf5'
with h5py.File(path, 'a') as f:
if i == 0:
for name in list(f):
del f[name]
f['XWIN_WORLD'] = np.array([], dtype='f8')
f['YWIN_WORLD'] = np.array([], dtype='f8')
f['VALUE'] = np.array([], dtype='i8')
f['FLUX_APER'] = np.ones((0 if i == 0 else 2, 1), dtype='f4')
mixed = builder.build_pixel(pixels[0], 'tiles', listing, products, root,
root / 'mixed', 'abc', mask)
empty_list = root / 'empty.csv'
empty_list.write_text(f'pixel,tile_id\n{pixels[0]},100.200\n')
empty = builder.build_pixel(pixels[0], 'tiles', empty_list, products, root,
root / 'empty', 'abc', mask)
mixed_schema = pq.read_schema(mixed).remove_metadata()
assert mixed_schema == pq.read_schema(empty).remove_metadata()
assert mixed_schema.field('FLUX_APER').type == pa.list_(pa.float32())
assert pq.ParquetFile(empty).read().num_rows == 0


def test_multiple_mask_provenance(patch):
root, products, mask, listing, pixels, _ = patch
other = root / 'second.hsp'
other.write_bytes(b'second mask')
masks = [mask, other]
first = builder.build_pixel(pixels[0], 'tiles', listing, products, root,
root / 'first', 'abc', masks)
records = json.loads(pq.read_metadata(first).metadata[b'MASKS'])
assert records == [{'path': str(p), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}
for p in masks]
other.write_bytes(b'changed')
second = builder.build_pixel(pixels[0], 'tiles', listing, products, root,
root / 'second', 'abc', masks)
changed = json.loads(pq.read_metadata(second).metadata[b'MASKS'])
assert changed[0] == records[0]
assert changed[1]['sha256'] != records[1]['sha256']


def test_star_partition_and_unlisted_pixel(patch, monkeypatch):
root, products, mask, _, pixels, _ = patch
coords = np.array([10., 11., 12., 13.])
sp = compute_spatial_index(coords, np.full(4, 10.)) >> 48
import pyarrow as pa
monkeypatch.setattr(builder, '_star_rows', lambda products, exp: pa.table(
{'RA': coords, 'DEC': np.full(4, 10.), 'EXP_ID': [exp] * 4,
'CCD_NB': [1] * 4, 'SOURCE_ORDINAL': np.arange(4)}))
manifest = products / 'exp/12/123456/manifests/exp_persist.json'
manifest.parent.mkdir(parents=True)
manifest.write_text('{}')
listing = root / 'exposures.csv'
listing.write_text('pixel,exp_id\n' + ''.join(f'{p},123456\n' for p in pixels))
collected = []
for p in pixels:
path = builder.build_pixel(p, 'stars', listing, products, root, root / 'stars', 'abc', mask)
collected.extend(pq.ParquetFile(path).read()['SOURCE_ORDINAL'].to_pylist())
assert sorted(collected) == list(range(4))
listing.write_text('pixel,exp_id\n' + ''.join(f'{p},123456\n' for p in pixels[:-1]))
with pytest.raises(ValueError, match=f'123456.*{pixels[-1]}'):
builder.build_pixel(pixels[0], 'stars', listing, products, root, root / 'other', 'abc', mask)


@pytest.mark.parametrize('dtype', ['S6', 'U6'])
def test_star_exp_id_utf8_preserves_leading_zero(tmp_path, monkeypatch, dtype):
import pyarrow as pa
import merge_star_cat

exp = '012345'
manifest = tmp_path / 'exp' / exp[:2] / exp / 'manifests' / 'exp_persist.json'
manifest.parent.mkdir(parents=True)
manifest.write_text(json.dumps({'tar': 'unused'}))
data = np.array([(exp, 2, 0), (exp, 2, 1)],
dtype=[('EXP_ID', dtype), ('CCD_NB', 'i4'),
('SOURCE_ORDINAL', 'i8')])
monkeypatch.setattr(merge_star_cat, 'read_exposure', lambda *args: data)
rows = builder._star_rows(tmp_path, exp)
path = tmp_path / 'stars.parquet'
pq.write_table(rows, path)
result = pq.read_table(path)
assert result.schema.field('EXP_ID').type == pa.string()
assert result['EXP_ID'].to_pylist() == [exp, exp]
assert len(set(zip(*(result[name].to_pylist() for name in
('EXP_ID', 'CCD_NB', 'SOURCE_ORDINAL'))))) == 2


def test_stars_read_persisted_tar(tmp_path):
import io
import json
import tarfile
from astropy.io import fits
import merge_star_cat

products = tmp_path / 'products'
base = products / 'exp/12/123456'
(base / 'psf').mkdir(parents=True)
(base / 'manifests').mkdir()
tar_path = base / 'psf/123456.tar'
with tarfile.open(tar_path, 'w') as tar:
for ccd in (2, 5):
columns = [fits.Column(name=name, format='D', array=[10., 11.])
for name in merge_star_cat.COLUMNS]
data = fits.HDUList([fits.PrimaryHDU(), fits.ImageHDU(),
fits.BinTableHDU.from_columns(columns)])
buf = io.BytesIO()
data.writeto(buf)
raw = buf.getvalue()
info = tarfile.TarInfo(f'validation_psf-123456-{ccd}.fits')
info.size = len(raw)
tar.addfile(info, io.BytesIO(raw))
(base / 'manifests/exp_persist.json').write_text(json.dumps({'tar': str(tar_path)}))
rows = builder._star_rows(products, '123456')
assert rows['EXP_ID'].to_pylist() == ['123456'] * 4
assert rows['CCD_NB'].to_pylist() == [2, 2, 5, 5]
assert rows['SOURCE_ORDINAL'].to_pylist() == [0, 1, 0, 1]


def test_maps_match_sum_and_provenance(tmp_path, monkeypatch):
products = tmp_path / 'products'
mask = tmp_path / 'mask.hsp'
mask.write_bytes(b'mask')
other = tmp_path / 'mask2.hsp'
other.write_bytes(b'second mask')
masks = [mask, other]
pixel1, pixel2 = 100, 101
shift = 24
children = np.array([(pixel1 << shift) + 4, (pixel2 << shift) + 9], dtype=np.int64)
listing = tmp_path / 'exposures.csv'
listing.write_text('pixel,exp_id\n100,123\n101,123\n100,124\n101,124\n')
for exp, values in [('123', [7 | (2 << 3), 3 | (1 << 3)]),
('124', [5 | (3 << 3), 7 | (4 << 3)])]:
d = products / 'exp' / exp[:2] / exp
(d / 'manifests').mkdir(parents=True)
(d / 'maps').mkdir()
(d / 'manifests/exp_maps.json').write_text('{}')
frag = hsp.HealSparseMap.make_empty(128, 131072, np.uint16)
frag[children] = np.array(values, dtype=np.uint16)
frag.write(str(d / 'maps' / f'maps-{exp}.hsp'))
import merge_exposure_maps as merge
monkeypatch.setattr(merge.build_index, 'campaign_exposures', lambda *args: ['123', '124'])
merged = {name: tmp_path / f'{name}.hsp' for name in ('npoint', 'ntaken', 'nexp', 'nflagged')}
monkeypatch.setattr(sys, 'argv', ['merge_exposure_maps.py', '--products-dir', str(products),
'--tile-list', 'unused', '--index-db', 'unused',
*sum(([f'--{name}', str(path)] for name, path in merged.items()), [])])
merge.main()
for i, p in enumerate([pixel1, pixel2]):
result = maps.build_maps(p, listing, products, tmp_path, tmp_path / 'out', 'abc123', masks)
for name, path in result.items():
m = hsp.HealSparseMap.read(str(path))
whole = hsp.HealSparseMap.read(str(merged[name]))
assert m.get_values_pix(children[i]) == whole.get_values_pix(children[i])
assert set(m.valid_pixels) <= {int(children[i])}
assert m.metadata['SPSHA'] == 'abc123'
assert json.loads(m.metadata['MASKS']) == [
{'path': str(path), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
for path in masks]
before = json.loads(hsp.HealSparseMap.read(str(result['npoint'])).metadata['MASKS'])
other.write_bytes(b'changed second mask')
changed = maps.build_maps(pixel2, listing, products, tmp_path, tmp_path / 'changed',
'abc123', masks)
after = json.loads(hsp.HealSparseMap.read(str(changed['npoint'])).metadata['MASKS'])
assert after[0] == before[0]
assert after[1]['sha256'] != before[1]['sha256']
listing.write_text('pixel,exp_id\n100,123\n100,124\n101,124\n')
with pytest.raises(ValueError, match='123.*101'):
maps.build_maps(100, listing, products, tmp_path, tmp_path / 'other', 'abc', mask)
39 changes: 39 additions & 0 deletions tests/unit/test_publication_sources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Publication waits for durable success or explicit abandonment."""

import importlib.util
from pathlib import Path

import pytest


SPEC = importlib.util.spec_from_file_location(
"publication_sources", Path(__file__).resolve().parents[2]
/ "workflow/scripts/publication_sources.py")
module = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(module)


@pytest.mark.parametrize("kind,column,manifest", [
("tiles", "tile_id", "tiles/12/123.456/tile_make_cat.json"),
("stars", "exp_id", "exp/12/123.456/manifests/exp_persist.json"),
("maps", "exp_id", "exp/12/123.456/manifests/exp_maps.json"),
])
def test_missing_manifest_blocks_until_abandoned(tmp_path, kind, column, manifest):
listing = tmp_path / "list.csv"
listing.write_text(f"pixel,{column}\n7,123.456\n7,222.333\n8,999.999\n")
success = tmp_path / "products" / manifest
success.parent.mkdir(parents=True)
success.write_text("{}")
with pytest.raises(RuntimeError, match="222.333"):
module.finished_sources(7, kind, listing, tmp_path / "products", tmp_path)
(tmp_path / "abandoned.txt").write_text("222.333 # failed permanently\n")
assert module.finished_sources(7, kind, listing, tmp_path / "products", tmp_path) == ["123.456"]
(tmp_path / "abandoned.txt").write_text("123.456\n222.333\n")
assert module.finished_sources(7, kind, listing, tmp_path / "products", tmp_path) == []


def test_duplicate_list_entry_is_rejected(tmp_path):
listing = tmp_path / "list.csv"
listing.write_text("pixel,tile_id\n7,123.456\n7,123.456\n")
with pytest.raises(ValueError, match="Duplicate"):
module.finished_sources(7, "tiles", listing, tmp_path, tmp_path)
Loading
Loading