from __future__ import annotations from typing import Optional, Tuple import numpy as np from src.common.config import Config def is_valid_curve( cfg: Config, t: np.ndarray, p: np.ndarray, d: np.ndarray, min_len: Optional[int] = None, max_nonpos_deriv_frac: Optional[float] = None, p_log10_max: Optional[float] = None, d_log10_max: Optional[float] = None, ) -> Tuple[bool, str]: """筛除不适合用于训练的求解器输出曲线。""" c = cfg.raw["curve_processing"] min_len = int(min_len if min_len is not None else c.get("min_valid_points", 30)) max_nonpos_deriv_frac = float( max_nonpos_deriv_frac if max_nonpos_deriv_frac is not None else c.get("max_nonpos_deriv_frac", 0.80) ) p_log10_max = float(p_log10_max if p_log10_max is not None else c.get("p_log10_max", 6.0)) d_log10_max = float(d_log10_max if d_log10_max is not None else c.get("d_log10_max", 6.0)) t = np.asarray(t, dtype=np.float64).reshape(-1) p = np.asarray(p, dtype=np.float64).reshape(-1) d = np.asarray(d, dtype=np.float64).reshape(-1) if t.size < min_len or p.size != t.size or d.size != t.size: return False, "too_short_or_shape_mismatch" if not (np.isfinite(t).all() and np.isfinite(p).all() and np.isfinite(d).all()): return False, "non_finite" if np.any(t <= 0) or np.any(p <= 0): return False, "non_positive" nonpos = int(np.sum(d <= 0.0)) if nonpos / max(d.size, 1) > max_nonpos_deriv_frac: return False, "deriv_nonpos_too_many" pmax = float(np.max(p)) dmax = float(np.max(np.abs(d))) if pmax <= 0 or dmax <= 0: return False, "non_positive_max" if np.log10(pmax) > p_log10_max: return False, "pressure_exploded" if np.log10(dmax) > d_log10_max: return False, "deriv_exploded" return True, "" def clean_curve_for_dataset( cfg: Config, t: np.ndarray, p: np.ndarray, d: np.ndarray, min_len: Optional[int] = None, eps: Optional[float] = None, outlier_factor: Optional[float] = None, ) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]: """ 清洗原始双对数曲线,但不删除可能具有物理意义的尖峰。 当前数据集生成流程故意不做 IQR/离群点删除,因为压力导数尖峰可能 对应真实的流动阶段信息。这里仅保留有限正值点、按时间排序、删除 重复时间点,并检查剩余点数是否足够。 """ c = cfg.raw["curve_processing"] min_len = int(min_len if min_len is not None else c.get("min_valid_points", 30)) eps = float(eps if eps is not None else c.get("feature_epsilon", 1e-12)) t = np.asarray(t, np.float64).reshape(-1) p = np.asarray(p, np.float64).reshape(-1) d = np.asarray(d, np.float64).reshape(-1) # 在插值和取对数之前先做基础合法性过滤。 m = np.isfinite(t) & np.isfinite(p) & np.isfinite(d) & (t > 0.0) & (p > 0.0) if int(np.sum(m)) < min_len: return None t = t[m] p = p[m] d = d[m] # 插值要求时间单调递增。 idx = np.argsort(t) t = t[idx] p = p[idx] d = d[idx] # 删除重复时间点,避免 np.interp 在重复横坐标上产生不稳定行为。 if t.size >= 2: keep = np.ones_like(t, dtype=bool) keep[1:] = t[1:] > t[:-1] t = t[keep] p = p[keep] d = d[keep] if t.size < min_len: return None # 防止极小正压力值导致后续取对数不稳定。 p = np.maximum(p, eps) return t, p, d def _make_time_grid(cfg: Config, t0: float, t1: float, n: int) -> np.ndarray: t0 = max(float(t0), float(cfg.get("curve_processing", "min_time_floor", default=1e-6))) t1 = min(float(t1), float(cfg.get("curve_processing", "max_time_cap", default=3000.0))) t1 = max(t1, t0 * 1.0001) return np.geomspace(t0, t1, int(n), dtype=np.float64) def curve_time_grid_for_sample(cfg: Config, t: np.ndarray, n: Optional[int] = None) -> np.ndarray: """Return the exact time grid used for curve resampling.""" nT = int(n if n is not None else cfg.get("curve_processing", "n_time_points", default=160)) t = np.asarray(t, dtype=np.float64).reshape(-1) if t.size < 2: raise RuntimeError("curve_time_grid_for_sample: time array is too short") fixed = cfg.get("curve_processing", "fixed_time_range", default=None) if fixed is not None: t0, t1 = float(fixed[0]), float(fixed[1]) else: t0 = float(np.min(t)) t1 = float(np.max(t)) return _make_time_grid(cfg, t0, t1, nT).astype(np.float32) def resample_curve_to_features_with_time( cfg: Config, t: np.ndarray, p: np.ndarray, d: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """将一条求解器曲线转换为固定长度的训练目标向量。""" eps = float(cfg.get("curve_processing", "feature_epsilon", default=1e-12)) nT = int(cfg.get("curve_processing", "n_time_points", default=160)) use_slope = bool(cfg.get("curve_processing", "use_slope_feature", default=True)) t = np.asarray(t, dtype=np.float64).reshape(-1) p = np.asarray(p, dtype=np.float64).reshape(-1) d = np.asarray(d, dtype=np.float64).reshape(-1) if t.size < 2: raise RuntimeError("resample_curve_to_features: 时间点过少") grid = curve_time_grid_for_sample(cfg, t, n=nT).astype(np.float64) logp = np.log(np.maximum(p, eps)) logd = np.log(np.maximum(np.abs(d), eps)) # 所有样本都重采样到同一个几何时间网格上,模型预测该网格上的 # log_pressure 和 log_derivative。 lp = np.interp(grid, t, logp).astype(np.float32) ld = np.interp(grid, t, logd).astype(np.float32) feats = [lp, ld] if use_slope: # slope 作为辅助特征保留;即使训练权重设为 0,也能保持数据布局兼容。 logt = np.log(np.maximum(grid, eps)).astype(np.float64) s = np.zeros((nT,), dtype=np.float32) if nT >= 3: denom = logt[2:] - logt[:-2] denom = np.maximum(denom, 1e-12) s[1:-1] = ((lp[2:] - lp[:-2]) / denom).astype(np.float32) s[0] = s[1] s[-1] = s[-2] feats.append(s) x = np.concatenate(feats, axis=0).astype(np.float32) if x.size != cfg.curve_dim: raise RuntimeError(f"curve feature dim mismatch: got {x.size}, expect {cfg.curve_dim}") return x, grid.astype(np.float32) def resample_curve_to_features(cfg: Config, t: np.ndarray, p: np.ndarray, d: np.ndarray) -> np.ndarray: features, _ = resample_curve_to_features_with_time(cfg, t, p, d) return features