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 191 192 193 194
| import torch import torch.nn as nn import torch.optim as optim import numpy as np
def encode_state(vehicle_pos, vehicle_speed, nodes_info): """ 输入: vehicle_pos: 车辆当前位置 (笛卡尔坐标) [x, y] vehicle_speed: 车辆速度向量 [vx, vy] nodes_info: 边缘节点信息列表,每个元素为 [节点x, 节点y, 计算能力, 信任度]
输出: state_tensor: 编码后的状态张量 (shape: [1, state_dim]) """ polar_features = [] for node in nodes_info: dx = node[0] - vehicle_pos[0] dy = node[1] - vehicle_pos[1] r = np.sqrt(dx ** 2 + dy ** 2) theta = np.arctan2(dy, dx) polar_features.extend([r, theta])
speed_norm = np.linalg.norm(vehicle_speed) if speed_norm > 0: v_r = (vehicle_speed[0] * dx + vehicle_speed[1] * dy) / (r + 1e-5) v_theta = (vehicle_speed[0] * dy - vehicle_speed[1] * dx) / (r + 1e-5) else: v_r, v_theta = 0.0, 0.0
lstm_hidden = np.random.randn(16)
state = np.concatenate([ polar_features, [v_r, v_theta], lstm_hidden, [node[2] for node in nodes_info], [node[3] for node in nodes_info] ])
return torch.FloatTensor(state).unsqueeze(0)
class Actor(nn.Module): def __init__(self, state_dim, action_dim, hidden_dim=256): super().__init__() self.net = nn.Sequential( nn.Linear(state_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, action_dim), nn.Tanh() )
def forward(self, state): return self.net(state)
class Critic(nn.Module): def __init__(self, state_dim, action_dim, hidden_dim=256): super().__init__() self.q_net = nn.Sequential( nn.Linear(state_dim + action_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 1) )
def forward(self, state, action): return self.q_net(torch.cat([state, action], dim=1))
class ST_SAC: def __init__(self, state_dim, action_dim, lr=3e-4, gamma=0.99, alpha=0.2, tau=0.005): self.actor = Actor(state_dim, action_dim) self.critic = Critic(state_dim, action_dim) self.critic_target = Critic(state_dim, action_dim) self.critic_target.load_state_dict(self.critic.state_dict())
self.actor_optim = optim.Adam(self.actor.parameters(), lr=lr) self.critic_optim = optim.Adam(self.critic.parameters(), lr=lr)
self.gamma = gamma self.alpha_base = alpha self.tau = tau
def select_action(self, state, nodes_info, trust_threshold=0.5): """ 选择动作(含安全掩码) """ with torch.no_grad(): action = self.actor(state)
valid_nodes = [i for i, node in enumerate(nodes_info) if node[3] >= trust_threshold] mask = torch.zeros_like(action) for i in valid_nodes: mask[:, i] = 1.0
masked_action = action * mask + (1 - mask) * torch.randn_like(action) return masked_action.squeeze(0).numpy()
def update(self, state, action, reward, next_state, done, vehicle_speed): v_r = abs(state[0, -len(nodes_info) * 2 + 1]) alpha = self.alpha_base * (1 + torch.sigmoid(torch.tensor(v_r)))
with torch.no_grad(): next_action = self.actor(next_state) target_q = self.critic_target(next_state, next_action) target_q = reward + (1 - done) * self.gamma * target_q
current_q = self.critic(state, action) critic_loss = nn.MSELoss()(current_q, target_q)
self.critic_optim.zero_grad() critic_loss.backward() self.critic_optim.step()
pred_action = self.actor(state) q_value = self.critic(state, pred_action).detach() actor_loss = -q_value.mean() + alpha * (pred_action ** 2).mean()
self.actor_optim.zero_grad() actor_loss.backward() self.actor_optim.step()
for t_param, param in zip(self.critic_target.parameters(), self.critic.parameters()): t_param.data.copy_(self.tau * param.data + (1 - self.tau) * t_param.data)
if __name__ == "__main__": vehicle_pos = [0.0, 0.0] vehicle_speed = [1.0, 0.0] nodes_info = [ [10.0, 0.0, 5.0, 0.8], [0.0, 5.0, 3.0, 0.3], [-5.0, 0.0, 4.0, 0.6] ]
state_dim = len(encode_state(vehicle_pos, vehicle_speed, nodes_info).squeeze(0)) action_dim = len(nodes_info) agent = ST_SAC(state_dim, action_dim)
state = encode_state(vehicle_pos, vehicle_speed, nodes_info) for _ in range(100): action = agent.select_action(state, nodes_info) next_vehicle_pos = [vehicle_pos[0] + 0.1, vehicle_pos[1]] next_state = encode_state(next_vehicle_pos, vehicle_speed, nodes_info) reward = -np.abs(action).mean() done = False
agent.update(state, torch.FloatTensor(action).unsqueeze(0), torch.FloatTensor([reward]), next_state, done, vehicle_speed) state = next_state
|