error.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # time: 2023/3/13 9:24
  4. # file: dbUtils.py
  5. # author: David
  6. # company: shenyang JY
  7. import os
  8. import pandas as pd
  9. import numpy as np
  10. import datetime
  11. import pickle
  12. from request import requestHandler
  13. import time
  14. current_path = os.path.dirname(__file__)
  15. def readVar(path):
  16. if os.path.exists(path):
  17. with open(path, "rb") as file:
  18. var = pickle.load(file)
  19. return var
  20. else:
  21. return None
  22. class dqFix(object):
  23. # 将误差存储为静态变量
  24. def __init__(self, log, args):
  25. self.logger = log
  26. self.args = args
  27. self.opt = self.args.parse_args_and_yaml()
  28. def history_error(self, history_dq, history_rp, dq):
  29. his = self.opt.history_hours * 5
  30. errors = pd.merge(history_dq, history_rp, on='C_TIME')
  31. errors = errors.tail(his)
  32. if len(errors) > 0:
  33. errors = errors.apply(pd.to_numeric, errors='ignore')
  34. error = errors['C_REAL_VALUE'].values - errors['C_FP_VALUE'].values
  35. error = round(np.mean(error), 3)
  36. else:
  37. error = 0
  38. dq['his_fix'] = error + dq['C_FP_VALUE']
  39. dq.loc[dq['his_fix'] < 0, ['his_fix']] = 0
  40. dq.loc[dq['his_fix'] > self.opt.cap, ['his_fix']] = self.opt.cap
  41. dq['C_TIME'] = pd.to_datetime(dq['C_TIME'])
  42. return dq.loc[:, ['C_TIME', 'his_fix', 'C_FP_VALUE']]
  43. def history_error_clock(self, dq, rp, point):
  44. history_fixes = []
  45. for index, row in dq.iterrows():
  46. history_fix = row['C_FP_VALUE']
  47. time_end = row.iloc[0] - pd.Timedelta(hours=4) + point*pd.Timedelta(minutes=15)
  48. time_start = time_end - pd.Timedelta(hours=self.opt.history_hours)
  49. history = rp[(rp.C_TIME <= time_end) & (rp.C_TIME > time_start)].copy() # rp已过滤限电时段
  50. if self.opt.usable_power['api_able_power'] is True:
  51. history['error'] = history['C_ABLE_VALUE'] - history['C_FP_VALUE']
  52. else:
  53. history['error'] = history['C_REAL_VALUE'] - history['C_FP_VALUE']
  54. history_err = round(history.loc[:, 'error'].mean(), 3) if len(history) != 0 else 0
  55. history_fix += history_err
  56. history_fix = history_fix if history_fix > 0 else 0
  57. history_fix = self.opt.cap if history_fix > self.opt.cap else history_fix
  58. history_fixes.append(history_fix)
  59. return history_fixes
  60. def cdq(self, fhs):
  61. cdq = []
  62. for i, fh in fhs.iterrows():
  63. if i+1 > 16:
  64. T = 'T16'
  65. else:
  66. T = 'T' + str(i+1)
  67. coe_m = float(self.opt.coe[T]['m'])
  68. coe_n = float(self.opt.coe[T]['n'])
  69. dt = fh['C_TIME']
  70. dq = fh['C_FP_VALUE']
  71. dq_fix = fh['dq_fix']
  72. his_fix = fh['his_fix']
  73. new_dq = round(coe_n * his_fix + coe_m * dq_fix, 2) # 修改曲线为0问题
  74. for i, cal in enumerate(self.opt.spot_trading):
  75. if 'T' + str(cal['point']) == T:
  76. new_dq = round(new_dq * cal['coe'] + cal['abs'], 2)
  77. self.logger.info("现货交易:第{}个点,进行了乘系数加绝对值修改".format(cal['point']))
  78. for i, cal in enumerate(self.opt.calculate):
  79. interval = list(range(cal['extraMinRange'], cal['extraMaxRange'] + 1))
  80. if dt.hour in interval:
  81. new_dq = round(new_dq * cal['coe'] + cal['abs'], 2)
  82. self.logger.info("第{}组,时段为:{}-{}点,时刻:{},进行了乘系数加绝对值修改".format(i + 1, cal['extraMinRange'],
  83. cal['extraMaxRange'], dt.strftime('%Y-%m-%d %H:%M:%S')))
  84. opt_limit = round(self.opt.cap*0.1, 2)
  85. new_dq = new_dq if new_dq > 0 else 0
  86. new_dq = self.opt.cap if new_dq > self.opt.cap else new_dq
  87. new_dq = opt_limit - 0.2 if new_dq < opt_limit else new_dq
  88. if T == 'T1' and self.opt.first_point['switch'] is True:
  89. # 华东特殊规则,第一个点用实际功率替换
  90. rpt = requestHandler.history_rp.tail(1)
  91. new_dq = rpt['C_ABLE_VALUE'].iloc[0] if rpt['LIMIT_STATUS'].iloc[0] == 1 else rpt['C_REAL_VALUE'].iloc[0]
  92. cdq.append({"C_TIME": dt.strftime('%Y-%m-%d %H:%M:%S'), "CDQ_VALUE": new_dq})
  93. return cdq
  94. if __name__ == "__main__":
  95. import argparse
  96. # argparse方便于命令行下输入参数,可以根据需要增加更多
  97. parser = argparse.ArgumentParser()
  98. # parser.add_argument("-t", "--do_train", default=False, type=bool, help="whether to train")
  99. # parser.add_argument("-p", "--do_predict", default=True, type=bool, help="whether to train")
  100. # parser.add_argument("-b", "--batch_size", default=64, type=int, help="batch size")
  101. # parser.add_argument("-e", "--epoch", default=20, type=int, help="epochs num")
  102. args = parser.parse_args()
  103. #
  104. # for key in dir(args): # dir(args) 函数获得args所有的属性
  105. # if not key.startswith("_"): # 去掉 args 自带属性,比如__name__等
  106. # setattr(con, key, getattr(args, key)) # 将属性值赋给Config
  107. #
  108. # # main(con)