| from __future__ import annotations |
|
|
| import numpy as np |
| import pandas as pd |
|
|
| from shared.noise_analysis import ( |
| DOCUMENTED_LOCAL_NOISE_ANALYSIS_POST_ROWS, |
| DOCUMENTED_LOCAL_NOISE_ANALYSIS_PRE_ROWS, |
| first_detectable_time_from_baseline, |
| quantify_analysis, |
| ) |
| from shared.noise_snr import hash_string |
|
|
|
|
| _POSITION_COLUMN = "Position" |
| _VELOCITY_COLUMN = "Velocity" |
| _FORCE_COLUMN = "Hard_Stop_f" |
|
|
|
|
| def _scaled_noise_profile( |
| profile: dict[str, float], |
| *, |
| scale: float, |
| unscaled_keys: set[str] | None = None, |
| ) -> dict[str, float]: |
| fixed = unscaled_keys or set() |
| return { |
| key: float(value) if key in fixed else float(value) * float(scale) |
| for key, value in profile.items() |
| } |
|
|
|
|
| LOW = { |
| "position_base_sigma_scale": 0.002, |
| "position_drift_sigma_scale": 0.002, |
| "position_event_sigma_scale": 0.002, |
| "position_quant_step_scale": 0.002, |
| "position_quant_step_floor": 1e-4, |
| "velocity_base_sigma_scale": 0.002, |
| "velocity_hetero_sigma_scale": 0.002, |
| "velocity_drift_sigma_scale": 0.002, |
| "velocity_event_sigma_scale": 0.002, |
| "force_base_sigma_scale": 0.002, |
| "force_hetero_sigma_scale": 0.002, |
| "force_event_sigma_scale": 0.002, |
| } |
|
|
| HIGH_SCALE = 4.0 |
| HIGH = _scaled_noise_profile( |
| LOW, |
| scale=HIGH_SCALE, |
| ) |
|
|
| NOISE_DICT = {"low": LOW, "high": HIGH} |
| SNR_THR_DICT = { |
| "low": {"global": [-10000, -10000,-10000], "local": [-10000, -10000, -10000]}, |
| "high": {"global": [-10000, -10000,-10000], "local": [-10000, -10000, -10000]}, |
| } |
| _MAX_NOISE_RESAMPLE_ATTEMPTS = 25 |
|
|
|
|
| def _analysis_meets_thresholds( |
| noise_analysis: dict[str, list[float | str | None]], |
| *, |
| noise_level: str, |
| ) -> bool: |
| thresholds = SNR_THR_DICT[noise_level] |
| for scope in ("global", "local"): |
| values = noise_analysis.get(scope, []) |
| limit_values = thresholds.get(scope, []) |
| for idx, raw_value in enumerate(values): |
| if raw_value is None or idx >= len(limit_values): |
| continue |
| value = float(raw_value) |
| if np.isfinite(value) and value < float(limit_values[idx]): |
| return False |
| return True |
|
|
|
|
| def _rng(seed: int, key: str) -> np.random.Generator: |
| derived = (int(seed) ^ hash_string(key)) & 0xFFFFFFFF |
| return np.random.default_rng(derived) |
|
|
|
|
| def _values(df: pd.DataFrame, column: str) -> np.ndarray: |
| return pd.to_numeric(df[column], errors="coerce").to_numpy(dtype=float) |
|
|
|
|
| def _finite_scale(values: np.ndarray) -> float: |
| finite = values[np.isfinite(values)] |
| if finite.size == 0: |
| return 1.0 |
| spread = float(np.nanmax(finite) - np.nanmin(finite)) |
| rms = float(np.sqrt(np.mean(finite**2))) |
| return max(spread, rms, 1e-6) |
|
|
|
|
| def _coefficients(profile: str) -> dict[str, float]: |
| normalized = str(profile or "low").strip().lower() |
| if normalized == "low": |
| return LOW |
| if normalized == "high": |
| return HIGH |
| raise ValueError(f"Unknown noise profile '{profile}'. Expected 'low' or 'high'.") |
|
|
|
|
| def _smooth(values: np.ndarray) -> np.ndarray: |
| kernel = np.array([0.2, 0.3, 0.3, 0.2], dtype=float) |
| return np.convolve(values, kernel, mode="same") |
|
|
|
|
| def _drift(rng: np.random.Generator, n: int, scale: float) -> np.ndarray: |
| if n <= 0 or scale <= 0.0: |
| return np.zeros(n, dtype=float) |
| return _smooth(_smooth(rng.normal(0.0, scale, size=n))) |
|
|
|
|
| def _bounce_mask(position: np.ndarray, velocity: np.ndarray) -> np.ndarray: |
| n = min(position.size, velocity.size) |
| out = np.zeros(n, dtype=bool) |
| if n == 0: |
| return out |
| floor = float(np.nanmin(position[np.isfinite(position)])) if np.isfinite(position).any() else 0.0 |
| for idx in range(1, n): |
| if not np.isfinite(velocity[idx - 1]) or not np.isfinite(velocity[idx]): |
| continue |
| if not np.isfinite(position[idx]): |
| continue |
| is_bounce = velocity[idx - 1] < 0.0 and velocity[idx] > 0.0 and position[idx] <= floor + 0.1 |
| if is_bounce: |
| lo = max(0, idx - 2) |
| hi = min(n, idx + 3) |
| out[lo:hi] = True |
| return out |
|
|
|
|
| def _add_noise_once(df: pd.DataFrame, seed: int = 0, profile: str = "low") -> pd.DataFrame: |
| coeffs = _coefficients(profile) |
| out = df.copy() |
| if ( |
| _POSITION_COLUMN not in out.columns |
| and _VELOCITY_COLUMN not in out.columns |
| and _FORCE_COLUMN not in out.columns |
| ): |
| return out |
|
|
| position = ( |
| _values(out, _POSITION_COLUMN) |
| if _POSITION_COLUMN in out.columns |
| else np.array([], dtype=float) |
| ) |
| velocity = ( |
| _values(out, _VELOCITY_COLUMN) |
| if _VELOCITY_COLUMN in out.columns |
| else np.array([], dtype=float) |
| ) |
| bounces = _bounce_mask(position, velocity) |
|
|
| if _POSITION_COLUMN in out.columns: |
| values = position |
| scale = _finite_scale(values) |
| rng = _rng(seed, _POSITION_COLUMN) |
| noisy = values.copy() |
| noisy += rng.normal( |
| 0.0, |
| coeffs["position_base_sigma_scale"] * scale, |
| size=values.size, |
| ) |
| noisy += _drift(rng, values.size, coeffs["position_drift_sigma_scale"] * scale) |
| if bounces.size == values.size: |
| noisy += ( |
| rng.normal( |
| 0.0, |
| coeffs["position_event_sigma_scale"] * scale, |
| size=values.size, |
| ) |
| * bounces.astype(float) |
| ) |
| quant_step = max( |
| coeffs["position_quant_step_scale"] * scale, |
| coeffs["position_quant_step_floor"], |
| ) |
| noisy = np.round(noisy / quant_step) * quant_step |
| out[_POSITION_COLUMN] = np.maximum(noisy, 0.0) |
|
|
| if _VELOCITY_COLUMN in out.columns: |
| values = velocity |
| scale = _finite_scale(values) |
| rng = _rng(seed, _VELOCITY_COLUMN) |
| speed = np.abs(values) |
| ref = float(np.nanmedian(speed[np.isfinite(speed)])) if np.isfinite(speed).any() else 0.0 |
| sigma = ( |
| coeffs["velocity_base_sigma_scale"] * scale |
| + coeffs["velocity_hetero_sigma_scale"] * np.maximum(speed, ref) |
| ) |
| noisy = values.copy() |
| noisy += rng.normal(0.0, sigma, size=values.size) |
| noisy += _drift(rng, values.size, coeffs["velocity_drift_sigma_scale"] * scale) |
| if bounces.size == values.size: |
| noisy += ( |
| rng.normal( |
| 0.0, |
| coeffs["velocity_event_sigma_scale"] * scale, |
| size=values.size, |
| ) |
| * bounces.astype(float) |
| ) |
| out[_VELOCITY_COLUMN] = noisy |
|
|
| if _FORCE_COLUMN in out.columns: |
| values = _values(out, _FORCE_COLUMN) |
| scale = _finite_scale(values) |
| rng = _rng(seed, _FORCE_COLUMN) |
| magnitude = np.abs(values) |
| ref = ( |
| float(np.nanmedian(magnitude[np.isfinite(magnitude)])) |
| if np.isfinite(magnitude).any() |
| else 0.0 |
| ) |
| sigma = ( |
| coeffs["force_base_sigma_scale"] * scale |
| + coeffs["force_hetero_sigma_scale"] * np.maximum(magnitude, ref) |
| ) |
| noisy = values.copy() |
| noisy += rng.normal(0.0, sigma, size=values.size) |
| if bounces.size == values.size: |
| noisy += ( |
| rng.normal( |
| 0.0, |
| coeffs["force_event_sigma_scale"] * scale, |
| size=values.size, |
| ) |
| * bounces.astype(float) |
| ) |
| out[_FORCE_COLUMN] = noisy |
|
|
| return out |
|
|
|
|
| def quantify_noise( |
| clean: pd.DataFrame, |
| noisy: pd.DataFrame, |
| baseline: pd.DataFrame | None, |
| ) -> dict[str, list[float | str | None]]: |
| first_diff = first_detectable_time_from_baseline(clean, baseline) |
| analysis = quantify_analysis( |
| clean, |
| noisy, |
| reference_df=baseline, |
| first_diff=first_diff, |
| local_pre_rows=DOCUMENTED_LOCAL_NOISE_ANALYSIS_PRE_ROWS, |
| local_post_rows=DOCUMENTED_LOCAL_NOISE_ANALYSIS_POST_ROWS, |
| ) |
| if first_diff is None or "local" not in analysis: |
| analysis["local"] = [None] * len(analysis.get("global", [])) |
| return analysis |
|
|
|
|
| def add_noise( |
| clean: pd.DataFrame, |
| baseline: pd.DataFrame | None, |
| seed: int = 0, |
| noise_level: str = "low", |
| ) -> tuple[pd.DataFrame, dict[str, list[float | str | None]]]: |
| normalized = str(noise_level or "low").strip().lower() |
| if normalized not in NOISE_DICT: |
| raise ValueError(f"Unknown noise level '{noise_level}'. Expected 'low' or 'high'.") |
| current_seed = int(seed) |
| for _attempt in range(_MAX_NOISE_RESAMPLE_ATTEMPTS + 1): |
| noisy_df = _add_noise_once(clean, seed=current_seed, profile=normalized) |
| noise_analysis = quantify_noise(clean, noisy_df, baseline) |
| if _analysis_meets_thresholds(noise_analysis, noise_level=normalized): |
| return noisy_df, noise_analysis |
| current_seed += 1000 |
| raise RuntimeError( |
| f"Could not satisfy minimum SNR thresholds for noise level '{normalized}' " |
| f"after {_MAX_NOISE_RESAMPLE_ATTEMPTS + 1} attempts." |
| ) |
|
|
|
|
| __all__ = ["HIGH", "LOW", "NOISE_DICT", "SNR_THR_DICT", "add_noise", "quantify_noise"] |
|
|