File size: 7,105 Bytes
4c61b7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
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