astribidem 0.0.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
astribidem/__init__.py ADDED
@@ -0,0 +1,73 @@
1
+ """Exact astronomical crossmatching with row-position entity indexes."""
2
+
3
+ from astribidem._formats import __version__
4
+ from astribidem.api import crossmatch, resolve, rows_to_ids
5
+ from astribidem.audit import audit_edges
6
+ from astribidem.banded import (
7
+ build_band,
8
+ build_edges_by_band,
9
+ prepare_band_build,
10
+ sweep_boundaries,
11
+ write_band_layout,
12
+ )
13
+ from astribidem.candidate_edges import (
14
+ CandidateEdges,
15
+ DedupeOutcome,
16
+ PairEdges,
17
+ combine_segments,
18
+ )
19
+ from astribidem.edge_files import (
20
+ build_edges_to_directory,
21
+ read_edges,
22
+ read_segment,
23
+ segment_names,
24
+ write_edges,
25
+ write_segment,
26
+ )
27
+ from astribidem.edges import build_edges
28
+ from astribidem.hub_and_spoke import SpatialLink, UIDLink, match_hub_and_spoke
29
+ from astribidem.index_files import resolve_to_file
30
+ from astribidem.kernel import CatalogKernel
31
+ from astribidem.modes import (
32
+ CrossmatchModeConfig,
33
+ DegenerateCrossmatchConfig,
34
+ EntitySelectionConfig,
35
+ EntitywiseCrossmatchConfig,
36
+ index_summary,
37
+ )
38
+ from astribidem.uids import match_uids
39
+
40
+ __all__ = [
41
+ "__version__",
42
+ "CandidateEdges",
43
+ "CatalogKernel",
44
+ "CrossmatchModeConfig",
45
+ "DedupeOutcome",
46
+ "DegenerateCrossmatchConfig",
47
+ "EntitySelectionConfig",
48
+ "EntitywiseCrossmatchConfig",
49
+ "PairEdges",
50
+ "SpatialLink",
51
+ "UIDLink",
52
+ "audit_edges",
53
+ "build_band",
54
+ "build_edges",
55
+ "build_edges_by_band",
56
+ "build_edges_to_directory",
57
+ "combine_segments",
58
+ "crossmatch",
59
+ "index_summary",
60
+ "match_hub_and_spoke",
61
+ "match_uids",
62
+ "prepare_band_build",
63
+ "read_edges",
64
+ "read_segment",
65
+ "resolve",
66
+ "resolve_to_file",
67
+ "rows_to_ids",
68
+ "segment_names",
69
+ "sweep_boundaries",
70
+ "write_band_layout",
71
+ "write_edges",
72
+ "write_segment",
73
+ ]
astribidem/_formats.py ADDED
@@ -0,0 +1,43 @@
1
+ """Versioned persistence contracts, independent of the package release number."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("astribidem")
6
+ FORMAT_VERSION = 1
7
+
8
+
9
+ def file_metadata(kind: str) -> dict:
10
+ return {
11
+ "format": f"astribidem.{kind}",
12
+ "format_version": FORMAT_VERSION,
13
+ "astribidem_version": __version__,
14
+ }
15
+
16
+
17
+ def check_file_metadata(metadata: dict, kind: str) -> None:
18
+ expected = f"astribidem.{kind}"
19
+ if (
20
+ metadata.get("format") != expected
21
+ or type(metadata.get("format_version")) is not int
22
+ or metadata["format_version"] != FORMAT_VERSION
23
+ ):
24
+ raise ValueError(
25
+ f"unsupported {expected} format/version: "
26
+ f"{metadata.get('format')!r}/{metadata.get('format_version')!r}; "
27
+ "regenerate unversioned development files, or use a compatible release"
28
+ )
29
+
30
+
31
+ def index_metadata() -> dict[bytes, bytes]:
32
+ return {
33
+ b"astribidem.index_format_version": str(FORMAT_VERSION).encode(),
34
+ b"astribidem.version": __version__.encode(),
35
+ }
36
+
37
+
38
+ def check_index_metadata(metadata: dict[bytes, bytes]) -> None:
39
+ if metadata.get(b"astribidem.index_format_version") != str(FORMAT_VERSION).encode():
40
+ raise ValueError(
41
+ "unsupported astribidem index format version; regenerate unversioned "
42
+ "development indexes, or use a compatible release"
43
+ )
astribidem/_radii.py ADDED
@@ -0,0 +1,41 @@
1
+ """Validate scalar radii and expand per-survey deduplication overrides."""
2
+
3
+ from collections.abc import Iterable, Mapping
4
+ from math import isfinite
5
+ from numbers import Real
6
+
7
+
8
+ def radius(value: float, *, name: str, allow_zero: bool = False) -> float:
9
+ if (
10
+ isinstance(value, bool)
11
+ or not isinstance(value, Real)
12
+ or not isfinite(value)
13
+ or value < 0
14
+ or (not allow_zero and value == 0)
15
+ ):
16
+ bound = ">= 0" if allow_zero else "> 0"
17
+ raise ValueError(f"{name} must be a finite scalar radius {bound}")
18
+ return float(value)
19
+
20
+
21
+ def dedupe_radii(
22
+ names: Iterable[str],
23
+ default: float,
24
+ overrides: Mapping[str, float] | None = None,
25
+ ) -> dict[str, float]:
26
+ """Expand a scalar default and optional exceptions for spatial participants."""
27
+ default = radius(default, name="dedupe_radius_arcsec", allow_zero=True)
28
+ result = dict.fromkeys(names, default)
29
+ if overrides is not None:
30
+ if not isinstance(overrides, Mapping):
31
+ raise TypeError("dedupe_radius_arcsec_overrides must be a mapping")
32
+ for name, value in overrides.items():
33
+ if name not in result:
34
+ raise ValueError(
35
+ "dedupe_radius_arcsec_overrides names an unknown spatial "
36
+ f"participant: {name!r}"
37
+ )
38
+ result[name] = radius(
39
+ value, name=f"dedupe override for {name!r}", allow_zero=True
40
+ )
41
+ return result
astribidem/api.py ADDED
@@ -0,0 +1,159 @@
1
+ """Resolve candidate edges into indexes, and map index rows to caller IDs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable, Mapping
7
+ from itertools import combinations
8
+
9
+ import pyarrow as pa
10
+ import pyarrow.compute as pc
11
+ from numpy.typing import ArrayLike
12
+
13
+ from astribidem.candidate_edges import CandidateEdges
14
+ from astribidem.edges import _build_prepared_edges, _prepare_edge_build
15
+ from astribidem.kernel import resolve_workers
16
+ from astribidem.modes import CrossmatchModeConfig, mode_to_mapping
17
+ from astribidem.uids import _as_arrow
18
+
19
+
20
+ def _required_pairs(
21
+ mode: CrossmatchModeConfig, survey_names: Iterable[str]
22
+ ) -> set[frozenset[str]]:
23
+ surveys = survey_names if mode.requires_all_surveys() else mode.required_surveys()
24
+ return {frozenset(pair) for pair in combinations(surveys, 2)}
25
+
26
+
27
+ def _check_mode_fits_edges(mode: CrossmatchModeConfig, edges: CandidateEdges) -> None:
28
+ """Fail loudly when the edges cannot answer the mode's question."""
29
+ if not isinstance(mode, CrossmatchModeConfig):
30
+ raise TypeError("mode must be a CrossmatchModeConfig")
31
+ unknown = set(mode.required_surveys()) - set(edges.survey_names)
32
+ if unknown:
33
+ raise ValueError(f"mode names unknown surveys: {sorted(unknown)}")
34
+ missing = _required_pairs(mode, edges.survey_names) - set(edges.pairs)
35
+ if missing:
36
+ raise ValueError(
37
+ "the edges were built without survey pairs this mode needs: "
38
+ f"{sorted(sorted(pair) for pair in missing)}"
39
+ )
40
+
41
+
42
+ def resolve(edges: CandidateEdges, mode: CrossmatchModeConfig) -> pa.Table:
43
+ """Resolve candidate edges into one row-position index.
44
+
45
+ ``mode`` selects an Astral-derived subset join or exactly-once entity
46
+ resolution. A degenerate mode reads only its own surveys' pairs, so it
47
+ can use edges built for more surveys; an entitywise mode uses every
48
+ survey in the edges. Entity selection is applied only after all surveys
49
+ are resolved.
50
+
51
+ The result contains int64 ``<survey>/row_index`` columns (row ``i`` is the
52
+ survey's ``i``-th coordinate; null when absent), optional separations or
53
+ dispute reasons, and metadata recording the configuration, dedupe
54
+ outcomes and the result summary (read with ``index_summary``), so a table
55
+ saved with ``pyarrow.parquet.write_table`` is complete. Use ``rows_to_ids`` to
56
+ replace rows with caller IDs.
57
+ """
58
+ _check_mode_fits_edges(mode, edges)
59
+ table = mode.build(edges)
60
+ used_pairs = _required_pairs(mode, edges.survey_names)
61
+ provenance = {
62
+ "surveys": [
63
+ {"name": survey.name, "dedupe_radius_arcsec": survey.dedupe_radius_arcsec}
64
+ for survey in edges.surveys
65
+ ],
66
+ "pair_radius_arcsec": [
67
+ {
68
+ "surveys": [pair.survey_a, pair.survey_b],
69
+ "radius_arcsec": pair.radius_arcsec,
70
+ }
71
+ for key, pair in edges.pairs.items()
72
+ if key in used_pairs
73
+ ],
74
+ "mode": mode_to_mapping(mode),
75
+ }
76
+ outcomes = {
77
+ survey.name: {
78
+ "radius_arcsec": survey.dedupe_radius_arcsec,
79
+ "n_rows": survey.n_rows,
80
+ "n_dropped": survey.n_dropped,
81
+ "n_disputed": survey.n_disputed,
82
+ }
83
+ for survey in edges.surveys
84
+ }
85
+ metadata = dict(table.schema.metadata or {})
86
+ metadata[b"astribidem.resolved_config"] = json.dumps(
87
+ provenance, sort_keys=True, separators=(",", ":"), allow_nan=False
88
+ ).encode()
89
+ metadata[b"astribidem.dedupe"] = json.dumps(
90
+ outcomes, sort_keys=True, separators=(",", ":"), allow_nan=False
91
+ ).encode()
92
+ return table.replace_schema_metadata(metadata)
93
+
94
+
95
+ def crossmatch(
96
+ surveys: Mapping[str, tuple[ArrayLike, ArrayLike]],
97
+ *,
98
+ radius_arcsec: float,
99
+ dedupe_radius_arcsec: float,
100
+ dedupe_radius_arcsec_overrides: Mapping[str, float] | None = None,
101
+ mode: CrossmatchModeConfig,
102
+ workers: int = 1,
103
+ radius_arcsec_overrides: Mapping[tuple[str, str] | frozenset[str], float]
104
+ | None = None,
105
+ ) -> pa.Table:
106
+ """Build candidate edges and resolve them in memory: one row-position index.
107
+
108
+ Equivalent to ``resolve(build_edges(...), mode)``, except that a
109
+ degenerate mode joins only the survey pairs it reads. See ``build_edges``
110
+ for the matching settings and ``resolve`` for the result. No payloads are
111
+ read and nothing is saved.
112
+ """
113
+ if not isinstance(mode, CrossmatchModeConfig):
114
+ raise TypeError("mode must be a CrossmatchModeConfig")
115
+ if not isinstance(surveys, Mapping) or not surveys:
116
+ raise ValueError("surveys must map at least one name to an (ra, dec) tuple")
117
+ names = tuple(surveys)
118
+ unknown = set(mode.required_surveys()) - set(names)
119
+ if unknown:
120
+ raise ValueError(f"mode names unknown surveys: {sorted(unknown)}")
121
+ workers = resolve_workers(workers)
122
+ settings, kernels = _prepare_edge_build(
123
+ surveys,
124
+ radius_arcsec=radius_arcsec,
125
+ dedupe_radius_arcsec=dedupe_radius_arcsec,
126
+ dedupe_radius_arcsec_overrides=dedupe_radius_arcsec_overrides,
127
+ radius_arcsec_overrides=radius_arcsec_overrides,
128
+ pairs=None if mode.requires_all_surveys() else _required_pairs(mode, names),
129
+ )
130
+ del surveys
131
+ edges = _build_prepared_edges(settings, kernels, workers=workers)
132
+ del kernels
133
+ return resolve(edges, mode)
134
+
135
+
136
+ def rows_to_ids(
137
+ table: pa.Table,
138
+ ids: Mapping[str, object],
139
+ *,
140
+ id_columns: Mapping[str, str] | None = None,
141
+ ) -> pa.Table:
142
+ """Replace ``<survey>/row_index`` columns of a match index by IDs.
143
+
144
+ Each named survey's row column is used to index ``ids[survey]``, which
145
+ holds one ID per input row in input order (the coordinates passed to the
146
+ edge build, or the UIDs passed to ``match_uids``). The result replaces the
147
+ row column in place as ``<survey>/<id column>`` (default ``id``); null
148
+ rows stay null. Surveys not named in ``ids`` keep their row column. The
149
+ IDs are not checked.
150
+ """
151
+ id_columns = id_columns or {}
152
+ for survey, values in ids.items():
153
+ row_column = f"{survey}/row_index"
154
+ table = table.set_column(
155
+ table.column_names.index(row_column),
156
+ f"{survey}/{id_columns.get(survey, 'id')}",
157
+ pc.take(_as_arrow(values, name=survey, kind="IDs"), table[row_column]),
158
+ )
159
+ return table
astribidem/audit.py ADDED
@@ -0,0 +1,137 @@
1
+ """Diagnostics for candidate edges, computed from a ``CandidateEdges`` object.
2
+
3
+ The audit works the same on edges held in memory, reloaded with
4
+ ``read_edges``, or streamed to disk and reloaded. It reports per-survey dedupe
5
+ outcomes, per-pair edge counts and candidate multiplicity, and a census of the
6
+ connected components over every survey: sizes, the largest (a percolation
7
+ guardrail), and clean-component counts by survey combination. A clean
8
+ component spanning surveys {A, B} is exactly one row of a clean A x B
9
+ product, so the census sizes subset joins before any are built.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from itertools import combinations
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+
19
+ from astribidem.candidate_edges import CandidateEdges, DedupeOutcome
20
+ from astribidem.graph import build_global_graph
21
+
22
+ _SEPARATION_PERCENTILES = (5, 25, 50, 75, 95)
23
+ _SIZE_HISTOGRAM_CAP = 6
24
+
25
+
26
+ def _percentiles(values: np.ndarray) -> dict[str, float] | None:
27
+ if len(values) == 0:
28
+ return None
29
+ points = np.percentile(values, _SEPARATION_PERCENTILES)
30
+ return {
31
+ f"p{p}": round(float(v), 4) for p, v in zip(_SEPARATION_PERCENTILES, points)
32
+ }
33
+
34
+
35
+ def _size_histogram(sizes: np.ndarray) -> dict[str, int]:
36
+ histogram = {
37
+ str(size): int((sizes == size).sum()) for size in range(1, _SIZE_HISTOGRAM_CAP)
38
+ }
39
+ histogram[f">={_SIZE_HISTOGRAM_CAP}"] = int((sizes >= _SIZE_HISTOGRAM_CAP).sum())
40
+ return histogram
41
+
42
+
43
+ def _survey_audit(survey: DedupeOutcome) -> dict[str, Any]:
44
+ # Each distinct kept row stands for one duplicate group; the group also
45
+ # contains every dropped row that points at it.
46
+ _, dropped_per_group = np.unique(survey.kept_rows, return_counts=True)
47
+ return {
48
+ "name": survey.name,
49
+ "n_rows": survey.n_rows,
50
+ "dedupe_radius_arcsec": survey.dedupe_radius_arcsec,
51
+ "n_active": survey.n_active,
52
+ "n_dropped": survey.n_dropped,
53
+ "n_disputed": survey.n_disputed,
54
+ "n_duplicate_groups": len(dropped_per_group),
55
+ "largest_duplicate_group": int(dropped_per_group.max()) + 1
56
+ if len(dropped_per_group)
57
+ else 0,
58
+ }
59
+
60
+
61
+ def _pair_audit(edges: CandidateEdges, pair) -> dict[str, Any]:
62
+ active = {
63
+ name: edges.survey(name).n_active for name in (pair.survey_a, pair.survey_b)
64
+ }
65
+ rows_a, counts_a = np.unique(pair.row_a, return_counts=True)
66
+ rows_b, counts_b = np.unique(pair.row_b, return_counts=True)
67
+
68
+ def fraction(n_matched: int, name: str) -> float:
69
+ return round(n_matched / active[name], 6) if active[name] else 0.0
70
+
71
+ return {
72
+ "surveys": [pair.survey_a, pair.survey_b],
73
+ "radius_arcsec": pair.radius_arcsec,
74
+ "n_edges": len(pair.row_a),
75
+ "separation_arcsec": _percentiles(pair.separation_arcsec),
76
+ "matched_row_fraction": {
77
+ pair.survey_a: fraction(len(rows_a), pair.survey_a),
78
+ pair.survey_b: fraction(len(rows_b), pair.survey_b),
79
+ },
80
+ "multi_candidate_rows": {
81
+ pair.survey_a: int((counts_a > 1).sum()),
82
+ pair.survey_b: int((counts_b > 1).sum()),
83
+ },
84
+ }
85
+
86
+
87
+ def _component_census(edges: CandidateEdges) -> dict[str, Any]:
88
+ names = edges.survey_names
89
+ graph = build_global_graph(
90
+ names,
91
+ {survey.name: survey.active_rows() for survey in edges.surveys},
92
+ [
93
+ (p.survey_a, p.survey_b, p.row_a, p.row_b, p.separation_arcsec)
94
+ for p in edges.pairs.values()
95
+ ],
96
+ )
97
+ if graph.n_nodes == 0:
98
+ return {"n_rows": 0, "n_components": 0}
99
+ sizes = graph.sizes
100
+ clean = graph.clean()
101
+ multi = sizes > 1
102
+ ambiguous = ~clean & multi
103
+ by_combination = {}
104
+ for bits in np.unique(graph.survey_bits[multi]):
105
+ members = [name for i, name in enumerate(names) if (int(bits) >> i) & 1]
106
+ mask = (graph.survey_bits == bits) & multi
107
+ by_combination["+".join(members)] = {
108
+ "n_components": int(mask.sum()),
109
+ "n_clean": int((mask & clean).sum()),
110
+ }
111
+ return {
112
+ "n_rows": graph.n_nodes,
113
+ "n_components": len(sizes),
114
+ "size_histogram": _size_histogram(sizes),
115
+ "max_component_size": int(sizes.max()),
116
+ "n_clean_multi_survey": int((clean & multi).sum()),
117
+ "n_ambiguous": int(ambiguous.sum()),
118
+ "rows_in_ambiguous_components": int(sizes[ambiguous].sum()),
119
+ "by_survey_combination": by_combination,
120
+ }
121
+
122
+
123
+ def audit_edges(edges: CandidateEdges) -> dict[str, Any]:
124
+ """Summarise candidate edges as a JSON-serialisable dictionary.
125
+
126
+ Separations are in arcseconds. The component census covers the active
127
+ rows of every survey and the edges of every built pair; ``all_pairs_built``
128
+ is false when the build was restricted to some pairs, in which case the
129
+ census omits the missing pairs' edges.
130
+ """
131
+ expected = {frozenset(pair) for pair in combinations(edges.survey_names, 2)}
132
+ return {
133
+ "all_pairs_built": set(edges.pairs) == expected,
134
+ "surveys": [_survey_audit(survey) for survey in edges.surveys],
135
+ "pairs": [_pair_audit(edges, pair) for pair in edges.pairs.values()],
136
+ "components": _component_census(edges),
137
+ }