Scientific comparison reports
The comparison oracle in hebog.validation.comparison is independent of the
PyBDSF product readers and of Hebog's algorithms, so catalogue, RMS and mask
equivalence are testable before any frozen external product counts as
evidence. The frozen PyBDSF products under config/baselines/ and every
Hebog comparison use the same typed reports; stratification by source class
is layered on top and never changes these calculations.
Catalogue matching
CatalogueSource stores ICRS positions in degrees, peak flux density in
Jy/beam and integrated flux density in Jy, and can carry candidate-reported
one-sigma errors, fitted and deconvolved CatalogueEllipse records, an
explicit resolved, major-axis-only, unresolved or unavailable state, parent-island identity,
component count and canonical quality flags; from_units accepts degrees or
arcseconds and Jy or mJy. The caller decides whether it is comparing
sources, Gaussian components or another row type first; the concepts are not
interchangeable.
compare_catalogues forms all pairs inside the caller's beam-normalized
separation gate, boundary included, and solves one global one-to-one
assignment with lexicographic objectives: most pairs inside the gate, then
the smallest sum of great-circle separations, then the smallest sum of the
symmetric flux difference |candidate - reference| / (candidate + reference).
Position decides before flux: two objects sharing a gate are paired by
separation even when the crossed pairing agrees better in flux, and the flux
errors then show the disagreement. Flux enters each pair's cost with a weight
of 10⁻⁹ beam, so it decides only between pairings whose separations differ by
less than that, which covers coincident rows and rounding. Ties are resolved
deterministically for a given input order, and right ascension wraps at 360°.
The report gives separations in beam FWHM and flux differences as signed
fractions of the reference, with median and 95th-percentile summaries.
Completeness is matched/reference and reliability matched/candidate; an empty
denominator counts as 1.0, so two empty catalogues agree and a
candidate-only catalogue has zero reliability. Match-only metrics are None
without pairs. For matched rows it adds signed fitted and deconvolved axis
differences (the worse of major and minor per row), shortest position-angle
differences modulo 180°, classification accuracy, component-count agreement
and exact and Jaccard quality-flag agreement, keeping fitted and deconvolved
angles separate. The caller supplies the minimum reference axis ratio for
position-angle evidence (the compact contract uses 1.1). Reference or
injected truth alone selects every population, so a missing candidate shape,
classification or parent identity counts as unavailable rather than removing
a difficult row; each gate reports eligible, available and
availability-fraction fields.
Candidate uncertainties are normalized against the reference value, with
eligible and available counts, one-sigma coverage, mean normalized residual
and sample standard deviation per metric; a missing uncertainty is an
availability failure, not a silent omission. Calibration claims therefore
need governed truth as the reference; a PyBDSF comparison measures
compatibility only.
Parent-island association is compared after assignment through linear-size
contingency summaries: pairwise true-positive, false-positive and
false-negative co-association counts with precision, recall, intersection
over union and agreement, so the far larger set of unrelated pairs cannot
hide a split or merge. A missing candidate parent identity stays in the
population as a unique unavailable identity. CatalogueOutlierThresholds
has no defaults: callers supply their frozen position, flux and shape limits
to obtain a catastrophic-outlier fraction, and the report retains them.
RMS maps
compare_rms_maps takes equal-shaped non-negative RMS arrays in Jy/beam and
an optional boolean valid mask. Non-finite values and pixels outside the mask
are excluded, and a negative finite RMS inside it is invalid input. Absolute
differences use every comparable pixel; fractional differences use only
pixels with positive reference RMS, with zero-reference pixels counted
explicitly. Empty comparisons return counts and None metrics.
Masks and island labels
compare_masks takes boolean arrays of equal shape and reports
true-positive, true-negative, false-positive and false-negative counts with
agreement, precision, recall and intersection over union. Two empty masks
score 1.0 on all four; a missing candidate-positive class has precision
0.0 when the reference has positive pixels and 1.0 otherwise.
compare_island_labels compares non-negative integer label planes
independently of their label values, with zero as background. It builds the
sparse positive-overlap graph, separates its components and assigns objects
by the number of overlapping pairs and then their intersecting pixels,
retaining per-match intersection over union, completeness, reliability,
unmatched labels and every split or merge visible in the graph. An optional
valid mask excludes pixels first. This object report stops high background
agreement from concealing a topologically wrong mask.
Released and pinned-master PyBDSF do not produce identical catalogues on
the same image; that divergence is resolved against injected truth, not by
treating either as authoritative.
hebog.validation.comparison
Independent scientific comparison reports for governed validation.
Catalogue matching uses canonical degrees and janskys. It maximizes the number
of pairs inside the separation gate, then minimizes their total angular
separation, and uses integrated-flux agreement only to break ties. Array
reports never broadcast inputs and state how many pixels were excluded.
AssociationComparisonReport
dataclass
Pairwise parent-association confusion counts and rates.
Source code in src/hebog/validation/comparison.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224 | @dataclass(frozen=True, slots=True)
class AssociationComparisonReport:
"""Pairwise parent-association confusion counts and rates."""
matched_source_count: int
identity_eligible_count: int
identity_available_count: int
identity_availability_fraction: float | None
compared_pair_count: int
true_positive_pair_count: int
false_positive_pair_count: int
false_negative_pair_count: int
disagreement_pair_count: int
agreement_fraction: float | None
precision: float
recall: float
intersection_over_union: float
|
BinomialConfidenceInterval
dataclass
Two-sided Wilson score interval for one observed success rate.
Source code in src/hebog/validation/comparison.py
316
317
318
319
320
321
322 | @dataclass(frozen=True, slots=True)
class BinomialConfidenceInterval:
"""Two-sided Wilson score interval for one observed success rate."""
confidence_level: float
lower: float
upper: float
|
CatalogueComparisonReport
dataclass
Assignment, completeness, reliability, position, and flux metrics.
Source code in src/hebog/validation/comparison.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267 | @dataclass(frozen=True, slots=True)
class CatalogueComparisonReport:
"""Assignment, completeness, reliability, position, and flux metrics."""
reference_count: int
candidate_count: int
matches: tuple[CatalogueMatch, ...]
unmatched_reference_identifiers: tuple[str, ...]
unmatched_candidate_identifiers: tuple[str, ...]
completeness: float
reliability: float
median_separation_beam_fwhm: float | None
percentile_95_separation_beam_fwhm: float | None
median_absolute_peak_flux_fractional_difference: float | None
percentile_95_absolute_peak_flux_fractional_difference: float | None
median_absolute_integrated_flux_fractional_difference: float | None
percentile_95_absolute_integrated_flux_fractional_difference: float | None
median_absolute_fitted_axis_fractional_difference: float | None
percentile_95_absolute_fitted_axis_fractional_difference: float | None
median_absolute_deconvolved_axis_fractional_difference: float | None
percentile_95_absolute_deconvolved_axis_fractional_difference: float | None
median_absolute_fitted_position_angle_difference_degrees: float | None
percentile_95_absolute_fitted_position_angle_difference_degrees: (
float | None
)
median_absolute_deconvolved_position_angle_difference_degrees: float | None
percentile_95_absolute_deconvolved_position_angle_difference_degrees: (
float | None
)
unresolved_classification_count: int
unresolved_classification_accuracy: float | None
field_availability: tuple[CatalogueFieldAvailabilityReport, ...]
association: AssociationComparisonReport
component_count_comparison_count: int
component_count_agreement_fraction: float | None
quality_flag_exact_agreement_fraction: float | None
median_quality_flag_jaccard: float | None
uncertainty_calibration: tuple[UncertaintyCalibrationReport, ...]
catastrophic_outlier_thresholds: CatalogueOutlierThresholds | None
catastrophic_outlier_reference_identifiers: tuple[str, ...]
catastrophic_outlier_fraction: float | None
|
CatalogueFieldAvailabilityReport
dataclass
Reference-selected availability for one gated candidate field.
Source code in src/hebog/validation/comparison.py
198
199
200
201
202
203
204
205 | @dataclass(frozen=True, slots=True)
class CatalogueFieldAvailabilityReport:
"""Reference-selected availability for one gated candidate field."""
metric: _AvailabilityMetric
eligible_count: int
available_count: int
availability_fraction: float | None
|
CatalogueMatch
dataclass
One assigned reference/candidate source pair.
Source code in src/hebog/validation/comparison.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159 | @dataclass(frozen=True, slots=True)
class CatalogueMatch:
"""One assigned reference/candidate source pair."""
reference_identifier: str
candidate_identifier: str
separation_beam_fwhm: float
peak_flux_fractional_difference: float
integrated_flux_fractional_difference: float
fitted_major_axis_fractional_difference: float | None
fitted_minor_axis_fractional_difference: float | None
fitted_position_angle_difference_degrees: float | None
deconvolved_major_axis_fractional_difference: float | None
deconvolved_minor_axis_fractional_difference: float | None
deconvolved_position_angle_difference_degrees: float | None
unresolved_classification_agrees: bool | None
component_count_agrees: bool | None
quality_flag_jaccard: float
quality_flags_agree: bool
|
CatalogueOutlierThresholds
dataclass
Caller-frozen thresholds defining catastrophic matched-row errors.
Source code in src/hebog/validation/comparison.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138 | @dataclass(frozen=True, slots=True)
class CatalogueOutlierThresholds:
"""Caller-frozen thresholds defining catastrophic matched-row errors."""
position_beams: float
peak_flux_fractional_difference: float
integrated_flux_fractional_difference: float
fitted_axis_fractional_difference: float
deconvolved_axis_fractional_difference: float
def __post_init__(self) -> None:
"""Require finite positive thresholds without hidden defaults."""
if any(
not np.isfinite(value) or value <= 0
for value in (
self.position_beams,
self.peak_flux_fractional_difference,
self.integrated_flux_fractional_difference,
self.fitted_axis_fractional_difference,
self.deconvolved_axis_fractional_difference,
)
):
raise ValueError("catalogue outlier thresholds must be positive")
|
__post_init__()
Require finite positive thresholds without hidden defaults.
Source code in src/hebog/validation/comparison.py
126
127
128
129
130
131
132
133
134
135
136
137
138 | def __post_init__(self) -> None:
"""Require finite positive thresholds without hidden defaults."""
if any(
not np.isfinite(value) or value <= 0
for value in (
self.position_beams,
self.peak_flux_fractional_difference,
self.integrated_flux_fractional_difference,
self.fitted_axis_fractional_difference,
self.deconvolved_axis_fractional_difference,
)
):
raise ValueError("catalogue outlier thresholds must be positive")
|
IslandComparisonReport
dataclass
Object matches, splits, merges, and overlap for labelled masks.
Source code in src/hebog/validation/comparison.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313 | @dataclass(frozen=True, slots=True)
class IslandComparisonReport:
"""Object matches, splits, merges, and overlap for labelled masks."""
compared_pixel_count: int
excluded_pixel_count: int
reference_count: int
candidate_count: int
matches: tuple[IslandLabelMatch, ...]
unmatched_reference_labels: tuple[int, ...]
unmatched_candidate_labels: tuple[int, ...]
split_reference_labels: tuple[int, ...]
merged_candidate_labels: tuple[int, ...]
completeness: float
reliability: float
median_matched_intersection_over_union: float | None
minimum_matched_intersection_over_union: float | None
|
IslandLabelMatch
dataclass
One overlap-based assignment between two labelled regions.
Source code in src/hebog/validation/comparison.py
286
287
288
289
290
291
292
293
294 | @dataclass(frozen=True, slots=True)
class IslandLabelMatch:
"""One overlap-based assignment between two labelled regions."""
reference_label: int
candidate_label: int
intersection_pixel_count: int
union_pixel_count: int
intersection_over_union: float
|
IslandPopulationReport
dataclass
Aggregate object non-inferiority metrics across a dataset matrix.
Source code in src/hebog/validation/comparison.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340 | @dataclass(frozen=True, slots=True)
class IslandPopulationReport:
"""Aggregate object non-inferiority metrics across a dataset matrix."""
case_count: int
reference_count: int
candidate_count: int
matched_count: int
completeness: float
reliability: float
completeness_confidence_interval: BinomialConfidenceInterval | None
reliability_confidence_interval: BinomialConfidenceInterval | None
split_count: int
merge_count: int
median_matched_intersection_over_union: float | None
minimum_matched_intersection_over_union: float | None
|
MaskComparisonReport
dataclass
Pixel confusion matrix and derived mask agreement metrics.
Source code in src/hebog/validation/comparison.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283 | @dataclass(frozen=True, slots=True)
class MaskComparisonReport:
"""Pixel confusion matrix and derived mask agreement metrics."""
compared_pixel_count: int
excluded_pixel_count: int
true_positive_count: int
true_negative_count: int
false_positive_count: int
false_negative_count: int
agreement_fraction: float
precision: float
recall: float
intersection_over_union: float
|
NumericConfidenceInterval
dataclass
Two-sided confidence interval for one real-valued statistic.
Source code in src/hebog/validation/comparison.py
162
163
164
165
166
167
168 | @dataclass(frozen=True, slots=True)
class NumericConfidenceInterval:
"""Two-sided confidence interval for one real-valued statistic."""
confidence_level: float
lower: float
upper: float
|
RmsComparisonReport
dataclass
Absolute and relative RMS-map differences in canonical units.
Source code in src/hebog/validation/comparison.py
343
344
345
346
347
348
349
350
351
352
353
354 | @dataclass(frozen=True, slots=True)
class RmsComparisonReport:
"""Absolute and relative RMS-map differences in canonical units."""
compared_pixel_count: int
relative_pixel_count: int
excluded_pixel_count: int
zero_reference_pixel_count: int
median_absolute_difference_jy_per_beam: float | None
percentile_95_absolute_difference_jy_per_beam: float | None
median_absolute_fractional_difference: float | None
percentile_95_absolute_fractional_difference: float | None
|
UncertaintyCalibrationDecision
dataclass
Reviewed entire-interval decision for one uncertainty stratum.
Source code in src/hebog/validation/comparison.py
| @dataclass(frozen=True, slots=True)
class UncertaintyCalibrationDecision:
"""Reviewed entire-interval decision for one uncertainty stratum."""
status: Literal["pass", "fail", "report-only"]
failed_metrics: tuple[_UncertaintyDecisionFailure, ...]
|
UncertaintyCalibrationReport
dataclass
Bias, dispersion, and one-sigma coverage for one reported error.
Source code in src/hebog/validation/comparison.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187 | @dataclass(frozen=True, slots=True)
class UncertaintyCalibrationReport:
"""Bias, dispersion, and one-sigma coverage for one reported error."""
metric: UncertaintyMetric
eligible_count: int
sample_count: int
availability_fraction: float
within_one_sigma_count: int
coverage_fraction: float | None
mean_normalized_residual: float | None
sample_standard_deviation: float | None
coverage_confidence_interval: (
BinomialConfidenceInterval | NumericConfidenceInterval | None
)
mean_confidence_interval: NumericConfidenceInterval | None
dispersion_confidence_interval: NumericConfidenceInterval | None
|
aggregate_island_comparisons(reports, *, confidence_level=0.95)
Aggregate a generated or governed island-comparison matrix.
Source code in src/hebog/validation/comparison.py
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996 | def aggregate_island_comparisons(
reports: Sequence[IslandComparisonReport],
*,
confidence_level: float = 0.95,
) -> IslandPopulationReport:
"""Aggregate a generated or governed island-comparison matrix."""
reference_count = sum(report.reference_count for report in reports)
candidate_count = sum(report.candidate_count for report in reports)
matched_count = sum(len(report.matches) for report in reports)
overlaps = np.asarray(
[
match.intersection_over_union
for report in reports
for match in report.matches
],
dtype=np.float64,
)
return IslandPopulationReport(
case_count=len(reports),
reference_count=reference_count,
candidate_count=candidate_count,
matched_count=matched_count,
completeness=_safe_classification_fraction(
matched_count,
reference_count,
empty_value=1.0,
),
reliability=_safe_classification_fraction(
matched_count,
candidate_count,
empty_value=1.0 if not reference_count else 0.0,
),
completeness_confidence_interval=wilson_score_interval(
matched_count,
reference_count,
confidence_level=confidence_level,
),
reliability_confidence_interval=wilson_score_interval(
matched_count,
candidate_count,
confidence_level=confidence_level,
),
split_count=sum(
len(report.split_reference_labels) for report in reports
),
merge_count=sum(
len(report.merged_candidate_labels) for report in reports
),
median_matched_intersection_over_union=_array_median(overlaps),
minimum_matched_intersection_over_union=(
float(np.min(overlaps)) if overlaps.size else None
),
)
|
compare_catalogues(reference, candidate, *, beam_fwhm_degrees, maximum_separation_beams, outlier_thresholds=None, position_angle_minimum_axis_ratio=None)
Match two catalogues and calculate scientific comparison metrics.
Source code in src/hebog/validation/comparison.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218 | def compare_catalogues( # noqa: PLR0913
reference: Sequence[CatalogueSource],
candidate: Sequence[CatalogueSource],
*,
beam_fwhm_degrees: float,
maximum_separation_beams: float,
outlier_thresholds: CatalogueOutlierThresholds | None = None,
position_angle_minimum_axis_ratio: float | None = None,
) -> CatalogueComparisonReport:
"""Match two catalogues and calculate scientific comparison metrics."""
if not np.isfinite(beam_fwhm_degrees) or beam_fwhm_degrees <= 0:
raise ValueError("beam_fwhm_degrees must be positive and finite")
if (
not np.isfinite(maximum_separation_beams)
or maximum_separation_beams <= 0
):
raise ValueError(
"maximum_separation_beams must be positive and finite"
)
shape_is_present = any(
source.fitted_shape is not None or source.deconvolved_shape is not None
for source in (*reference, *candidate)
)
if position_angle_minimum_axis_ratio is None:
if shape_is_present:
raise ValueError(
"position_angle_minimum_axis_ratio is required when "
"comparing shapes"
)
position_angle_axis_ratio = np.inf
else:
if (
not np.isfinite(position_angle_minimum_axis_ratio)
or position_angle_minimum_axis_ratio <= 1.0
):
raise ValueError(
"position_angle_minimum_axis_ratio must be finite and "
"greater than one"
)
position_angle_axis_ratio = position_angle_minimum_axis_ratio
_validate_catalogue_identifiers(reference, catalogue_name="reference")
_validate_catalogue_identifiers(candidate, catalogue_name="candidate")
assignments = _match_indices(
reference,
candidate,
beam_fwhm_degrees=beam_fwhm_degrees,
maximum_separation_beams=maximum_separation_beams,
)
matches: list[CatalogueMatch] = []
uncertainty_samples: dict[str, list[float]] = {}
uncertainty_eligible_counts: Counter[str] = Counter()
field_eligible_counts: Counter[str] = Counter()
field_available_counts: Counter[str] = Counter()
matched_reference_indices: set[int] = set()
matched_candidate_indices: set[int] = set()
for reference_index, candidate_index, separation_beams in assignments:
reference_source = reference[reference_index]
candidate_source = candidate[candidate_index]
matched_reference_indices.add(reference_index)
matched_candidate_indices.add(candidate_index)
fitted_shape_differences = _shape_differences(
reference_source.fitted_shape,
candidate_source.fitted_shape,
position_angle_minimum_axis_ratio=position_angle_axis_ratio,
)
deconvolved_shape_differences = _deconvolved_shape_differences(
reference_source,
candidate_source,
position_angle_minimum_axis_ratio=position_angle_axis_ratio,
)
_record_field_availability(
reference_source,
candidate_source,
field_eligible_counts,
field_available_counts,
)
uncertainty_eligible_counts.update(
_uncertainty_eligible_metrics(
reference_source,
position_angle_minimum_axis_ratio=position_angle_axis_ratio,
)
)
for metric, sample in normalized_uncertainty_samples(
reference_source,
candidate_source,
position_angle_minimum_axis_ratio=position_angle_axis_ratio,
):
uncertainty_samples.setdefault(metric, []).append(sample)
matches.append(
CatalogueMatch(
reference_identifier=reference_source.identifier,
candidate_identifier=candidate_source.identifier,
separation_beam_fwhm=separation_beams,
peak_flux_fractional_difference=(
candidate_source.peak_flux_jy_per_beam
- reference_source.peak_flux_jy_per_beam
)
/ reference_source.peak_flux_jy_per_beam,
integrated_flux_fractional_difference=(
candidate_source.integrated_flux_jy
- reference_source.integrated_flux_jy
)
/ reference_source.integrated_flux_jy,
fitted_major_axis_fractional_difference=(
fitted_shape_differences[0]
),
fitted_minor_axis_fractional_difference=(
fitted_shape_differences[1]
),
fitted_position_angle_difference_degrees=(
fitted_shape_differences[2]
),
deconvolved_major_axis_fractional_difference=(
deconvolved_shape_differences[0]
),
deconvolved_minor_axis_fractional_difference=(
deconvolved_shape_differences[1]
),
deconvolved_position_angle_difference_degrees=(
deconvolved_shape_differences[2]
),
unresolved_classification_agrees=(
_deconvolution_classification_agrees(
reference_source,
candidate_source,
)
),
component_count_agrees=(
None
if reference_source.component_count is None
or candidate_source.component_count is None
else reference_source.component_count
== candidate_source.component_count
),
quality_flag_jaccard=_quality_flag_jaccard(
reference_source,
candidate_source,
),
quality_flags_agree=(
reference_source.quality_flags
== candidate_source.quality_flags
),
)
)
separations = [match.separation_beam_fwhm for match in matches]
peak_flux_differences = [
abs(match.peak_flux_fractional_difference) for match in matches
]
integrated_flux_differences = [
abs(match.integrated_flux_fractional_difference) for match in matches
]
fitted_axis_differences = [
value
for match in matches
if (
value := _maximum_absolute_available(
(
match.fitted_major_axis_fractional_difference,
match.fitted_minor_axis_fractional_difference,
)
)
)
is not None
]
deconvolved_axis_differences = [
value
for match in matches
if (
value := _maximum_absolute_available(
(
match.deconvolved_major_axis_fractional_difference,
match.deconvolved_minor_axis_fractional_difference,
)
)
)
is not None
]
fitted_position_angle_differences = [
abs(match.fitted_position_angle_difference_degrees)
for match in matches
if match.fitted_position_angle_difference_degrees is not None
]
deconvolved_position_angle_differences = [
abs(match.deconvolved_position_angle_difference_degrees)
for match in matches
if match.deconvolved_position_angle_difference_degrees is not None
]
unresolved_classifications = [
match.unresolved_classification_agrees
for match in matches
if match.unresolved_classification_agrees is not None
]
component_comparisons = [
match.component_count_agrees
for match in matches
if match.component_count_agrees is not None
]
association_report = _association_report(reference, candidate, assignments)
catastrophic_outliers = (
tuple(
match.reference_identifier
for match in matches
if _is_catastrophic_outlier(match, outlier_thresholds)
)
if outlier_thresholds is not None
else ()
)
match_count = len(matches)
reference_count = len(reference)
candidate_count = len(candidate)
return CatalogueComparisonReport(
reference_count=reference_count,
candidate_count=candidate_count,
matches=tuple(matches),
unmatched_reference_identifiers=tuple(
source.identifier
for index, source in enumerate(reference)
if index not in matched_reference_indices
),
unmatched_candidate_identifiers=tuple(
source.identifier
for index, source in enumerate(candidate)
if index not in matched_candidate_indices
),
completeness=(
match_count / reference_count if reference_count else 1.0
),
reliability=(
match_count / candidate_count if candidate_count else 1.0
),
median_separation_beam_fwhm=_median(separations),
percentile_95_separation_beam_fwhm=_percentile_95(separations),
median_absolute_peak_flux_fractional_difference=_median(
peak_flux_differences
),
percentile_95_absolute_peak_flux_fractional_difference=(
_percentile_95(peak_flux_differences)
),
median_absolute_integrated_flux_fractional_difference=_median(
integrated_flux_differences
),
percentile_95_absolute_integrated_flux_fractional_difference=(
_percentile_95(integrated_flux_differences)
),
median_absolute_fitted_axis_fractional_difference=_median(
fitted_axis_differences
),
percentile_95_absolute_fitted_axis_fractional_difference=(
_percentile_95(fitted_axis_differences)
),
median_absolute_deconvolved_axis_fractional_difference=_median(
deconvolved_axis_differences
),
percentile_95_absolute_deconvolved_axis_fractional_difference=(
_percentile_95(deconvolved_axis_differences)
),
median_absolute_fitted_position_angle_difference_degrees=_median(
fitted_position_angle_differences
),
percentile_95_absolute_fitted_position_angle_difference_degrees=(
_percentile_95(fitted_position_angle_differences)
),
median_absolute_deconvolved_position_angle_difference_degrees=(
_median(deconvolved_position_angle_differences)
),
percentile_95_absolute_deconvolved_position_angle_difference_degrees=(
_percentile_95(deconvolved_position_angle_differences)
),
unresolved_classification_count=len(unresolved_classifications),
unresolved_classification_accuracy=(
sum(unresolved_classifications) / len(unresolved_classifications)
if unresolved_classifications
else None
),
field_availability=_field_availability_reports(
field_eligible_counts,
field_available_counts,
),
association=association_report,
component_count_comparison_count=len(component_comparisons),
component_count_agreement_fraction=(
sum(component_comparisons) / len(component_comparisons)
if component_comparisons
else None
),
quality_flag_exact_agreement_fraction=(
sum(match.quality_flags_agree for match in matches) / match_count
if match_count
else None
),
median_quality_flag_jaccard=_median(
[match.quality_flag_jaccard for match in matches]
),
uncertainty_calibration=_uncertainty_calibration_reports(
uncertainty_samples,
uncertainty_eligible_counts,
),
catastrophic_outlier_thresholds=outlier_thresholds,
catastrophic_outlier_reference_identifiers=catastrophic_outliers,
catastrophic_outlier_fraction=(
len(catastrophic_outliers) / match_count
if outlier_thresholds is not None and match_count
else None
),
)
|
compare_island_labels(reference, candidate, *, valid_mask=None)
Compare non-negative integer island labels by pixel overlap.
Source code in src/hebog/validation/comparison.py
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562 | def compare_island_labels(
reference: npt.ArrayLike,
candidate: npt.ArrayLike,
*,
valid_mask: npt.ArrayLike | None = None,
) -> IslandComparisonReport:
"""Compare non-negative integer island labels by pixel overlap."""
reference_array, candidate_array = _as_same_shape_arrays(
reference,
candidate,
)
reference_labels = _as_island_labels(reference_array)
candidate_labels = _as_island_labels(candidate_array)
valid = _valid_region(reference_array.shape, valid_mask)
compared_pixel_count = int(np.count_nonzero(valid))
reference_counts = _positive_label_counts(reference_labels, valid)
candidate_counts = _positive_label_counts(candidate_labels, valid)
intersections = _label_intersections(
reference_labels,
candidate_labels,
valid,
)
assigned = _match_label_overlaps(
intersections,
compared_pixel_count=compared_pixel_count,
)
matches = tuple(
IslandLabelMatch(
reference_label=reference_label,
candidate_label=candidate_label,
intersection_pixel_count=intersection,
union_pixel_count=(
reference_counts[reference_label]
+ candidate_counts[candidate_label]
- intersection
),
intersection_over_union=(
intersection
/ (
reference_counts[reference_label]
+ candidate_counts[candidate_label]
- intersection
)
),
)
for reference_label, candidate_label, intersection in assigned
)
matched_reference = {match.reference_label for match in matches}
matched_candidate = {match.candidate_label for match in matches}
reference_degrees: dict[int, int] = {}
candidate_degrees: dict[int, int] = {}
for reference_label, candidate_label in intersections:
reference_degrees[reference_label] = (
reference_degrees.get(reference_label, 0) + 1
)
candidate_degrees[candidate_label] = (
candidate_degrees.get(candidate_label, 0) + 1
)
overlap_values = np.asarray(
[match.intersection_over_union for match in matches],
dtype=np.float64,
)
return IslandComparisonReport(
compared_pixel_count=compared_pixel_count,
excluded_pixel_count=reference_labels.size - compared_pixel_count,
reference_count=len(reference_counts),
candidate_count=len(candidate_counts),
matches=matches,
unmatched_reference_labels=tuple(
sorted(set(reference_counts) - matched_reference)
),
unmatched_candidate_labels=tuple(
sorted(set(candidate_counts) - matched_candidate)
),
split_reference_labels=tuple(
sorted(
label
for label, degree in reference_degrees.items()
if degree > 1
)
),
merged_candidate_labels=tuple(
sorted(
label
for label, degree in candidate_degrees.items()
if degree > 1
)
),
completeness=_safe_classification_fraction(
len(matches),
len(reference_counts),
empty_value=1.0,
),
reliability=_safe_classification_fraction(
len(matches),
len(candidate_counts),
empty_value=1.0 if not reference_counts else 0.0,
),
median_matched_intersection_over_union=_array_median(overlap_values),
minimum_matched_intersection_over_union=(
float(np.min(overlap_values)) if overlap_values.size else None
),
)
|
compare_masks(reference, candidate, *, valid_mask=None)
Compare two boolean masks over an optional valid pixel region.
Source code in src/hebog/validation/comparison.py
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320 | def compare_masks(
reference: npt.ArrayLike,
candidate: npt.ArrayLike,
*,
valid_mask: npt.ArrayLike | None = None,
) -> MaskComparisonReport:
"""Compare two boolean masks over an optional valid pixel region."""
reference_array, candidate_array = _as_same_shape_arrays(
reference,
candidate,
)
if not np.issubdtype(reference_array.dtype, np.bool_) or not np.issubdtype(
candidate_array.dtype,
np.bool_,
):
raise TypeError("mask products must be boolean arrays")
valid = _valid_region(reference_array.shape, valid_mask)
reference_mask = np.asarray(reference_array, dtype=np.bool_)
candidate_mask = np.asarray(candidate_array, dtype=np.bool_)
true_positive = int(
np.count_nonzero(valid & reference_mask & candidate_mask)
)
true_negative = int(
np.count_nonzero(valid & ~reference_mask & ~candidate_mask)
)
false_positive = int(
np.count_nonzero(valid & ~reference_mask & candidate_mask)
)
false_negative = int(
np.count_nonzero(valid & reference_mask & ~candidate_mask)
)
compared = int(np.count_nonzero(valid))
reference_positive = true_positive + false_negative
candidate_positive = true_positive + false_positive
return MaskComparisonReport(
compared_pixel_count=compared,
excluded_pixel_count=reference_mask.size - compared,
true_positive_count=true_positive,
true_negative_count=true_negative,
false_positive_count=false_positive,
false_negative_count=false_negative,
agreement_fraction=_safe_classification_fraction(
true_positive + true_negative,
compared,
empty_value=1.0,
),
precision=_safe_classification_fraction(
true_positive,
candidate_positive,
empty_value=1.0 if reference_positive == 0 else 0.0,
),
recall=_safe_classification_fraction(
true_positive,
reference_positive,
empty_value=1.0,
),
intersection_over_union=_safe_classification_fraction(
true_positive,
true_positive + false_positive + false_negative,
empty_value=1.0,
),
)
|
compare_rms_maps(reference_rms_jy_per_beam, candidate_rms_jy_per_beam, *, valid_mask=None)
Compare non-negative RMS maps over finite, optionally masked pixels.
Source code in src/hebog/validation/comparison.py
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067 | def compare_rms_maps(
reference_rms_jy_per_beam: npt.ArrayLike,
candidate_rms_jy_per_beam: npt.ArrayLike,
*,
valid_mask: npt.ArrayLike | None = None,
) -> RmsComparisonReport:
"""Compare non-negative RMS maps over finite, optionally masked pixels."""
reference_input, candidate_input = _as_same_shape_arrays(
reference_rms_jy_per_beam,
candidate_rms_jy_per_beam,
)
reference = np.asarray(reference_input, dtype=np.float64)
candidate = np.asarray(candidate_input, dtype=np.float64)
selected = _valid_region(reference.shape, valid_mask)
if np.any(selected & np.isfinite(reference) & (reference < 0)) or np.any(
selected & np.isfinite(candidate) & (candidate < 0)
):
raise ValueError("finite RMS values must be non-negative")
comparable = selected & np.isfinite(reference) & np.isfinite(candidate)
absolute_differences = np.asarray(
np.abs(candidate[comparable] - reference[comparable]),
dtype=np.float64,
)
positive_reference = comparable & (reference > 0)
relative_differences = np.asarray(
np.abs(
(candidate[positive_reference] - reference[positive_reference])
/ reference[positive_reference]
),
dtype=np.float64,
)
compared_count = int(np.count_nonzero(comparable))
relative_count = int(np.count_nonzero(positive_reference))
zero_reference_count = int(np.count_nonzero(comparable & (reference == 0)))
return RmsComparisonReport(
compared_pixel_count=compared_count,
relative_pixel_count=relative_count,
excluded_pixel_count=reference.size - compared_count,
zero_reference_pixel_count=zero_reference_count,
median_absolute_difference_jy_per_beam=_array_median(
absolute_differences
),
percentile_95_absolute_difference_jy_per_beam=(
_array_percentile_95(absolute_differences)
),
median_absolute_fractional_difference=_array_median(
relative_differences
),
percentile_95_absolute_fractional_difference=(
_array_percentile_95(relative_differences)
),
)
|
evaluate_uncertainty_calibration(report, *, minimum_samples, nominal_coverage, maximum_absolute_coverage_difference, maximum_absolute_mean, minimum_standard_deviation, maximum_standard_deviation)
Apply the reviewed entire-confidence-interval decision rule.
Source code in src/hebog/validation/comparison.py
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941 | def evaluate_uncertainty_calibration( # noqa: PLR0913
report: UncertaintyCalibrationReport,
*,
minimum_samples: int,
nominal_coverage: float,
maximum_absolute_coverage_difference: float,
maximum_absolute_mean: float,
minimum_standard_deviation: float,
maximum_standard_deviation: float,
) -> UncertaintyCalibrationDecision:
"""Apply the reviewed entire-confidence-interval decision rule."""
if minimum_samples < _MINIMUM_MEAN_INTERVAL_SAMPLES:
raise ValueError("minimum_samples must be at least two")
if report.sample_count < minimum_samples:
return UncertaintyCalibrationDecision(
status="report-only",
failed_metrics=("insufficient-samples",),
)
coverage = report.coverage_confidence_interval
mean = report.mean_confidence_interval
dispersion = report.dispersion_confidence_interval
if coverage is None or mean is None or dispersion is None:
raise ValueError(
"eligible calibration report lacks confidence intervals"
)
failures: list[_UncertaintyDecisionFailure] = []
if (
coverage.lower
< nominal_coverage - maximum_absolute_coverage_difference
or coverage.upper
> nominal_coverage + maximum_absolute_coverage_difference
):
failures.append("coverage")
if (
mean.lower < -maximum_absolute_mean
or mean.upper > maximum_absolute_mean
):
failures.append("mean")
if (
dispersion.lower < minimum_standard_deviation
or dispersion.upper > maximum_standard_deviation
):
failures.append("dispersion")
return UncertaintyCalibrationDecision(
status="fail" if failures else "pass",
failed_metrics=tuple(failures),
)
|
normalized_uncertainty_samples(reference, candidate, *, position_angle_minimum_axis_ratio)
Return normalized candidate-minus-reference residuals.
A residual divides an offset by an uncertainty, so both must be the same
kind of angle. E_RA is a great-circle error, while differencing two right
ascensions gives coordinate degrees, so the RA offset is converted before
the division; without that the residual would be 1/cos(dec) too large.
Source code in src/hebog/validation/comparison.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657 | def normalized_uncertainty_samples(
reference: CatalogueSource,
candidate: CatalogueSource,
*,
position_angle_minimum_axis_ratio: float,
) -> tuple[tuple[UncertaintyMetric, float], ...]:
"""Return normalized candidate-minus-reference residuals.
A residual divides an offset by an uncertainty, so both must be the same
kind of angle. `E_RA` is a great-circle error, while differencing two right
ascensions gives coordinate degrees, so the RA offset is converted before
the division; without that the residual would be 1/cos(dec) too large.
"""
samples: list[tuple[UncertaintyMetric, float]] = []
def add(
metric: UncertaintyMetric,
difference: float,
uncertainty: float | None,
) -> None:
if uncertainty is not None:
samples.append((metric, difference / uncertainty))
add(
"right-ascension",
_signed_periodic_difference(
candidate.right_ascension_degrees,
reference.right_ascension_degrees,
period=_FULL_CIRCLE_DEGREES,
)
* cos(radians(candidate.declination_degrees)),
candidate.right_ascension_error_degrees,
)
add(
"declination",
candidate.declination_degrees - reference.declination_degrees,
candidate.declination_error_degrees,
)
add(
"peak-flux",
candidate.peak_flux_jy_per_beam - reference.peak_flux_jy_per_beam,
candidate.peak_flux_error_jy_per_beam,
)
add(
"integrated-flux",
candidate.integrated_flux_jy - reference.integrated_flux_jy,
candidate.integrated_flux_error_jy,
)
_add_shape_uncertainty_samples(
samples,
prefix="fitted",
reference=reference.fitted_shape,
candidate=candidate.fitted_shape,
position_angle_minimum_axis_ratio=position_angle_minimum_axis_ratio,
)
_add_shape_uncertainty_samples(
samples,
prefix="deconvolved",
reference=reference.deconvolved_shape,
candidate=candidate.deconvolved_shape,
position_angle_minimum_axis_ratio=position_angle_minimum_axis_ratio,
)
return tuple(samples)
|
uncertainty_calibration_report(metric, normalized_residuals, *, eligible_count, confidence_level, bootstrap_resamples, bootstrap_seed, cluster_ids=None, coverage_interval='wilson-score', mean_interval='student-t', dispersion_interval='scipy-bca-bootstrap-fixed-seed')
Summarize one uncertainty stratum with reviewed intervals.
Source code in src/hebog/validation/comparison.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892 | def uncertainty_calibration_report( # noqa: PLR0913
metric: UncertaintyMetric,
normalized_residuals: npt.ArrayLike,
*,
eligible_count: int,
confidence_level: float,
bootstrap_resamples: int,
bootstrap_seed: int,
cluster_ids: npt.ArrayLike | None = None,
coverage_interval: CoverageIntervalMethod = "wilson-score",
mean_interval: MeanIntervalMethod = "student-t",
dispersion_interval: DispersionIntervalMethod = (
"scipy-bca-bootstrap-fixed-seed"
),
) -> UncertaintyCalibrationReport:
"""Summarize one uncertainty stratum with reviewed intervals."""
if metric not in _UNCERTAINTY_METRICS:
raise ValueError("unsupported uncertainty metric")
values = np.asarray(normalized_residuals, dtype=np.float64)
if values.ndim != 1:
raise ValueError("normalized residuals must be one-dimensional")
if not np.all(np.isfinite(values)):
raise ValueError("normalized residuals must be finite")
if (
isinstance(eligible_count, bool)
or eligible_count < 0
or values.size > eligible_count
):
raise ValueError("eligible count must include every residual sample")
if not np.isfinite(confidence_level) or not 0 < confidence_level < 1:
raise ValueError("confidence_level must be finite and in (0, 1)")
if isinstance(bootstrap_resamples, bool) or bootstrap_resamples < 1:
raise ValueError("bootstrap_resamples must be positive")
if isinstance(bootstrap_seed, bool) or bootstrap_seed < 0:
raise ValueError("bootstrap_seed must be non-negative")
clustered = (
coverage_interval == "cluster-robust-student-t"
or mean_interval == "cluster-robust-student-t"
or dispersion_interval == "cluster-percentile-bootstrap-fixed-seed"
)
cluster_codes = _cluster_codes(values, cluster_ids) if clustered else None
sample_count = int(values.size)
within_one_sigma_count = int(np.count_nonzero(np.abs(values) <= 1.0))
coverage_values = np.asarray(np.abs(values) <= 1.0, dtype=np.float64)
return UncertaintyCalibrationReport(
metric=metric,
eligible_count=eligible_count,
sample_count=sample_count,
availability_fraction=(
sample_count / eligible_count if eligible_count else 0.0
),
within_one_sigma_count=within_one_sigma_count,
coverage_fraction=(
within_one_sigma_count / sample_count if sample_count else None
),
mean_normalized_residual=(
float(np.mean(values)) if sample_count else None
),
sample_standard_deviation=(
_sample_standard_deviation(values) if sample_count > 1 else None
),
coverage_confidence_interval=(
_cluster_robust_mean_interval(
coverage_values,
cast(npt.NDArray[np.int64], cluster_codes),
confidence_level=confidence_level,
bounds=(0.0, 1.0),
)
if coverage_interval == "cluster-robust-student-t"
else wilson_score_interval(
within_one_sigma_count,
sample_count,
confidence_level=confidence_level,
)
),
mean_confidence_interval=(
_cluster_robust_mean_interval(
values,
cast(npt.NDArray[np.int64], cluster_codes),
confidence_level=confidence_level,
)
if mean_interval == "cluster-robust-student-t"
else _student_mean_interval(
values,
confidence_level=confidence_level,
)
),
dispersion_confidence_interval=(
_cluster_dispersion_interval(
values,
cast(npt.NDArray[np.int64], cluster_codes),
confidence_level=confidence_level,
bootstrap_resamples=bootstrap_resamples,
bootstrap_seed=bootstrap_seed,
)
if dispersion_interval == "cluster-percentile-bootstrap-fixed-seed"
else _dispersion_interval(
values,
confidence_level=confidence_level,
bootstrap_resamples=bootstrap_resamples,
bootstrap_seed=bootstrap_seed,
)
),
)
|
wilson_score_interval(successes, total, *, confidence_level=0.95)
Return a Wilson interval, or None for an empty population.
Source code in src/hebog/validation/comparison.py
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599 | def wilson_score_interval(
successes: int,
total: int,
*,
confidence_level: float = 0.95,
) -> BinomialConfidenceInterval | None:
"""Return a Wilson interval, or ``None`` for an empty population."""
if (
isinstance(successes, bool)
or isinstance(total, bool)
or successes < 0
or total < 0
or successes > total
):
raise ValueError(
"binomial counts must satisfy 0 <= successes <= total"
)
if not np.isfinite(confidence_level) or not 0 < confidence_level < 1:
raise ValueError("confidence_level must be finite and in (0, 1)")
if total == 0:
return None
probability = successes / total
z_score = NormalDist().inv_cdf(0.5 + confidence_level / 2.0)
z_squared = z_score * z_score
denominator = 1.0 + z_squared / total
centre = probability + z_squared / (2.0 * total)
radius = z_score * np.sqrt(
probability * (1.0 - probability) / total
+ z_squared / (4.0 * total * total)
)
return BinomialConfidenceInterval(
confidence_level=confidence_level,
lower=float(max(0.0, (centre - radius) / denominator)),
upper=float(min(1.0, (centre + radius) / denominator)),
)
|