You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nmWTAI-Platform/ML/nmWTAI-ML/src/data/schedule_encoding.py

401 lines
9.3 KiB
Python

# -*- coding: utf-8 -*-
"""流量制度固定长度编码。
原始流量制度是变长的分段时长 timeQ 和对应流量 q。神经网络输入需要固定维度,
因此本模块先对制度做规范化,再把 q(t) 投影到固定时间网格,并可附加累计产量、
流量跳变和关井标记等辅助通道。
编码结果由 x_sched 和 x_sec 两部分组成:前者描述整条制度在时间网格上的形态,
后者描述当前 section_index 及总时长等段级上下文。
"""
# pylint: disable=import-error
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional, Tuple
import numpy as np
from src.common.config import Config
@dataclass
class EncodedSchedule:
"""固定长度流量制度编码结果。
x_sched 是按时间网格展开后的多通道制度特征,通常包含 q(t)、累计产量、流量跳变
和关井标记;x_sec 是段级上下文特征,描述当前 section_index 在整条制度中的位置、
制度总段数和总时长等信息。
"""
x_sched: np.ndarray
x_sec: np.ndarray
# pylint: disable=too-many-locals
def canonicalize_schedule(
cfg: Config,
time_q: List[float],
q: List[float],
) -> Tuple[np.ndarray, np.ndarray, bool]:
"""规范化变长流量制度。
该步骤把输入裁剪到求解器允许的最大段数,保证时长为正、流量非负,并按配置合并
相邻且流量近似相同的分段。规范化后再进入固定网格编码,可减少“同一制度因为
无意义细碎分段而得到不同特征”的情况。
"""
max_points = int(cfg.get("schedule", "max_points", default=512))
dt = np.asarray(
list(map(float, time_q)),
dtype=np.float64,
).reshape(-1)[:max_points]
qq = np.asarray(
list(map(float, q)),
dtype=np.float64,
).reshape(-1)[:max_points]
dt = np.maximum(dt, 1e-12)
qq = np.maximum(qq, 0.0)
canonical_cfg = (
cfg.raw["schedule"].get("canonicalize_for_model", {}) or {}
)
q_threshold = float(canonical_cfg.get("q_thr", 1e-6))
merge_same_q = bool(canonical_cfg.get("merge_same_q", True))
merge_rel_tol = float(canonical_cfg.get("merge_rel_tol", 1e-4))
remove_shutin = bool(canonical_cfg.get("remove_shutin", False))
has_shutin = bool(np.any(qq <= q_threshold))
if merge_same_q and dt.size >= 2:
new_dt = []
new_q = []
current_dt = float(dt[0])
current_q = float(qq[0])
def close(value_a: float, value_b: float) -> bool:
"""判断两个相邻流量是否可视为同一平台段。"""
denominator = max(abs(value_a), abs(value_b), 1.0)
return abs(value_a - value_b) / denominator <= merge_rel_tol
for idx in range(1, dt.size):
if close(float(qq[idx]), current_q):
current_dt += float(dt[idx])
else:
new_dt.append(current_dt)
new_q.append(current_q)
current_dt = float(dt[idx])
current_q = float(qq[idx])
new_dt.append(current_dt)
new_q.append(current_q)
dt = np.asarray(new_dt, dtype=np.float64)
qq = np.asarray(new_q, dtype=np.float64)
if remove_shutin and dt.size >= 2:
valid_mask = qq > q_threshold
if int(np.sum(valid_mask)) >= 2:
dt = dt[valid_mask]
qq = qq[valid_mask]
return dt, qq, has_shutin
def _make_u_grid(
cfg: Config,
total_time: float,
n_u_points: int,
mode: str,
) -> np.ndarray:
"""生成 [0, 1] 上的固定网格,用于把变长流量制度编码成定长向量。"""
obs_window_cfg = cfg.raw["schedule"].get("obs_window", {}) or {}
t_min = float(obs_window_cfg.get("t_min", 1e-6))
total_time = max(float(total_time), t_min * 2.0)
if mode == "linear":
return np.linspace(
t_min,
total_time,
n_u_points,
dtype=np.float64,
)
return np.geomspace(
t_min,
total_time,
n_u_points,
dtype=np.float64,
)
# pylint: disable=too-many-locals,too-many-statements
def encode_schedule_to_timegrid(
cfg: Config,
section_index: int,
time_q: List[float],
q: List[float],
n_sections: Optional[int] = None,
) -> EncodedSchedule:
"""把分段流量制度编码为神经网络可用的定长向量。
分段制度先转换为阶梯函数 q(t),再在固定时间网格 u 上采样。根据配置可附加累计
流量积分、相邻网格流量差分、关井标记等通道。最后再拼接 5 个 section 级特征,
让模型知道当前样本对应哪一个生产/关井分段,而不只看到整条制度形状。
"""
dt, qq, has_shutin = canonicalize_schedule(
cfg,
time_q,
q,
)
if dt.size < 2 or qq.size != dt.size:
raise ValueError("invalid schedule after canonicalize")
section_index = int(max(1, section_index))
n_sections_total = (
int(n_sections)
if n_sections is not None
else int(dt.size)
)
n_sections_total = max(n_sections_total, int(dt.size))
total_time = float(np.sum(dt))
encoding_cfg = cfg.raw["timegrid_encoding"]
n_u_points = int(encoding_cfg.get("n_u_points", 256))
grid_mode = str(
encoding_cfg.get("grid", "log"),
).lower()
include_cum = bool(
encoding_cfg.get("include_cum", True),
)
include_dq = bool(
encoding_cfg.get("include_dq", True),
)
include_shutin = bool(
encoding_cfg.get("include_shutin", False),
)
q_eps = float(
encoding_cfg.get("q_eps", 1e-12),
)
time_edges = np.concatenate(
[[0.0], np.cumsum(dt)],
axis=0,
)
u_grid = _make_u_grid(
cfg,
total_time=total_time,
n_u_points=n_u_points,
mode=(
"linear"
if grid_mode == "linear"
else "log"
),
)
interval_idx = np.searchsorted(
time_edges[1:],
u_grid,
side="right",
)
interval_idx = np.clip(
interval_idx,
0,
dt.size - 1,
)
q_u = qq[interval_idx].astype(np.float64)
cum_u = None
if include_cum:
prefix = np.concatenate(
[[0.0], np.cumsum(dt * qq)],
axis=0,
)
cum_u = (
prefix[interval_idx]
+ (
u_grid
- time_edges[:-1][interval_idx]
)
* qq[interval_idx]
)
dq_u = None
if include_dq:
dq_u = np.zeros_like(
u_grid,
dtype=np.float64,
)
dq_u[1:] = np.diff(q_u)
dq_u[0] = (
dq_u[1]
if dq_u.size > 1
else 0.0
)
shut_u = None
if include_shutin:
shutin_thr = float(
encoding_cfg.get("shutin_thr", 1e-6),
)
shut_u = (
q_u <= shutin_thr
).astype(np.float64)
normalize_mode = str(
encoding_cfg.get(
"normalize_mode",
"global",
)
).lower()
if normalize_mode == "per_sample":
q_scale = max(
float(np.max(q_u)),
q_eps,
)
cum_scale = max(
(
float(cum_u.max())
if cum_u is not None
else 1.0
),
q_eps,
)
else:
q_scale = float(
encoding_cfg.get(
"q_global_max",
1.0,
)
)
cum_scale = float(
encoding_cfg.get(
"cum_global_max",
1.0,
)
)
q_u = q_u / max(q_scale, q_eps)
if cum_u is not None:
cum_u = cum_u / max(
cum_scale,
q_eps,
)
if dq_u is not None:
dq_u = dq_u / max(
q_scale,
q_eps,
)
channels = [q_u]
if include_cum:
channels.append(
cum_u
if cum_u is not None
else np.zeros_like(q_u)
)
if include_dq:
channels.append(
dq_u
if dq_u is not None
else np.zeros_like(q_u)
)
if include_shutin:
channels.append(
shut_u
if shut_u is not None
else np.zeros_like(q_u)
)
x_grid = np.stack(
channels,
axis=1,
)
x_sched = x_grid.reshape(-1).astype(np.float32)
n_sections_total = int(
max(1, n_sections_total),
)
section_clamped = int(
np.clip(
section_index,
1,
n_sections_total,
)
)
section_pos = float(
(section_clamped - 1)
/ max(n_sections_total - 1, 1)
)
section_index_norm = float(
section_clamped
/ max(n_sections_total, 1)
)
n_sections_norm = float(
n_sections_total
/ max(12, 1)
)
log_total_time = float(
np.log(max(total_time, 1e-12))
)
x_sec = np.array(
[
section_index_norm,
section_pos,
n_sections_norm,
float(has_shutin),
log_total_time,
],
dtype=np.float32,
)
return EncodedSchedule(
x_sched=x_sched,
x_sec=x_sec,
)