Commit dd334441 authored by lcn's avatar lcn

修复Bug

parent d85b4ef3
...@@ -27,11 +27,11 @@ class AutoDic(dict): ...@@ -27,11 +27,11 @@ class AutoDic(dict):
class EnergyStoreOptimize(object): class EnergyStoreOptimize(object):
def __init__(self, inlid): def __init__(self, inlid):
self._inlid = inlid self._inlid = inlid
# self._r_cache = redis.Redis(host="172.18.1.253", db=1) # self._r_cache = redis.Redis(host="172.18.1.253", db=1)
async def calc_inline(self, ess_system): async def calc_inline(self, ess_system):
rlt = {'rlt_flag': True} rlt = {'rlt_flag': True}
inl_info = await self._get_inline_info() inl_info = await self._get_inline_info()
...@@ -47,27 +47,31 @@ class EnergyStoreOptimize(object): ...@@ -47,27 +47,31 @@ class EnergyStoreOptimize(object):
max_dt.int_timestamp) max_dt.int_timestamp)
time_str_d = PricePolicyHelper.quarter_chars_2_time_str( time_str_d = PricePolicyHelper.quarter_chars_2_time_str(
pp_info_d['quarters']) pp_info_d['quarters'])
# construct inline_var # construct inline_var
inline_var = {'inline_capacity': inl_info['tc_runtime'], inline_var = {'inline_capacity': inl_info['tc_runtime'],
'capacity_price': pp_info_d['price_tc'], 'capacity_price': pp_info_d['price_tc'],
'max_demand_price': pp_info_d['price_md']} 'max_demand_price': pp_info_d['price_md']}
if pp_info_d['price_s']: if pp_info_d['price_s']:
sct = await self._contruct_section('s', pp_info_d, time_str_d, max_dt) sct = await self._contruct_section('s', pp_info_d, time_str_d,
max_dt)
inline_var['section_s'] = sct inline_var['section_s'] = sct
if pp_info_d['price_p']: if pp_info_d['price_p']:
sct = await self._contruct_section('p', pp_info_d, time_str_d, max_dt) sct = await self._contruct_section('p', pp_info_d, time_str_d,
max_dt)
inline_var['section_p'] = sct inline_var['section_p'] = sct
if pp_info_d['price_f']: if pp_info_d['price_f']:
sct = await self._contruct_section('f', pp_info_d, time_str_d, max_dt) sct = await self._contruct_section('f', pp_info_d, time_str_d,
max_dt)
inline_var['section_f'] = sct inline_var['section_f'] = sct
if pp_info_d['price_v']: if pp_info_d['price_v']:
sct = await self._contruct_section('v', pp_info_d, time_str_d, max_dt) sct = await self._contruct_section('v', pp_info_d, time_str_d,
max_dt)
inline_var['section_v'] = sct inline_var['section_v'] = sct
# contruct df_curve # contruct df_curve
df_curve = await self._get_kw_curve(max_dt) df_curve = await self._get_kw_curve(max_dt)
# handle return # handle return
if len(df_curve) == 0: if len(df_curve) == 0:
rlt['rlt_flag'] = False rlt['rlt_flag'] = False
...@@ -86,7 +90,7 @@ class EnergyStoreOptimize(object): ...@@ -86,7 +90,7 @@ class EnergyStoreOptimize(object):
eot.economic_evaluate) eot.economic_evaluate)
rlt['opt_curve'] = self.convert_opt_curve(eot.opt_curve) rlt['opt_curve'] = self.convert_opt_curve(eot.opt_curve)
return rlt return rlt
def convert_economic_evaluate(self, economic_evaluate): def convert_economic_evaluate(self, economic_evaluate):
invest_income_table = economic_evaluate['invest_income_table'] invest_income_table = economic_evaluate['invest_income_table']
table = [] table = []
...@@ -102,7 +106,7 @@ class EnergyStoreOptimize(object): ...@@ -102,7 +106,7 @@ class EnergyStoreOptimize(object):
table.append(tmp_d) table.append(tmp_d)
economic_evaluate['invest_income_table'] = table economic_evaluate['invest_income_table'] = table
return economic_evaluate return economic_evaluate
def convert_opt_curve(self, opt_curve): def convert_opt_curve(self, opt_curve):
rlt = [] rlt = []
for idx, row in opt_curve.iterrows(): for idx, row in opt_curve.iterrows():
...@@ -113,7 +117,7 @@ class EnergyStoreOptimize(object): ...@@ -113,7 +117,7 @@ class EnergyStoreOptimize(object):
tmp_d['load_bat_curve'] = row['load_bat_curve'] tmp_d['load_bat_curve'] = row['load_bat_curve']
rlt.append(tmp_d) rlt.append(tmp_d)
return rlt return rlt
async def _contruct_section(self, p_char, pp_info_d, time_str_d, max_dt): async def _contruct_section(self, p_char, pp_info_d, time_str_d, max_dt):
""" contruct section_x for inline_var.""" """ contruct section_x for inline_var."""
section = {'price': pp_info_d['price_' + p_char]} section = {'price': pp_info_d['price_' + p_char]}
...@@ -122,7 +126,7 @@ class EnergyStoreOptimize(object): ...@@ -122,7 +126,7 @@ class EnergyStoreOptimize(object):
time_range_str = ';'.join(time_str_d[p_char]) time_range_str = ';'.join(time_str_d[p_char])
section['time_range'] = time_range_str section['time_range'] = time_range_str
return section return section
async def _get_inline_info(self): async def _get_inline_info(self):
""" get inline_vc, tc_runtime, cid from redis. """ get inline_vc, tc_runtime, cid from redis.
:return: a dict :return: a dict
...@@ -137,7 +141,7 @@ class EnergyStoreOptimize(object): ...@@ -137,7 +141,7 @@ class EnergyStoreOptimize(object):
'tc_runtime': info['tc_runtime'], 'tc_runtime': info['tc_runtime'],
'cid': info['cid']} 'cid': info['cid']}
return rlt return rlt
async def _get_company_price_policy(self, cid): async def _get_company_price_policy(self, cid):
# pp_json = await RedisUtils(db=1).hget(PRICE_POLICY_HASHNAME, str(cid)) # pp_json = await RedisUtils(db=1).hget(PRICE_POLICY_HASHNAME, str(cid))
# pp_json = self._r_cache.hget(PRICE_POLICY_HASHNAME, str(cid)) # pp_json = self._r_cache.hget(PRICE_POLICY_HASHNAME, str(cid))
...@@ -151,157 +155,77 @@ class EnergyStoreOptimize(object): ...@@ -151,157 +155,77 @@ class EnergyStoreOptimize(object):
return result return result
# pp = json.loads(pp_json) # pp = json.loads(pp_json)
# return pp # return pp
async def _build_max_kwh_day(self): async def _build_max_kwh_day(self):
""" build es query sentance for find max kwh day.""" """ build es query sentance for find max kwh day."""
dt = pendulum.now() dt = pendulum.now()
dt_half_year_ago = dt.subtract(months=6) dt_half_year_ago = dt.subtract(months=6)
q = { start_time = dt_half_year_ago.format("YYYY-MM-DD HH:mm:ss")
"size": 1, end_time = dt.format("YYYY-MM-DD HH:mm:ss")
"query": { sql = f"""
"bool": { select create_time from inline_1day_power
"must": [ where inlid = %s and create_time >= %s and create_time < %s
{"term": { order by kwh desc limit 1
"inlid": { """
"value": self._inlid async with MysqlUtil() as conn:
} result = await conn.fetchone(sql, args=(self._inlid, start_time,
}}, end_time))
{"range": {
"day": { return result.get("create_time") if result else None
"gte": str(dt_half_year_ago),
"lt": str(dt)
}
}}
]
}
},
"sort": [
{
"kwh": {
"order": "desc"
}
}
]
}
return q
async def _find_kwh_max_day(self): async def _find_kwh_max_day(self):
""" find the max kwh day in latest 6 months. """ find the max kwh day in latest 6 months.
:return: a dt object, or None if no doc :return: a dt object, or None if no doc
""" """
rlt = None rlt = None
q = await self._build_max_kwh_day() create_time = await self._build_max_kwh_day()
async with EsUtil() as es: if not create_time:
search_rlt = await es.search_origin( return create_time
body=q, create_time = create_time.strftime("%Y-%m-%d %H:%M:%S")
index=INLINE_1DAY_POWER_ESINDEX) return pendulum.parse(create_time, tz='Asia/Shanghai')
# search_rlt = self._es.search(INLINE_1DAY_POWER_ESINDEX, q)
hits_list = search_rlt['hits']['hits'] async def _build_aggs_kwh(self, p_char, start_dt):
try:
max_day_doc = hits_list[0]['_source']
except IndexError:
pass
else:
day_str = max_day_doc['day']
rlt = pendulum.from_format(day_str, 'YYYY-MM-DDTHH:mm:ssZ',
tz='Asia/Shanghai')
return rlt
def _build_aggs_kwh(self, p_char, start_dt):
end_dt = start_dt.add(days=1) end_dt = start_dt.add(days=1)
q = { start_time = start_dt.format("YYYY-MM-DD HH:mm:ss")
"size": 0, end_time = end_dt.format("YYYY-MM-DD HH:mm:ss")
"query": { sql = f"""
"bool": { select sum(kwh) kwh from inline_15min_power
"must": [ where inlid = %s and spfv = %s and create_time >= %s and
{"term": { create_time < %s
"inlid": { order by kwh desc limit 1
"value": self._inlid """
} async with MysqlUtil() as conn:
}}, result = await conn.fetchone(sql, args=(self._inlid, p_char,
{"term": { start_time,
"spfv": { end_time))
"value": p_char
} return result.get("kwh") if result else 0
}},
{"range": {
"quarter_time": {
"gte": str(start_dt),
"lt": str(end_dt)
}
}}
]
}
},
"aggs": {
"kwh": {
"sum": {
"field": "kwh"
}
}
}
}
return q
async def _get_total_kwh_of_one_pchar(self, p_char, start_dt): async def _get_total_kwh_of_one_pchar(self, p_char, start_dt):
q = self._build_aggs_kwh(p_char, start_dt) return await self._build_aggs_kwh(p_char, start_dt)
async with EsUtil() as es:
search_rlt = await es.search_origin(body=q, index=INLINE_15MIN_POWER_ESINDEX) async def _build_kw_curve(self, start_dt):
# search_rlt = self._es.search(INLINE_15MIN_POWER_ESINDEX, q)
aggs_rlt = search_rlt['aggregations']
return aggs_rlt['kwh']['value']
def _build_kw_curve(self, start_dt):
end_dt = start_dt.add(days=1) end_dt = start_dt.add(days=1)
q = { start_time = start_dt.format("YYYY-MM-DD HH:mm:ss")
"size": 100, end_time = end_dt.format("YYYY-MM-DD HH:mm:ss")
"_source": ["quarter_time", "p"], sql = f"""
"query": { select create_time,p from inline_15min_power
"bool": { where inlid = %s and create_time >= %s and
"must": [ create_time < %s
{"term": { order by create_time asc limit 100
"inlid": { """
"value": self._inlid async with MysqlUtil() as conn:
} results = await conn.fetchall(sql, args=(self._inlid,
}}, start_time,
{"range": { end_time))
"quarter_time": { return results or []
"gte": str(start_dt),
"lt": str(end_dt)
}
}}
]
}
},
"sort": [
{
"quarter_time": {
"order": "asc"
}
}
]
}
return q
async def _get_kw_curve(self, start_dt): async def _get_kw_curve(self, start_dt):
q = self._build_kw_curve(start_dt) hits_list = await self._build_kw_curve(start_dt)
async with EsUtil() as es:
search_rlt = await es.search_origin(
body=q,
index=INLINE_15MIN_POWER_ESINDEX)
# search_rlt = self._es.search(INLINE_15MIN_POWER_ESINDEX, q)
# hits_list is already sorted by quarter_time asc
hits_list = search_rlt['hits']['hits']
kw_list = [] kw_list = []
for item in hits_list: for item in hits_list:
src_d = item['_source'] src_d = item
qrt_str = src_d['quarter_time'] src_d['quarter_time'] = item.get("create_time")
dt = pendulum.from_format(qrt_str, 'YYYY-MM-DDTHH:mm:ssZ',
tz='Asia/Shanghai')
qrt_dt = datetime.datetime(year=dt.year, month=dt.month,
day=dt.day, hour=dt.hour,
minute=dt.minute, second=dt.second)
src_d['quarter_time'] = qrt_dt
kw_list.append(src_d) kw_list.append(src_d)
df = pd.DataFrame(kw_list) df = pd.DataFrame(kw_list)
return df return df
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment