analysis_report.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. from flask import Flask, request
  4. import time
  5. import random
  6. import logging
  7. import traceback
  8. import os
  9. from common.database_dml import get_df_list_from_mongo, insert_data_into_mongo
  10. import plotly.express as px
  11. import plotly.graph_objects as go
  12. import pandas as pd
  13. import plotly.io as pio
  14. from bson.decimal128 import Decimal128
  15. import numbers
  16. from common.processing_data_common import str_to_list,generate_unique_colors
  17. from scipy.stats import gaussian_kde
  18. app = Flask('analysis_report——service')
  19. def put_analysis_report_to_html(args, df_clean, df_predict, df_accuracy):
  20. col_time = args['col_time']
  21. col_x_env = args['col_x_env']
  22. col_x_pre = str_to_list(args['col_x_pre'])
  23. label = args['label']
  24. label_pre = args['label_pre']
  25. farmId = args['farmId']
  26. df_clean = df_clean.applymap(
  27. lambda x: float(x.to_decimal()) if isinstance(x, Decimal128) else float(x) if isinstance(x,
  28. numbers.Number) else x).sort_values(
  29. by=col_time)
  30. df_predict = df_predict.applymap(
  31. lambda x: float(x.to_decimal()) if isinstance(x, Decimal128) else float(x) if isinstance(x,
  32. numbers.Number) else x).sort_values(
  33. by=col_time)
  34. df_accuracy = df_accuracy.applymap(
  35. lambda x: float(x.to_decimal()) if isinstance(x, Decimal128) else float(x) if isinstance(x,
  36. numbers.Number) else x).sort_values(
  37. by=col_time)
  38. total_size = df_clean.shape[0]
  39. clean_size = total_size
  40. if 'is_limit' in df_clean.columns:
  41. df_clean['is_limit'] = df_clean['is_limit'].apply(lambda x: '正常点' if x==0 else '异常点')
  42. clean_size = df_clean[df_clean['is_limit']=='正常点'].shape[0]
  43. df_overview = pd.DataFrame(
  44. {'场站编码':[farmId],
  45. '数据开始时间': [df_clean[col_time].min()], '数据结束时间': [df_clean[col_time].max()],
  46. '总天数':[(pd.to_datetime(df_clean[col_time].max())-pd.to_datetime(df_clean[col_time].min())).days],
  47. '数据总记录数': [total_size],'清洗后记录数':[clean_size],'数据可用率':[clean_size/total_size]})
  48. overview_html = df_overview.to_html(classes='table table-bordered table-striped', index=False)
  49. df_clean_after = df_clean[df_clean['is_limit']=='正常点']
  50. # -------------------- 数据描述 --------------------
  51. describe_html = df_clean.describe().reset_index().rename(columns={'index': '统计量'}).to_html(
  52. classes='table table-bordered table-striped fixed', index=False)
  53. # -------------------- 实测气象与实际功率散点图--------------------
  54. fig_scatter = px.scatter(df_clean, x=col_x_env, y=label, color='is_limit')
  55. # 自定义散点图布局
  56. fig_scatter.update_layout(
  57. template='seaborn', # 使用 seaborn 风格
  58. plot_bgcolor='rgba(255, 255, 255, 0.8)', # 背景色(淡白色)
  59. xaxis=dict(
  60. showgrid=True, # 显示网格
  61. gridcolor='rgba(200, 200, 200, 0.5)', # 网格线颜色(淡灰色)
  62. title=col_x_env, # x 轴标题
  63. title_font=dict(size=14), # x 轴标题字体大小
  64. tickfont=dict(size=12) # x 轴刻度标签字体大小
  65. ),
  66. yaxis=dict(
  67. showgrid=True, # 显示网格
  68. gridcolor='rgba(200, 200, 200, 0.5)', # 网格线颜色(淡灰色)
  69. title=label, # y 轴标题
  70. title_font=dict(size=14), # y 轴标题字体大小
  71. tickfont=dict(size=12) # y 轴刻度标签字体大小
  72. ),
  73. legend=dict(
  74. x=0.01, y=0.99, # 图例位置
  75. bgcolor='rgba(255, 255, 255, 0.7)', # 图例背景色
  76. bordercolor='black', # 图例边框颜色
  77. borderwidth=1, # 图例边框宽度
  78. font=dict(size=12) # 图例文字大小
  79. ),
  80. title=dict(
  81. text='实际功率与辐照度的散点图', # 图表标题
  82. x=0.5, # 标题居中
  83. font=dict(size=16) # 标题字体大小
  84. ),
  85. )
  86. # 将散点图保存为 HTML 片段
  87. scatter_html = pio.to_html(fig_scatter, full_html=False)
  88. # -------------------- 生成相关性热力图 --------------------
  89. # 计算相关矩阵
  90. correlation_matrix = df_clean_after.corr()
  91. # 生成热力图,带数值标签和新配色
  92. fig_heatmap = go.Figure(data=go.Heatmap(
  93. z=correlation_matrix.values,
  94. x=correlation_matrix.columns,
  95. y=correlation_matrix.columns,
  96. colorscale='RdBu', # 使用红蓝配色:正相关为蓝色,负相关为红色
  97. text=correlation_matrix.round(2).astype(str), # 将相关性值保留两位小数并转换为字符串
  98. texttemplate="%{text}", # 显示数值标签
  99. colorbar=dict(title='Correlation'),
  100. zmin=-1, zmax=1 # 设置颜色映射的范围
  101. ))
  102. # 自定义热力图布局
  103. fig_heatmap.update_layout(
  104. # title='Correlation Matrix Heatmap',
  105. xaxis=dict(tickangle=45),
  106. yaxis=dict(autorange='reversed'),
  107. template='seaborn'
  108. )
  109. # 将热力图保存为 HTML 片段
  110. corr_html = pio.to_html(fig_heatmap, full_html=False)
  111. # -------------------- 6.实测气象与预测气象趋势曲线 --------------------
  112. # # 生成折线图(以 C_GLOBALR 和 NWP预测总辐射 为例)实际功率
  113. # y_env = [label,col_x_env]+ col_x_pre
  114. # fig_line = px.line(df_clean, x=col_time, y=y_env, markers=True)
  115. # # fig_line = px.line(df_clean[(df_clean[col_time] >= df_predict[col_time].min()) & (
  116. # # df_clean[col_time] <= df_predict[col_time].max())], x=col_time, y=y_env, markers=True)
  117. # # 自定义趋势图布局
  118. # fig_line.update_layout(
  119. # template='seaborn',
  120. # # title=dict(text=f"{col_x_env}与{col_x_pre}趋势曲线",
  121. # # x=0.5, font=dict(size=24, color='darkblue')),
  122. # plot_bgcolor='rgba(255, 255, 255, 0.8)', # 改为白色背景
  123. # xaxis=dict(
  124. # showgrid=True,
  125. # gridcolor='rgba(200, 200, 200, 0.5)', # 网格线颜色
  126. # rangeslider=dict(visible=True), # 显示滚动条
  127. # rangeselector=dict(visible=True) # 显示预设的时间范围选择器
  128. # ),
  129. # yaxis=dict(showgrid=True, gridcolor='rgba(200, 200, 200, 0.5)'),
  130. # legend=dict(x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0.7)', bordercolor='black', borderwidth=1)
  131. # )
  132. #
  133. # # 将折线图保存为 HTML 片段
  134. # env_pre_html = pio.to_html(fig_line, full_html=False)
  135. # 创建折线图(label 单独一个纵轴, [col_x_env] + col_x_pre 一个纵轴)
  136. fig_line = px.line(df_clean, x=col_time, y=[label] + [col_x_env] + col_x_pre, markers=True)
  137. # 修改布局,添加双轴设置
  138. fig_line.update_layout(
  139. template='seaborn',
  140. plot_bgcolor='rgba(255, 255, 255, 0.8)', # 设置白色背景
  141. xaxis=dict(
  142. showgrid=True,
  143. gridcolor='rgba(200, 200, 200, 0.5)', # 网格线颜色
  144. rangeslider=dict(visible=True), # 显示滚动条
  145. rangeselector=dict(visible=True) # 显示预设的时间范围选择器
  146. ),
  147. yaxis=dict(
  148. title="实际功率", # 主纵轴用于 label
  149. showgrid=True,
  150. gridcolor='rgba(200, 200, 200, 0.5)'
  151. ),
  152. yaxis2=dict(
  153. title="环境数据", # 第二纵轴用于 [col_x_env] + col_x_pre
  154. overlaying='y', # 与主纵轴叠加
  155. side='right', # 放置在右侧
  156. showgrid=False # 不显示网格线
  157. ),
  158. legend=dict(
  159. x=0.01,
  160. y=0.99,
  161. bgcolor='rgba(255, 255, 255, 0.7)',
  162. bordercolor='black',
  163. borderwidth=1
  164. )
  165. )
  166. # 更新每个曲线的 y 轴对应性
  167. for i, col in enumerate([label] + [col_x_env] + col_x_pre):
  168. fig_line.data[i].update(yaxis='y' if col == label else 'y2')
  169. # 将折线图保存为 HTML 片段
  170. env_pre_html = pio.to_html(fig_line, full_html=False)
  171. # -------------------- 5.实测气象与预测气象偏差密度曲线 --------------------
  172. # 创建 Plotly 图形对象
  173. fig_density = go.Figure()
  174. colors = generate_unique_colors(len(col_x_pre))
  175. for col in zip(col_x_pre,colors):
  176. df_clean[f"{col[0]}_deviation"] = df_clean[col[0]] - df_clean[col_x_env]
  177. data = df_clean[f"{col[0]}_deviation"].dropna() # 确保没有 NaN 值
  178. kde = gaussian_kde(data)
  179. x_vals = np.linspace(data.min(), data.max(), 1000)
  180. y_vals = kde(x_vals)
  181. # 添加曲线
  182. fig_density.add_trace(go.Scatter(
  183. x=x_vals,
  184. y=y_vals,
  185. mode='lines',
  186. fill='tozeroy',
  187. line=dict(color=col[1]), # 循环使用颜色
  188. name=f'Density {col[0]}' # 图例名称
  189. ))
  190. # 生成预测与实测辐照度偏差的密度曲线图
  191. # 将密度曲线图保存为 HTML 片段
  192. density_html = pio.to_html(fig_density, full_html=False)
  193. # -------------------- 预测功率与实际功率曲线 --------------------
  194. # 生成折线图(以 C_GLOBALR 和 NWP预测总辐射 为例)
  195. # 创建一个图表对象
  196. fig = go.Figure()
  197. # 获取所有的模型
  198. models = df_predict['model'].unique()
  199. # 添加实际功率曲线
  200. fig.add_trace(go.Scatter(
  201. x=df_predict[col_time],
  202. y=df_predict[label],
  203. mode='lines+markers',
  204. name='实际功率', # 实际功率
  205. line=dict(dash='dot', width=2), # 虚线
  206. marker=dict(symbol='cross'),
  207. ))
  208. # 为每个模型添加预测值和实际功率的曲线
  209. for model in models:
  210. # 筛选该模型的数据
  211. model_data = df_predict[df_predict['model'] == model]
  212. # 添加预测值曲线
  213. fig.add_trace(go.Scatter(
  214. x=model_data[col_time],
  215. y=model_data[label_pre],
  216. mode='lines+markers',
  217. name=f'{model} 预测值', # 预测值
  218. marker=dict(symbol='circle'),
  219. line=dict(width=2)
  220. ))
  221. # 设置图表的标题和标签
  222. fig.update_layout(
  223. template='seaborn', # 使用 seaborn 模板
  224. title=dict(
  225. # text=f"{label_pre} 与 {label} 对比", # 标题
  226. x=0.5, font=dict(size=20, color='darkblue') # 标题居中并设置字体大小和颜色
  227. ),
  228. plot_bgcolor='rgba(255, 255, 255, 0.8)', # 背景色
  229. xaxis=dict(
  230. showgrid=True,
  231. gridcolor='rgba(200, 200, 200, 0.5)', # 网格线颜色
  232. title='时间', # 时间轴标题
  233. rangeslider=dict(visible=True), # 显示滚动条
  234. rangeselector=dict(visible=True) # 显示预设的时间范围选择器
  235. ),
  236. yaxis=dict(
  237. showgrid=True,
  238. gridcolor='rgba(200, 200, 200, 0.5)',
  239. title='功率' # y轴标题
  240. ),
  241. legend=dict(
  242. x=0.01,
  243. y=0.99,
  244. bgcolor='rgba(255, 255, 255, 0.7)', # 背景透明
  245. bordercolor='black',
  246. borderwidth=1,
  247. font=dict(size=12) # 字体大小
  248. ),
  249. hovermode='x unified', # 鼠标悬停时显示统一的提示框
  250. hoverlabel=dict(
  251. bgcolor='white',
  252. font_size=14,
  253. font_family="Rockwell", # 设置字体样式
  254. bordercolor='black'
  255. ),
  256. margin=dict(l=50, r=50, t=50, b=50) # 调整边距,避免标题或标签被遮挡
  257. )
  258. # 将折线图保存为 HTML 片段
  259. power_html = pio.to_html(fig, full_html=False)
  260. # -------------------- 准确率表展示--------------------
  261. acc_html = df_accuracy.sort_values(by=col_time).to_html(classes='table table-bordered table-striped', index=False)
  262. # -------------------- 准确率汇总展示--------------------
  263. # 指定需要转换的列
  264. cols_to_convert = ['MAE', 'accuracy', 'RMSE', 'deviationElectricity', 'deviationAssessment']
  265. for col in cols_to_convert:
  266. if col in df_accuracy.columns:
  267. df_accuracy[col] = df_accuracy[col].apply(
  268. lambda x: float(x.to_decimal()) if isinstance(x, Decimal128) else float(x) if isinstance(x,
  269. numbers.Number) else np.nan)
  270. # 确定存在的列
  271. agg_dict = {}
  272. rename_cols = ['model']
  273. if 'MAE' in df_accuracy.columns:
  274. agg_dict['MAE'] = np.nanmean
  275. rename_cols.append('MAE平均值')
  276. if 'accuracy' in df_accuracy.columns:
  277. agg_dict['accuracy'] = np.nanmean
  278. rename_cols.append('准确率平均值')
  279. if 'RMSE' in df_accuracy.columns:
  280. agg_dict['RMSE'] = np.nanmean
  281. rename_cols.append('RMSE平均值')
  282. if 'deviationElectricity' in df_accuracy.columns:
  283. agg_dict['deviationElectricity'] = [np.nanmean, np.nansum]
  284. rename_cols.append('考核电量平均值')
  285. rename_cols.append('考核总电量')
  286. if 'deviationAssessment' in df_accuracy.columns:
  287. agg_dict['deviationAssessment'] = [np.nanmean, np.nansum]
  288. rename_cols.append('考核分数平均值')
  289. rename_cols.append('考核总分数')
  290. # 进行分组聚合,如果有需要聚合的列
  291. summary_df = df_accuracy.groupby('model').agg(agg_dict).reset_index()
  292. summary_df.columns = rename_cols
  293. summary_html = summary_df.to_html(classes='table table-bordered table-striped', index=False)
  294. # -------------------- 生成完整 HTML 页面 --------------------
  295. html_content = f"""
  296. <!DOCTYPE html>
  297. <html lang="en">
  298. <head>
  299. <meta charset="UTF-8">
  300. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  301. <title>Data Analysis Report</title>
  302. <!-- 引入 Bootstrap CSS -->
  303. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  304. <style>
  305. justify-between;{{
  306. display: flex;
  307. justify-content: space-between;
  308. }}
  309. body {{
  310. background-color: #f4f4f9;
  311. font-family: Arial, sans-serif;
  312. padding: 20px;
  313. }}
  314. .container {{
  315. background-color: #fff;
  316. padding: 20px;
  317. border-radius: 10px;
  318. box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  319. margin-bottom: 30px;
  320. }}
  321. h1 {{
  322. text-align: center;
  323. color: #333;
  324. margin-bottom: 20px;
  325. }}
  326. .plot-container {{
  327. margin: 20px 0;
  328. max-height: 500px; /* 限制高度 */
  329. overflow-y: auto; /* 显示垂直滚动条 */
  330. }}
  331. .table-container {{
  332. margin-top: 30px;
  333. overflow-x: auto; /* 水平滚动条 */
  334. max-width: 100%; /* 限制宽度 */
  335. white-space: nowrap; /* 防止内容换行 */
  336. max-height: 500px; /* 限制高度 */
  337. overflow-y: auto; /* 显示垂直滚动条 */
  338. }}
  339. .fixed-table thead tr > th:first-child,
  340. .fixed-table tbody tr > td:first-child {{
  341. position: sticky;
  342. left: 0;
  343. z-index: 1;
  344. }}
  345. .fixed-table-header thead tr > th {{
  346. position: sticky;
  347. top: 0;
  348. z-index: 2;
  349. }}
  350. table {{
  351. width: 100%;
  352. font-size: 12px; /* 设置字体大小为12px */
  353. }}
  354. th, td {{
  355. text-align: center; /* 表头和单元格文字居中 */
  356. }}
  357. }}
  358. </style>
  359. </head>
  360. <body>
  361. <div class="container">
  362. <h1>分析报告</h1>
  363. <!-- Pandas DataFrame 表格 -->
  364. <div class="table-container">
  365. <h2>1. 数据总览</h2>
  366. {overview_html}
  367. </div>
  368. <!-- Pandas DataFrame 表格 -->
  369. <h2>2. 数据描述</h2>
  370. <div class="table-container fixed-table">
  371. {describe_html}
  372. </div>
  373. <div class="plot-container">
  374. <h2>3. 实测气象与实际功率散点图</h2>
  375. {scatter_html}
  376. </div>
  377. <div class="plot-container">
  378. <h2>4. 相关性分析</h2>
  379. {corr_html}
  380. </div>
  381. <div class="plot-container">
  382. <h2>5. 预测气象与实测气象偏差曲线</h2>
  383. {density_html}
  384. </div>
  385. <div class="plot-container">
  386. <h2>6. 实测气象与预测气象曲线趋势</h2>
  387. {env_pre_html}
  388. </div>
  389. <div class="plot-container">
  390. <h2>7. 预测功率与实际功率曲线对比</h2>
  391. {power_html}
  392. </div>
  393. <!-- Pandas DataFrame 表格 -->
  394. <div style="display:flex; justify-content: space-between;">
  395. <h2>8. 准确率对比</h2>
  396. <span>
  397. <a href="/formula.xlsx">公式</a>
  398. </span>
  399. </div>
  400. <div class="table-container fixed-table-header">
  401. {acc_html}
  402. </div>
  403. <!-- Pandas DataFrame 表格 -->
  404. <div class="table-container">
  405. <h2>9. 准确率汇总对比</h2>
  406. {summary_html}
  407. </div>
  408. </div>
  409. </body>
  410. </html>
  411. """
  412. filename = f"{farmId}_{int(time.time() * 1000)}_{random.randint(1000, 9999)}.html"
  413. # 保存为 HTML
  414. directory = '/usr/share/nginx/html'
  415. if not os.path.exists(directory):
  416. os.makedirs(directory)
  417. file_path = os.path.join(directory, filename)
  418. path = f"http://ds3:10010/{filename}"
  419. # 将 HTML 内容写入文件
  420. with open(file_path, "w", encoding="utf-8") as f:
  421. f.write(html_content)
  422. print("HTML report generated successfully!")
  423. return path
  424. @app.route('/analysis_report', methods=['POST'])
  425. def analysis_report():
  426. start_time = time.time()
  427. result = {}
  428. success = 0
  429. path = ""
  430. print("Program starts execution!")
  431. try:
  432. args = request.values.to_dict()
  433. print('args', args)
  434. logger.info(args)
  435. # 获取数据
  436. df_clean, df_predict, df_accuracy = get_df_list_from_mongo(args)[0], get_df_list_from_mongo(args)[1], \
  437. get_df_list_from_mongo(args)[2]
  438. path = put_analysis_report_to_html(args, df_clean, df_predict, df_accuracy)
  439. success = 1
  440. except Exception as e:
  441. my_exception = traceback.format_exc()
  442. my_exception.replace("\n", "\t")
  443. result['msg'] = my_exception
  444. end_time = time.time()
  445. result['success'] = success
  446. result['args'] = args
  447. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  448. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  449. result['file_path'] = path
  450. print("Program execution ends!")
  451. return result
  452. if __name__ == "__main__":
  453. print("Program starts execution!")
  454. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  455. logger = logging.getLogger("analysis_report log")
  456. from waitress import serve
  457. serve(app, host="0.0.0.0", port=10092)
  458. print("server start!")