"""Simulated modality dropout. The paper evaluates robustness by randomly omitting one input source at inference time, at dropout rates of 20% and 50%. A dropped modality is passed to the fusion layer as missing (mask = 0), which substitutes the uniform distribution (Eq. 15). """ from __future__ import annotations from typing import Optional import numpy as np MODES = ("either", "hist", "risk", "both") def simulate_dropout( n: int, rate: float, mode: str = "either", rng: Optional[np.random.Generator] = None, ) -> tuple[np.ndarray, np.ndarray]: """Draw modality masks (m_p, m_q) with a given dropout rate. Parameters ---------- n: Number of samples. rate: Fraction of samples affected by dropout, in [0, 1]. mode: ``"either"`` (default) - each affected sample loses one modality, chosen uniformly at random (this matches "randomly omitting 1 input source"). ``"hist"`` - affected samples lose the histopathology input. ``"risk"`` - affected samples lose the clinical risk input. ``"both"`` - affected samples lose both inputs. rng: NumPy random generator, for reproducibility. Returns ------- (m_p, m_q): Boolean presence masks, shape (n,). True means the modality is present. """ if not 0.0 <= rate <= 1.0: raise ValueError("rate must lie in [0, 1]") if mode not in MODES: raise ValueError(f"mode must be one of {MODES}") rng = rng if rng is not None else np.random.default_rng() affected = rng.random(n) < rate m_p = np.ones(n, dtype=bool) m_q = np.ones(n, dtype=bool) if mode == "hist": m_p[affected] = False elif mode == "risk": m_q[affected] = False elif mode == "both": m_p[affected] = False m_q[affected] = False else: # either drop_hist = rng.random(n) < 0.5 m_p[affected & drop_hist] = False m_q[affected & ~drop_hist] = False return m_p, m_q