main.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # time: 2023/3/2 10:28
  4. # file: config.py
  5. # author: David
  6. # company: shenyang JY
  7. """
  8. 模型调参及系统功能配置
  9. """
  10. import concurrent.futures
  11. import types
  12. from pyexpat import features
  13. from tensorflow import add_n
  14. from tqdm import tqdm
  15. import pandas as pd
  16. from pathlib import Path
  17. from copy import deepcopy
  18. from concurrent.futures import ProcessPoolExecutor
  19. from app.common.config import parser, logger
  20. from app.model.resource_manager import ResourceController
  21. from app.model.task_worker import Task
  22. from app.model.material import MaterialLoader
  23. from multiprocessing import Manager, Lock
  24. """"
  25. 调用思路
  26. xxxx 1. 从入口参数中获取IN OUT文件位置 xxxx
  27. 2. 按照训练和预测加载和解析数据
  28. 3. 对数据进行预处理
  29. 4. 执行训练,保存模型,输出状态
  30. 5. 执行预测,输出结果,输出状态
  31. """
  32. """
  33. 训练任务
  34. 1.将一个省份下的所有场站加入队列
  35. 2.队列中的每个场站是一个子任务,还有最终的区域级子任务
  36. """
  37. def add_nwp(df_obj, df):
  38. if df_obj.empty:
  39. df_obj = df
  40. else:
  41. add_cols = [col for col in df_obj.columns if col not in ['PlantID', 'PlantName', 'PlantType', 'Qbsj', 'Datetime']]
  42. df_obj[add_cols] = df_obj[add_cols].add(df, fill_value=0)
  43. return df_obj
  44. def main():
  45. # ---------------------------- 解析参数 ----------------------------
  46. # 解析参数,将固定参数和任务参数合并
  47. opt = parser.parse_args_and_yaml()
  48. config = opt.__dict__
  49. # 打印参数
  50. logger.info(f"输入文件目录: {opt.input_file}")
  51. # ---------------------------- 配置计算资源和任务 ----------------------------
  52. # 初始化资源管理器
  53. rc = ResourceController(
  54. max_workers=opt.system['max_workers'],
  55. gpu_list=opt.system['gpu_devices']
  56. )
  57. # 生成任务列表
  58. all_stations = [str(child.parts[-1]) for child in Path(opt.input_file).iterdir() if child.is_dir()]
  59. loader = MaterialLoader(opt.input_file)
  60. task = Task(loader)
  61. # ---------------------------- 监控任务,进度跟踪 ----------------------------
  62. # 场站级功率预测训练
  63. completed = 0
  64. with tqdm(total=len(all_stations)) as pbar:
  65. with ProcessPoolExecutor(max_workers=rc.cpu_cores) as executor:
  66. futures = []
  67. for sid in all_stations:
  68. # 动态分配GPU
  69. task_config = deepcopy(config)
  70. gpu_id = rc.get_gpu()
  71. task_config['gpu_assignment'] = gpu_id
  72. task_config['station_id'] = sid
  73. # 提交任务
  74. future = executor.submit(task.station_task, task_config)
  75. future.add_done_callback(
  76. lambda _: rc.release_gpu(task_config['gpu_assignment']))
  77. futures.append(future)
  78. total_cap = 0
  79. weighted_nwp = pd.DataFrame()
  80. weighted_nwp_h = pd.DataFrame()
  81. weighted_nwp_v = pd.DataFrame()
  82. weighted_nwp_v_h = pd.DataFrame()
  83. # 处理完成情况
  84. for future in concurrent.futures.as_completed(futures):
  85. try:
  86. result = future.result()
  87. if result['status'] == 'success':
  88. # 分治-汇总策略得到加权后的nwp
  89. completed += 1
  90. local = result['weights']
  91. total_cap += local['cap']
  92. weighted_nwp = add_nwp(weighted_nwp, local['nwp'])
  93. weighted_nwp_h = add_nwp(weighted_nwp_h, local['nwp_h'])
  94. weighted_nwp_v = add_nwp(weighted_nwp_v, local['nwp_v'])
  95. weighted_nwp_v_h = add_nwp(weighted_nwp_v_h, local['nwp_v_h'])
  96. pbar.update(1)
  97. pbar.set_postfix_str(f"Completed: {completed}/{len(all_stations)}")
  98. except Exception as e:
  99. print(f"Task failed: {e}")
  100. # 归一化处理
  101. use_cols = [col for col in weighted_nwp.columns if col not in ['PlantID', 'PlantName', 'PlantType', 'Qbsj', 'Datetime']]
  102. use_cols_v = [col for col in weighted_nwp_v.columns if col not in ['PlantID', 'PlantName', 'PlantType', 'Qbsj', 'Datetime']]
  103. weighted_nwp[use_cols] /= total_cap
  104. weighted_nwp_h[use_cols] /= total_cap
  105. weighted_nwp_v[use_cols_v] /= total_cap
  106. weighted_nwp_v_h[use_cols_v] /= total_cap
  107. data_nwps = types.SimpleNamespace(**{'nwp': weighted_nwp, 'nwp_h': weighted_nwp_h, 'nwp_v': weighted_nwp_v, 'nwp_v_h': weighted_nwp_v_h})
  108. print(f"Final result: {completed} stations trained successfully")
  109. # 区域级功率预测训练
  110. task_config = deepcopy(config)
  111. gpu_id = rc.get_gpu()
  112. task_config['gpu_assignment'] = gpu_id
  113. task.region_task(task_config, data_nwps)
  114. if __name__ == "__main__":
  115. main()