-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
438 lines (373 loc) · 16 KB
/
run.py
File metadata and controls
438 lines (373 loc) · 16 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import sys
import os
from pathlib import Path
from typing import Optional, Dict, Any
import yaml
import subprocess
import platform
import requests
import time
class AITool:
def __init__(self, config_path: Optional[str] = None):
self.config = self._load_config(config_path)
self.initialized = False
self.offline_mode = False
def _load_config(self, config_path: Optional[str] = None) -> Dict[Any, Any]:
"""加载配置文件"""
if config_path is None:
config_path = Path(__file__).parent / "config" / "config.yaml"
try:
with open(config_path, 'r', encoding='utf-8') as f:
return yaml.safe_load(f)
except Exception as e:
print(f"加载配置文件失败: {str(e)}")
return {}
def _fix_ssl_issues(self) -> bool:
"""尝试修复SSL问题"""
try:
# 检查是否是Anaconda环境
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))
if is_conda:
print("检测到Anaconda环境,尝试修复SSL...")
commands = [
"conda install -y ca-certificates",
"conda install -y certifi",
"conda install -y openssl",
"conda install -y pyopenssl",
"conda update -y --all"
]
for cmd in commands:
print(f"执行: {cmd}")
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"命令执行失败: {result.stderr}")
return False
print(result.stdout)
# 更新环境变量
if platform.system() == 'Windows':
ssl_path = os.path.join(sys.prefix, 'Library', 'ssl')
if os.path.exists(ssl_path):
os.environ['SSL_CERT_DIR'] = ssl_path
os.environ['SSL_CERT_FILE'] = os.path.join(ssl_path, 'cert.pem')
print(f"已设置SSL证书路径: {ssl_path}")
return True
else:
print("非Anaconda环境,尝试使用pip安装...")
commands = [
"pip install --upgrade pip",
"pip install --upgrade certifi",
"pip install pyopenssl",
"pip install cryptography"
]
for cmd in commands:
print(f"执行: {cmd}")
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"命令执行失败: {result.stderr}")
return False
print(result.stdout)
return True
except Exception as e:
print(f"修复SSL时出错: {str(e)}")
return False
def check_environment(self) -> bool:
"""检查运行环境"""
print("=== 系统环境检查 ===")
print(f"Python版本: {sys.version}")
print(f"Python路径: {sys.executable}")
print(f"当前目录: {os.getcwd()}")
print(f"系统平台: {platform.system()}")
print("==================\n")
# 检查SSL
try:
import ssl
print("SSL模块已安装")
except ImportError:
print("SSL模块导入失败,尝试修复...")
if not self._fix_ssl_issues():
print("SSL修复失败,请尝试以下手动步骤:")
print("1. 完全卸载Python/Anaconda")
print("2. 重新安装最新版本的Anaconda")
print("3. 在安装时选择'Add Anaconda to PATH'选项")
return False
try:
import ssl
print("SSL修复成功!")
except ImportError:
print("SSL仍然无法导入,需要手动修复")
return False
# 检查其他依赖包
required_packages = ['requests', 'yaml']
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print("缺少以下依赖包:")
for pkg in missing_packages:
print(f"- {pkg}")
print("\n正在安装缺失的依赖...")
for pkg in missing_packages:
try:
subprocess.run(f"pip install {pkg}", shell=True, check=True)
print(f"已安装 {pkg}")
except subprocess.CalledProcessError:
print(f"安装 {pkg} 失败")
return False
return True
def _test_internet_connection(self) -> bool:
"""测试网络连接"""
urls = [
"https://www.baidu.com",
"https://www.google.com"
]
for url in urls:
try:
print(f"正在测试连接 {url}...")
response = requests.get(url, timeout=15)
if response.status_code == 200:
print(f"成功连接到 {url}")
return True
except Exception as e:
print(f"连接 {url} 失败: {str(e)}")
return False
def initialize(self) -> bool:
"""初始化AI工具"""
try:
# 首先检查代理配置
if 'proxy' in self.config:
proxy_config = self.config['proxy']
os.environ['HTTP_PROXY'] = proxy_config.get('http', '')
os.environ['HTTPS_PROXY'] = proxy_config.get('https', '')
# 测试网络连接
if not self._test_internet_connection():
print("网络连接失败,请检查网络设置")
return False
print("AI工具初始化成功")
self.initialized = True
return True
except Exception as e:
print(f"\n初始化失败:")
print(f"错误类型: {type(e).__name__}")
print(f"错误信息: {str(e)}")
return False
def demo_solar_calculation(self) -> None:
"""演示太阳能计算功能"""
try:
# 在 demo_solar_calculation 方法中修改导入语句
from src.solar import (
BuildingData,
EnvironmentalData,
SolarSystemData,
SolarPerformanceCalculator,
SolarSystemOptimizer
)
print("\n=== 太阳能系统计算演示 ===")
# 创建测试数据
building = BuildingData(
roof_area=100,
roof_angle=30,
orientation=180,
shading_objects=[],
roof_material="concrete",
load_capacity=200
)
environment = EnvironmentalData(
solar_radiation=1000,
temperature=25,
weather_pattern={},
dust_factor=0.05,
altitude=100,
latitude=31.2
)
# 创建系统数据
solar_data = SolarSystemData(building, environment)
# 计算原始系统输出
calculator = SolarPerformanceCalculator()
original_output = calculator.calculate_system_output(solar_data)
print(f"\n1. 原始系统输出: {original_output:.2f} kWh/天")
# 系统优化
optimizer = SolarSystemOptimizer()
optimized_data = optimizer.optimize(solar_data)
optimized_output = calculator.calculate_system_output(optimized_data)
# 获取优化报告
optimization_report = optimizer.get_optimization_report(solar_data, optimized_data)
print(f"\n2. 优化后系统输出: {optimized_output:.2f} kWh/天")
print(f"3. 性能提升: {optimization_report['improvements']['radiation_increase']:.1f}%")
# 显示详细优化建议
print("\n4. 优化建议:")
print(f" - 建议的太阳能板倾角: {optimization_report['optimized']['tilt']:.1f}°")
print(f" - 建议的朝向角度: {optimization_report['optimized']['orientation']:.1f}°")
print(f" - 预计每日增加发电量: {optimized_output - original_output:.2f} kWh")
except Exception as e:
print(f"\n演示运行失败:")
print(f"错误类型: {type(e).__name__}")
print(f"错误信息: {str(e)}")
import traceback
print(f"错误追踪:\n{traceback.format_exc()}")
def configure_system_parameters(self):
"""系统参数配置功能"""
print("\n=== 系统参数配置 ===")
try:
while True:
print("\n当前可配置的参数:")
print("1. 建筑参数")
print("2. 环境参数")
print("3. 系统效率参数")
print("4. 返回上级菜单")
choice = input("\n请选择要配置的参数类型 (1-4): ").strip()
if choice == "1":
self._configure_building_parameters()
elif choice == "2":
self._configure_environmental_parameters()
elif choice == "3":
self._configure_efficiency_parameters()
elif choice == "4":
print("返回上级菜单...")
break
else:
print("无效的选择,请重试")
except Exception as e:
print(f"参数配置出错: {str(e)}")
def _configure_building_parameters(self):
"""配置建筑参数"""
print("\n=== 建筑参数配置 ===")
try:
print("当前可配置的建筑参数:")
print("1. 屋顶面积 (平方米)")
print("2. 屋顶倾角 (度)")
print("3. 朝向角度 (度,180为正南)")
print("4. 屋顶材料")
print("5. 载荷能力 (kg/m²)")
choice = input("\n请选择要配置的参数 (1-5): ").strip()
if choice == "1":
value = float(input("请输入新的屋顶面积 (平方米): "))
print(f"已设置屋顶面积为: {value} 平方米")
elif choice == "2":
value = float(input("请输入新的屋顶倾角 (0-90度): "))
if 0 <= value <= 90:
print(f"已设置屋顶倾角为: {value} 度")
else:
print("倾角必须在0-90度之间")
elif choice == "3":
value = float(input("请输入新的朝向角度 (0-360度): "))
if 0 <= value <= 360:
print(f"已设置朝向角度为: {value} 度")
else:
print("朝向角度必须在0-360度之间")
elif choice == "4":
material = input("请输入新的屋顶材料: ")
print(f"已设置屋顶材料为: {material}")
elif choice == "5":
value = float(input("请输入新的载荷能力 (kg/m²): "))
print(f"已设置载荷能力为: {value} kg/m²")
else:
print("无效的选择")
except ValueError:
print("输入格式错误,请输入数字")
except Exception as e:
print(f"配置建筑参数时出错: {str(e)}")
def _configure_environmental_parameters(self):
"""配置环境参数"""
print("\n=== 环境参数配置 ===")
try:
print("当前可配置的环境参数:")
print("1. 太阳辐射强度 (W/m²)")
print("2. 环境温度 (°C)")
print("3. 灰尘因子 (0-1)")
print("4. 海拔高度 (米)")
print("5. 地理纬度 (度)")
choice = input("\n请选择要配置的参数 (1-5): ").strip()
if choice == "1":
value = float(input("请输入新的太阳辐射强度 (W/m²): "))
print(f"已设置太阳辐射强度为: {value} W/m²")
elif choice == "2":
value = float(input("请输入新的环境温度 (°C): "))
print(f"已设置环境温度为: {value} °C")
elif choice == "3":
value = float(input("请输入新的灰尘因子 (0-1): "))
if 0 <= value <= 1:
print(f"已设置灰尘因子为: {value}")
else:
print("灰尘因子必须在0-1之间")
elif choice == "4":
value = float(input("请输入新的海拔高度 (米): "))
print(f"已设置海拔高度为: {value} 米")
elif choice == "5":
value = float(input("请输入新的地理纬度 (-90到90度): "))
if -90 <= value <= 90:
print(f"已设置地理纬度为: {value} 度")
else:
print("纬度必须在-90到90度之间")
else:
print("无效的选择")
except ValueError:
print("输入格式错误,请输入数字")
except Exception as e:
print(f"配置环境参数时出错: {str(e)}")
def _configure_efficiency_parameters(self):
"""配置系统效率参数"""
print("\n=== 系统效率参数配置 ===")
try:
print("当前可配置的效率参数:")
print("1. 太阳能板效率 (0-1)")
print("2. 温度系数 (%/°C)")
print("3. 系统损耗 (0-1)")
choice = input("\n请选择要配置的参数 (1-3): ").strip()
if choice == "1":
value = float(input("请输入新的太阳能板效率 (0-1): "))
if 0 <= value <= 1:
print(f"已设置太阳能板效率为: {value}")
else:
print("效率必须在0-1之间")
elif choice == "2":
value = float(input("请输入新的温度系数 (%/°C): "))
print(f"已设置温度系数为: {value} %/°C")
elif choice == "3":
value = float(input("请输入新的系统损耗 (0-1): "))
if 0 <= value <= 1:
print(f"已设置系统损耗为: {value}")
else:
print("系统损耗必须在0-1之间")
else:
print("无效的选择")
except ValueError:
print("输入格式错误,请输入数字")
except Exception as e:
print(f"配置效率参数时出错: {str(e)}")
def run_interactive_demo(self):
"""运行交互式演示"""
while True:
print("\n=== 请选择功能: ===")
print("1. 系统参数配置")
print("2. 太阳能系统计算演示")
print("3. 退出")
try:
choice = input("\n请选择功能 (1-3): ").strip()
if choice == "1":
self.configure_system_parameters()
elif choice == "2":
self.demo_solar_calculation()
elif choice == "3":
print("演示结束,谢谢使用!")
break
else:
print("无效的选择,请重试")
except Exception as e:
print(f"操作出错: {str(e)}")
continue
def main():
# 创建AI工具实例
tool = AITool()
# 检查环境
if not tool.check_environment():
sys.exit(1)
# 初始化AI工具
if not tool.initialize():
sys.exit(1)
# 运行交互式演示
tool.run_interactive_demo()
if __name__ == "__main__":
main()