Download models/utils.py from Hang917/DynaTraj: direct link, hf CLI and curl.
- Browser
- Download file 7.11 kB
-
https://huggingface.co/datasets/Hang917/DynaTraj/resolve/main/models/utils.py
- Command line
-
hf download hf://datasets/Hang917/DynaTraj/models/utils.py
-
curl -L -o utils.py https://huggingface.co/datasets/Hang917/DynaTraj/resolve/main/models/utils.py
7.11 kB
| """ | |
| Model Utility Functions | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| def interpolate_trajectory(t_eval, t_query, traj, dim_batch=1): | |
| """ | |
| Interpolate trajectory (z or x) at t_query based on t_eval and traj. | |
| Args: | |
| t_eval: [T] time grid of ODE solution | |
| t_query: [B, L] query times for each batch | |
| traj: [T, B, D] trajectory (z or x) | |
| dim_batch: batch dimension (default 1) | |
| Returns: | |
| interp: [B, L, D] | |
| """ | |
| B, L = t_query.shape | |
| T = t_eval.shape[0] | |
| indices_flat = torch.searchsorted(t_eval, t_query.flatten(), right=False) | |
| indices = torch.clamp(indices_flat, 0, T - 2).reshape(B, L) | |
| t_left = t_eval[indices] | |
| t_right = t_eval[indices + 1] | |
| batch_indices = torch.arange(B, device=t_eval.device).unsqueeze(1).expand(-1, L) | |
| traj_left = traj[indices, batch_indices, :] | |
| traj_right = traj[indices + 1, batch_indices, :] | |
| weight = ((t_query - t_left) / (t_right - t_left + 1e-8)).unsqueeze(-1) | |
| interp = traj_left + weight * (traj_right - traj_left) | |
| return interp | |
| def interpolate_external_input(t_eval, t_batch, ut_batch, external_input_dim): | |
| """ | |
| Interpolate external input at t_eval times using existing interpolate_trajectory function. | |
| Args: | |
| t_eval: [T] evaluation times | |
| t_batch: [B, L] relative time batches (not used, for API consistency) | |
| ut_batch: [B, L_u, U+1] external input batch with time as last dimension | |
| external_input_dim: dimension of external input | |
| Returns: | |
| u_interp: [T, B, U] interpolated external inputs | |
| """ | |
| if ut_batch is None or external_input_dim == 0: | |
| return None | |
| u_batch = ut_batch[:, :, :external_input_dim] # [B, L_u, U] | |
| t_u_batch = ut_batch[:, :, external_input_dim] # [B, L_u] | |
| B, L_u, U = u_batch.shape | |
| T = len(t_eval) | |
| # 简单粗暴:用第一个batch的时间网格,假设所有batch时间一致 | |
| t_u = t_u_batch[0, :] - t_batch[0] # [L_u] | |
| t_query = t_eval.unsqueeze(0).expand(B, -1) # [B, T] | |
| traj = u_batch.permute(1, 0, 2) # [L_u, B, U] | |
| # 直接调用 interpolate_trajectory | |
| result = interpolate_trajectory(t_u, t_query, traj) # [B, T, U] | |
| # 转置成需要的格式 [T, B, U] | |
| return result.permute(1, 0, 2) | |
| def create_vector_field_with_external_input(base_vector_field, u_interp, t_eval): | |
| """ | |
| Universal wrapper to add external input to any vector field. | |
| Args: | |
| base_vector_field: Original vector field function | |
| u_interp: [T, B, U] interpolated external inputs (None if no external input) | |
| t_eval: [T] evaluation times | |
| Returns: | |
| Enhanced vector field function that includes external input | |
| """ | |
| if u_interp is None: | |
| return base_vector_field | |
| def vector_field_with_input(t, state): | |
| t_idx = torch.searchsorted(t_eval, t, right=False) | |
| t_idx = torch.clamp(t_idx, 0, len(t_eval) - 1) | |
| u_t = u_interp[t_idx, :, :] # [B, U] | |
| return base_vector_field(t, state, u_t) | |
| return vector_field_with_input | |
| class VectorFieldWithInput(nn.Module): | |
| def __init__(self, base_vector_field: nn.Module, u_interp, t_eval): | |
| """ | |
| base_vector_field: nn.Module, takes (t, state, u_t) and outputs dx/dt | |
| u_interp: [T, B, U] external inputs sampled on t_eval (None if no input) | |
| t_eval: [T] monotonically nondecreasing time grid corresponding to u_interp | |
| """ | |
| super().__init__() | |
| self.base_vector_field = base_vector_field | |
| self.register_buffer("t_eval", t_eval) # 注册成 buffer, 会跟随 device 移动 | |
| if u_interp is not None: | |
| self.register_buffer("u_interp", u_interp) | |
| else: | |
| self.u_interp = None | |
| def forward(self, t, state): | |
| if self.u_interp is None: | |
| # 无外部输入,保持三输入形式 | |
| return self.base_vector_field(t, state) | |
| T = self.t_eval.shape[0] | |
| t_scalar = torch.as_tensor(t, dtype=self.t_eval.dtype, device=self.t_eval.device) | |
| # Clamp to endpoints | |
| if t_scalar <= self.t_eval[0]: | |
| u_t = self.u_interp[0, :, :] # [B, U] | |
| elif t_scalar >= self.t_eval[-1]: | |
| u_t = self.u_interp[-1, :, :] | |
| else: | |
| idx_right = torch.searchsorted(self.t_eval, t_scalar, right=False) | |
| idx_right = torch.clamp(idx_right, 1, T - 1) | |
| idx_left = idx_right - 1 | |
| t_left = self.t_eval[idx_left] | |
| t_right = self.t_eval[idx_right] | |
| u_left = self.u_interp[idx_left, :, :] | |
| u_right = self.u_interp[idx_right, :, :] | |
| w = (t_scalar - t_left) / (t_right - t_left + 1e-8) | |
| u_t = u_left + w * (u_right - u_left) | |
| # 传给原始 vector field(恢复三参数形式,不再拼接) | |
| return self.base_vector_field(t, state, u_t) | |
| def create_vector_field_with_external_input(base_vector_field, u_interp, t_eval): | |
| return VectorFieldWithInput(base_vector_field, u_interp, t_eval) | |
| # def create_vector_field_with_external_input(base_vector_field, u_interp, t_eval): | |
| # """ | |
| # Wrap a vector field to inject time-varying external input u(t) via linear interpolation. | |
| # Args: | |
| # base_vector_field: callable(t, state, u_t) -> dx/dt | |
| # u_interp: [T, B, U] external inputs sampled on t_eval (None if no input) | |
| # t_eval: [T] monotonically nondecreasing time grid corresponding to u_interp | |
| # Returns: | |
| # vector_field_with_input(t, state): calls base_vector_field with linearly | |
| # interpolated u(t) aligned to t_eval. | |
| # """ | |
| # if u_interp is None: | |
| # return base_vector_field | |
| # T = t_eval.shape[0] | |
| # def vector_field_with_input(t, state): | |
| # # Ensure t is a tensor on the same device/dtype as t_eval | |
| # t_scalar = torch.as_tensor(t, dtype=t_eval.dtype, device=t_eval.device) | |
| # # Clamp to endpoints: constant extension outside [t_eval[0], t_eval[-1]] | |
| # if t_scalar <= t_eval[0]: | |
| # u_t = u_interp[0, :, :] # [B, U] | |
| # elif t_scalar >= t_eval[-1]: | |
| # u_t = u_interp[-1, :, :] # [B, U] | |
| # else: | |
| # # Find the right interval [t_left, t_right] with t_left <= t < t_right | |
| # idx_right = torch.searchsorted(t_eval, t_scalar, right=False) | |
| # # Guarantee we have both neighbors | |
| # idx_right = torch.clamp(idx_right, 1, T - 1) | |
| # idx_left = idx_right - 1 | |
| # t_left = t_eval[idx_left] | |
| # t_right = t_eval[idx_right] | |
| # u_left = u_interp[idx_left, :, :] # [B, U] | |
| # u_right = u_interp[idx_right, :, :] # [B, U] | |
| # # Linear interpolation weight in [0,1] | |
| # w = (t_scalar - t_left) / (t_right - t_left + 1e-8) | |
| # # Linear interpolation of u(t) | |
| # u_t = u_left + w * (u_right - u_left) # [B, U] | |
| # # Call the original vector field with interpolated control | |
| # return base_vector_field(t, state, u_t) | |
| # return vector_field_with_input | |