"""Fixed class/family/frame/pixel mass and deterministic point budgets. The caller supplies the complete source-group to exclusion-family mapping, filters the held family and validates source/target admission before this helper. Original group and split metadata are preserved. A mapping must cover all study families, even when one arm contains no frames from some of its source groups. """ from collections.abc import Mapping import numpy as np def _identity(value): return isinstance(value, str) and bool(value) def prepare(records, held_family, family_by_group): """Return sample-sorted record copies, float64 weights and JSON mass audit. Each class receives .5 total mass, divided equally among allowed families, then among frames supporting that class, then among its pixels. Every allowed family must support both classes, but a frame may support only one. Unknown-only frames cannot receive positive sampling quotas and are rejected. Record dicts and targets are copied; unrelated payloads are shared untouched. """ if ( not _identity(held_family) or not isinstance(family_by_group, Mapping) or not family_by_group or any(not _identity(g) or not _identity(f) for g, f in family_by_group.items()) ): raise ValueError("Explicit nonempty source-group/family mapping required") families = set(family_by_group.values()) if held_family not in families: raise ValueError("Held family must be present in the study mapping") allowed = sorted(families - {held_family}) records = list(records) if not records or not allowed: raise ValueError("Nonempty records and allowed families required") names, samples, observed = set(), set(), set() for record in records: if not isinstance(record, Mapping) or any( not _identity(record.get(key)) for key in ("name", "sample_id", "group") ): raise ValueError("Record name, sample_id and source group required") name, sid, group = (record[k] for k in ("name", "sample_id", "group")) if name in names or sid in samples: raise ValueError("Duplicate frame name or sample_id") names.add(name) samples.add(sid) if group not in family_by_group: raise ValueError("Source group missing from explicit family mapping") family = family_by_group[group] if family == held_family: raise ValueError("Held family must never be admitted; caller must filter it") observed.add(family) target = record.get("target") if ( not isinstance(target, np.ndarray) or target.dtype != np.uint8 or target.ndim != 2 or not target.size or not np.isin(target, (0, 1, 255)).all() ): raise ValueError("Nonempty 2D uint8 targets with labels 0, 1, 255 required") if not np.any(target != 255): raise ValueError("Every frame needs known class support") if observed != set(allowed): raise ValueError("Every allowed family must be represented in both study arms") out = [ dict(r, target=r["target"].copy()) for r in sorted(records, key=lambda r: r["sample_id"]) ] weights = {r["name"]: np.zeros(r["target"].shape, dtype=np.float64) for r in out} support = { r["name"]: {label: int((r["target"] == label).sum()) for label in (0, 1)} for r in out } family_classes = [] family_mass = 0.5 / len(allowed) for family in allowed: rows = [r for r in out if family_by_group[r["group"]] == family] for label in (0, 1): present = [r for r in rows if support[r["name"]][label]] if not present: raise ValueError("Every allowed family must support both classes") frame_mass = family_mass / len(present) for row in present: mask = row["target"] == label weights[row["name"]][mask] = frame_mass / support[row["name"]][label] actual = sum( float(weights[r["name"]][r["target"] == label].sum()) for r in present ) if not np.isclose(actual, family_mass, rtol=1e-12, atol=1e-12): raise ValueError("Family/class mass accounting failed") family_classes.append( dict( family=family, label=label, supported_frames=len(present), pixels=sum(support[r["name"]][label] for r in present), expected_mass=family_mass, mass=actual, ) ) frames = [] for row in out: target, weight = row["target"], weights[row["name"]] if ( not np.isfinite(weight).all() or np.any(weight[target != 255] <= 0) or np.any(weight[target == 255] != 0) ): raise ValueError("Finite positive known weights and zero unknown weights required") frames.append( dict( name=row["name"], sample_id=row["sample_id"], group=row["group"], family=family_by_group[row["group"]], unknown_pixels=int((target == 255).sum()), mass=float(weight.sum()), classes=[ dict( label=label, pixels=support[row["name"]][label], mass=float(weight[target == label].sum()), ) for label in (0, 1) ], ) ) classes = [] for label in (0, 1): actual = sum(f["classes"][label]["mass"] for f in frames) if not np.isclose(actual, 0.5, rtol=1e-12, atol=1e-12): raise ValueError("Global class mass accounting failed") classes.append( dict( label=label, expected_mass=0.5, mass=actual, pixels=sum(support[r["name"]][label] for r in out), ) ) total = sum(f["mass"] for f in frames) if not np.isclose(total, 1.0, rtol=1e-12, atol=1e-12): raise ValueError("Total mass accounting failed") return out, weights, dict( schema="missioncore.diversity-mass/v1", held_family=held_family, allowed_families=allowed, total_mass=total, classes=classes, family_classes=family_classes, frames=frames, ) def quotas(total_points, frames, step): """Allocate positive int64 quotas in frame order; rotate remainder by step. Sum is total_points; over any complete frames-step cycle every frame receives exactly total_points draws. The caller aligns this vector with sorted records. """ values = (total_points, frames, step) if any( not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_)) for v in values ): raise ValueError("Integer point budget, frame count and step required") total_points, frames, step = (int(v) for v in values) if ( frames <= 0 or total_points < frames or total_points > np.iinfo(np.int64).max or step < 0 ): raise ValueError("Positive per-frame budget and nonnegative step required") base, remainder = divmod(total_points, frames) result = np.full(frames, base, dtype=np.int64) start = step % frames stop = start + remainder result[start:min(stop, frames)] += 1 result[:max(0, stop - frames)] += 1 return result