太阳能板最优化角度

实现单板最优角度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import torch
import random

best_angle = random.uniform(0, 90)
current_angle = torch.tensor(random.uniform(0,90),requires_grad=True)

lr = 0.1
optimizer = torch.optim.SGD([current_angle], lr=lr)

for epoch in range(30):
loss = (current_angle - best_angle) ** 2
loss.backward()
optimizer.step()
optimizer.zero_grad()

print(f"Epoch {epoch + 1}: Current Angle = {current_angle.item():.2f}, Loss = {loss.item():.2f}")

# 输出最优角度和最终角度
print(f"Optimal Angle: {best_angle:.2f}")
print(f"Final Angle: {current_angle.item():.2f}")

假设存在20块太阳能板同时寻找最佳太阳直射角度

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
import random
import torch
import matplotlib.pyplot as plt
num_panels = 20

best_angle = random.uniform(0, 90)
best_angles = [best_angle] * num_panels
current_angles = torch.tensor([random.uniform(0, 90) for _ in range(num_panels)], requires_grad=True)
print(current_angles)
lr = 0.1
optimizer = torch.optim.SGD([current_angles], lr=lr)

loss_history = []
angle_history = []

for epoch in range(40):
loss = sum((current_angles[i] - best_angles[i]) ** 2 for i in range(num_panels))
loss.backward()
optimizer.step()
optimizer.zero_grad()

loss_history.append(loss.item())
angle_history.append(current_angles.detach().numpy().copy())

if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}:")
for i in range(num_panels):
print(f" Panel {i+1}: Current Angle = {current_angles[i].item():.2f}, best Angle = {best_angles[i]:.2f}")
print(f" Total Loss = {loss.item():.2f}\n")

print("Final Angles:")
for i in range(num_panels):
print(f" Panel {i+1}: Final Angle = {current_angles[i].item():.2f}, best Angle = {best_angles[i]:.2f}")


plt.figure(figsize=(10, 5))
plt.plot(loss_history, label="Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Loss vs. Epoch")
plt.legend()
plt.grid()
plt.show()


plt.figure(figsize=(10, 5))
for i in range(num_panels):
plt.plot([angle_history[epoch][i] for epoch in range(len(angle_history))], label=f"Panel {i+1}")
plt.axhline(y=best_angle, color="r", linestyle="--", label="Optimal Angle")
plt.xlabel("Epoch")
plt.ylabel("Angle")
plt.title("Solar Panel Angles vs. Epoch")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.grid()
plt.tight_layout()
plt.show()