error.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. current_path = os.path.dirname(__file__)
  14. def readVar(path):
  15. if os.path.exists(path):
  16. with open(path, "rb") as file:
  17. var = pickle.load(file)
  18. return var
  19. else:
  20. return None
  21. class dqFix(object):
  22. # 将误差存储为静态变量
  23. def __init__(self, log, args):
  24. self.logger = log
  25. self.args = args
  26. self.opt = self.args.parse_args_and_yaml()
  27. def history_error(self, history_dq, history_rp, dq):
  28. his = self.opt.history_hours * 5
  29. errors = pd.merge(history_dq, history_rp, on='C_TIME')
  30. errors = errors.tail(his)
  31. if len(errors) > 0:
  32. errors = errors.apply(pd.to_numeric, errors='ignore')
  33. error = errors['C_REAL_VALUE'].values - errors['C_FP_VALUE'].values
  34. error = round(np.mean(error), 3)
  35. else:
  36. error = 0
  37. print("---error&errors---:", error, errors)
  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. sun_up_time = datetime.datetime.strptime(self.opt.first_point['sun_up_time'], '%Y-%m-%d %H:%M:%S')
  63. for i, fh in fhs.iterrows():
  64. if i+1 > 16:
  65. T = 'T16'
  66. else:
  67. T = 'T' + str(i+1)
  68. coe_m = float(self.opt.coe[T]['m'])
  69. coe_n = float(self.opt.coe[T]['n'])
  70. dt = fh['C_TIME']
  71. dq = fh['C_FP_VALUE']
  72. dq_fix = fh['dq_fix']
  73. his_fix = fh['his_fix']
  74. new_dq = round(coe_n * his_fix + coe_m * dq_fix, 2) # 修改曲线为0问题
  75. for i, cal in enumerate(self.opt.spot_trading):
  76. if 'T' + str(cal['point']) == T:
  77. new_dq = round(new_dq * cal['coe'] + cal['abs'], 2)
  78. self.logger.info("现货交易:第{}个点,进行了乘系数加绝对值修改".format(cal['point']))
  79. for i, cal in enumerate(self.opt.calculate):
  80. interval = list(range(cal['extraMinRange'], cal['extraMaxRange'] + 1))
  81. if dt.hour in interval:
  82. new_dq = round(new_dq * cal['coe'] + cal['abs'], 2)
  83. self.logger.info("第{}组,时段为:{}-{}点,时刻:{},进行了乘系数加绝对值修改".format(i + 1, cal['extraMinRange'],
  84. cal['extraMaxRange'], dt.strftime('%Y-%m-%d %H:%M:%S')))
  85. new_dq = new_dq if dq > 0 else 0
  86. new_dq = new_dq if new_dq > 0 else 0
  87. new_dq = self.opt.cap if new_dq > self.opt.cap else new_dq
  88. if T == 'T1' and self.opt.first_point['switch'] is True:
  89. # 华东特殊规则,第一个点用实际功率替换,日出用昨日日出点替换(系统判断是否限电能接尽接)
  90. if dt.time() != sun_up_time.time() or new_dq > 0:
  91. rpt = requestHandler.history_rp.tail(1)
  92. new_dq = rpt['C_ABLE_VALUE'].iloc[0] if rpt['LIMIT_STATUS'].iloc[0] == 1 else rpt['C_REAL_VALUE'].iloc[0]
  93. else:
  94. new_dq = self.opt.first_point['sun_up_value']
  95. cdq.append({"C_TIME": dt.strftime('%Y-%m-%d %H:%M:%S'), "CDQ_VALUE": new_dq})
  96. return cdq
  97. if __name__ == "__main__":
  98. import argparse
  99. # argparse方便于命令行下输入参数,可以根据需要增加更多
  100. parser = argparse.ArgumentParser()
  101. # parser.add_argument("-t", "--do_train", default=False, type=bool, help="whether to train")
  102. # parser.add_argument("-p", "--do_predict", default=True, type=bool, help="whether to train")
  103. # parser.add_argument("-b", "--batch_size", default=64, type=int, help="batch size")
  104. # parser.add_argument("-e", "--epoch", default=20, type=int, help="epochs num")
  105. args = parser.parse_args()
  106. #
  107. # for key in dir(args): # dir(args) 函数获得args所有的属性
  108. # if not key.startswith("_"): # 去掉 args 自带属性,比如__name__等
  109. # setattr(con, key, getattr(args, key)) # 将属性值赋给Config
  110. #
  111. # # main(con)