-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualize_individual_scenarios_v04.py
More file actions
253 lines (204 loc) · 9.45 KB
/
Copy pathvisualize_individual_scenarios_v04.py
File metadata and controls
253 lines (204 loc) · 9.45 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
Individual Scenario Visualization for MVP v0.4.3
3つのシナリオの詳細可視化スクリプト
"""
import json
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
import pandas as pd
import seaborn as sns
# 日本語フォント設定(Windows対応 - 警告完全抑制)
import matplotlib
import warnings
import logging
# 全ての警告を抑制
warnings.filterwarnings('ignore')
# matplotlib のログレベルを ERROR に設定
matplotlib.set_loglevel('ERROR')
logging.getLogger('matplotlib').setLevel(logging.ERROR)
logging.getLogger('matplotlib.font_manager').setLevel(logging.ERROR)
# Windows確実対応フォント設定(存在確認不要な汎用設定)
matplotlib.rcParams['font.family'] = ['DejaVu Sans', 'Arial', 'sans-serif']
matplotlib.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.family'] = ['DejaVu Sans', 'Arial', 'sans-serif']
plt.rcParams['axes.unicode_minus'] = False
def visualize_scenario(scenario_name, output_dir, color='#2E86C1'):
"""個別シナリオの詳細可視化"""
# データ読み込み
history_file = Path(output_dir) / 'training_history.json'
if not history_file.exists():
print(f"❌ {scenario_name}: データファイルが見つかりません - {history_file}")
return False
with open(history_file, 'r') as f:
data = json.load(f)
episode_rewards = data.get('episode_rewards', [])
episode_costs = data.get('episode_costs', [])
cost_variances = data.get('episode_cost_variances', [])
if not episode_rewards:
print(f"❌ {scenario_name}: エピソード報酬データがありません")
return False
print(f"✅ {scenario_name}: {len(episode_rewards)}エピソードの可視化を開始")
# 2x2のサブプロット作成
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle(f'{scenario_name} Scenario - Detailed Analysis (1000 Episodes)',
fontsize=16, fontweight='bold')
episodes = range(1, len(episode_rewards) + 1)
# 1. 学習曲線(移動平均付き)
ax1.set_title('Learning Curve with Moving Average', fontsize=12, fontweight='bold')
ax1.plot(episodes, episode_rewards, alpha=0.3, color=color, label='Raw Rewards')
# 移動平均(50エピソード)
if len(episode_rewards) >= 50:
window = 50
moving_avg = np.convolve(episode_rewards, np.ones(window)/window, mode='valid')
moving_episodes = range(window, len(episode_rewards) + 1)
ax1.plot(moving_episodes, moving_avg, color=color, linewidth=2, label='Moving Average (50ep)')
ax1.set_xlabel('Episode')
ax1.set_ylabel('Reward')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 2. 収束性分析(最後200エピソード)
ax2.set_title('Convergence Analysis (Last 200 Episodes)', fontsize=12, fontweight='bold')
if len(episode_rewards) >= 200:
final_rewards = episode_rewards[-200:]
final_episodes = range(len(episode_rewards)-199, len(episode_rewards)+1)
ax2.plot(final_episodes, final_rewards, color=color, alpha=0.7)
# 統計情報
mean_final = np.mean(final_rewards)
std_final = np.std(final_rewards)
ax2.axhline(y=mean_final, color='red', linestyle='--', alpha=0.8,
label=f'Mean: {mean_final:.1f}')
ax2.axhline(y=mean_final + std_final, color='orange', linestyle=':', alpha=0.6,
label=f'Mean ± Std: {std_final:.1f}')
ax2.axhline(y=mean_final - std_final, color='orange', linestyle=':', alpha=0.6)
ax2.set_xlabel('Episode')
ax2.set_ylabel('Reward')
ax2.legend()
ax2.grid(True, alpha=0.3)
else:
ax2.text(0.5, 0.5, 'Insufficient data\\n(< 200 episodes)',
ha='center', va='center', transform=ax2.transAxes)
# 3. Reward VaR (Value at Risk) 分析
ax3.set_title('Reward VaR (Value at Risk)', fontsize=12, fontweight='bold')
# VaR計算(5%, 10%, 25%パーセンタイル)
if len(episode_rewards) >= 20: # 十分なデータがある場合
# 移動窓でVaRを計算
window_size = min(100, len(episode_rewards) // 4)
var_5_percent = []
var_10_percent = []
var_25_percent = []
var_episodes = []
for i in range(window_size, len(episode_rewards) + 1):
window_rewards = episode_rewards[i-window_size:i]
var_5_percent.append(np.percentile(window_rewards, 5))
var_10_percent.append(np.percentile(window_rewards, 10))
var_25_percent.append(np.percentile(window_rewards, 25))
var_episodes.append(i)
# VaRプロット
ax3.plot(var_episodes, var_5_percent, color='red', linewidth=2, alpha=0.8, label='5% VaR')
ax3.plot(var_episodes, var_10_percent, color='orange', linewidth=2, alpha=0.8, label='10% VaR')
ax3.plot(var_episodes, var_25_percent, color='green', linewidth=2, alpha=0.8, label='25% VaR')
ax3.set_xlabel('Episode')
ax3.set_ylabel('VaR (Reward at Risk)')
ax3.legend()
ax3.grid(True, alpha=0.3)
# 最終VaR値
final_var_5 = var_5_percent[-1] if var_5_percent else 0
final_var_10 = var_10_percent[-1] if var_10_percent else 0
ax3.text(0.02, 0.98, f'Final 5% VaR: {final_var_5:.2f}\nFinal 10% VaR: {final_var_10:.2f}',
transform=ax3.transAxes, va='top',
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))
else:
ax3.text(0.5, 0.5, 'Insufficient data for VaR\n(< 20 episodes)',
ha='center', va='center', transform=ax3.transAxes)
# 4. 報酬分布分析
ax4.set_title('Reward Distribution Analysis', fontsize=12, fontweight='bold')
# ヒストグラム
ax4.hist(episode_rewards, bins=50, alpha=0.7, color=color, density=True)
# 統計情報
mean_reward = np.mean(episode_rewards)
median_reward = np.median(episode_rewards)
std_reward = np.std(episode_rewards)
ax4.axvline(x=mean_reward, color='red', linestyle='--',
label=f'Mean: {mean_reward:.1f}')
ax4.axvline(x=median_reward, color='orange', linestyle='-',
label=f'Median: {median_reward:.1f}')
ax4.set_xlabel('Reward')
ax4.set_ylabel('Density')
ax4.legend()
ax4.grid(True, alpha=0.3)
# 統計サマリーをテキストで表示(VaR情報を含む)
if len(episode_rewards) >= 20:
final_var_5 = np.percentile(episode_rewards[-100:] if len(episode_rewards) >= 100 else episode_rewards, 5)
final_var_10 = np.percentile(episode_rewards[-100:] if len(episode_rewards) >= 100 else episode_rewards, 10)
final_variance = cost_variances[-1] if cost_variances else 0
stats_text = f'''Statistics:
Episodes: {len(episode_rewards)}
Mean: {mean_reward:.2f}
Std: {std_reward:.2f}
Min: {min(episode_rewards):.2f}
Max: {max(episode_rewards):.2f}
5% VaR: {final_var_5:.2f}
10% VaR: {final_var_10:.2f}'''
else:
final_variance = cost_variances[-1] if cost_variances else 0
stats_text = f'''Statistics:
Episodes: {len(episode_rewards)}
Mean: {mean_reward:.2f}
Std: {std_reward:.2f}
Min: {min(episode_rewards):.2f}
Max: {max(episode_rewards):.2f}
VaR: Insufficient data'''
ax4.text(1.02, 1.0, stats_text, transform=ax4.transAxes,
va='top', ha='left', fontsize=9,
bbox=dict(boxstyle='round', facecolor='lightgray', alpha=0.8))
plt.tight_layout()
# 保存
save_path = Path(f'scenario_analysis_{scenario_name.lower().replace("-", "_")}_v043.png')
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f" 📊 グラフ保存: {save_path}")
# 表示
plt.show()
return True
def main():
"""メイン実行関数"""
print("=== 3シナリオ個別可視化分析 - MVP v0.4.3 ===")
print()
# 3つのシナリオ定義
scenarios = {
'Safety-First': {
'output_dir': 'outputs_hvac202_safety_first_enhanced',
'color': '#FF6B6B',
'description': '継続運転の安全を最優先とする保全戦略'
},
'Cost-Efficient': {
'output_dir': 'outputs_hvac202_cost_efficient_enhanced',
'color': '#4ECDC4',
'description': '予算節約を最優先とする保全戦略'
},
'Balanced': {
'output_dir': 'outputs_hvac202_balanced_enhanced',
'color': '#45B7D1',
'description': '安全とコストの最適バランスを目指す保全戦略'
}
}
success_count = 0
for scenario_name, config in scenarios.items():
print(f"🔍 {scenario_name} シナリオ分析中...")
print(f" 説明: {config['description']}")
success = visualize_scenario(
scenario_name=scenario_name,
output_dir=config['output_dir'],
color=config['color']
)
if success:
success_count += 1
print()
print(f"✅ 可視化完了: {success_count}/3 シナリオ")
print()
print("生成されたファイル:")
for scenario_name in scenarios.keys():
filename = f'scenario_analysis_{scenario_name.lower().replace("-", "_")}_v043.png'
print(f" 📊 {filename}")
if __name__ == "__main__":
main()