asotr_flight/plot_flight_borders.py

190 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import matplotlib.pyplot as plt
from matplotlib import dates
import argparse
import sys
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
import pandas as pd
def convert_to_str(lst):
index = [i for i, x in enumerate(lst) if x == 1]
res = f"ch{index[0] + 1}"
for idx in index[1:]:
res += f"_{idx + 1}"
return res
def plot_asotr_borders(path_with_data, ch, asotr_kit, begin, end, font=14, cmd=0, show_flag=True):
print_width = 20
print_height = 12
width = 1
plot_windows = 2
channels = list(map(int, ch))
pict_name = (f'./reports/ASOTR{asotr_kit}_flight_T_P_{convert_to_str(channels)}_{begin[0:5].replace(".", "")}_{end[0:5].replace(".", "")}_{end[6:]}.png')
plot_task = {"temp": 1, "temp_set": 1, "pow": 1}
ox_dtime_format = "%d.%m.%Y"
legend = [
"канал 1 (БРД1)",
"канал 2 (БРД2)",
"канал 3 (БРД3)",
"канал 4 (БРД4)",
"канал 5 (плита МУП МВН)",
"канал 6 (плита МУП МВН)",
]
legend_set = list(map(lambda x: x + " уставка", legend))
width = [1, 1, 1, 1, 1, 1]
width_set = [3, 3, 3, 3, 3, 3]
marker = ["-", "--", "-.", "-", "-", "--"]
width_arr = [1, 0.5, 0.2, 0.1, 1, 1]
# get from files and prepare data
start_date = begin + " 00:00:00"
end_date = end + " 23:59:59"
try:
data, data_dict = asotr.get_data(path_with_data, asotr_kit, start_date, end_date, 'minutes')
except Exception as e:
return
if plot_windows == 1:
fig, ax = plt.subplots(figsize=(print_width, print_height), dpi=200)
if plot_task["temp"] == 1:
for i in range(len(channels)):
if channels[i] == 1:
ax.plot(data_dict["time_temp"],
data_dict['temp'].iloc[:,i],
marker[i],
linewidth=width[i],
label=legend[i],)
ax.tick_params(axis="both", width=1, labelsize=font)
ax.grid(visible=True, linestyle="dotted")
ax.set_ylabel("Температура, $^\circ$C", fontsize=font)
ax.set_xlabel("Время", fontsize=font)
ax.legend(fontsize=font)
date_formatter = dates.DateFormatter(ox_dtime_format)
ax.xaxis.set_major_formatter(date_formatter)
plt.tight_layout()
fig.savefig(pict_name)
if show_flag == True:
plt.show()
elif plot_windows == 2:
fig = plt.figure(figsize=(print_width, print_height), dpi=200)
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)
if cmd == '1':
fname = './flight_cmd_human.txt'
try:
cmd_human = pd.read_csv('./data/cmd_human.csv',
delimiter=';', names=['timestamp', 'cmd'])
except Exception as e:
print(f'Error parsing file: {e}')
return
max_temp = max(data_dict['temp'].iloc[:,1])
min_temp = min(data_dict['temp'].iloc[:,1])
# print(cmd_human)
step = 0
for i, row in cmd_human.iterrows():
row_time = row['timestamp'][0:len(row['timestamp']) - 4]
# print(row_time)
idx = asotr.find_best_time_idx(data_dict['time_temp'],
row_time, accuracy='minutes')
# print(idx)
if idx != -1:
ax1.axvline(x = data_dict['time_temp'][idx], color='r',
linestyle='-.')
ax1.text(data_dict['time_temp'][idx], max_temp - step, row['cmd'],
rotation=45, va='bottom', fontsize=font)
step += (max_temp - min_temp)/20
if plot_task["temp"] == 1:
for i in range(len(channels)):
if channels[i] == 1:
ax1.plot(data_dict["time_temp"],
data_dict['temp'].iloc[:,i],
marker[i],
linewidth=width[i],
label=legend[i],)
if plot_task["temp_set"] == 1:
for i in range(len(channels)):
if channels[i] == 1:
ax1.plot(data_dict["time_temp_set"],
data_dict['temp_set'].iloc[:,i],
marker[i],
linewidth=width_set[i],
label=legend_set[i],)
if plot_task["pow"] == 1:
for i in range(len(channels)):
if channels[i] == 1:
ax2.plot(data_dict["time_pow"],
data_dict['pow'].iloc[:,i],
marker[i],
linewidth=width[i],
label=legend[i],)
ax1.tick_params(axis="both", width=1, labelsize=font)
ax1.grid(visible=True, linestyle="dotted")
ax1.set_ylabel("Температура, $^\circ$C", fontsize=font)
ax1.set_xlabel("Время", fontsize=font)
ax1.legend(fontsize=font)
date_formatter = dates.DateFormatter(ox_dtime_format)
ax1.xaxis.set_major_formatter(date_formatter)
ax2.tick_params(axis="both", width=1, labelsize=font)
ax2.grid(visible=True, linestyle="dotted")
ax2.set_ylabel("Мощность, %", fontsize=font)
ax2.set_xlabel("Время", fontsize=font)
ax2.set_ylim(-5,105)
ax2.legend(fontsize=font)
date_formatter = dates.DateFormatter(ox_dtime_format)
ax2.xaxis.set_major_formatter(date_formatter)
title = (f'работа АСОТР{asotr_kit} в период с {start_date[0:10]} по {end_date[0:10]} г.')
fig.suptitle(title, fontsize=font)
plt.tight_layout()
fig.savefig(pict_name)
if show_flag == True:
plt.show()
if __name__ == '__main__':
argparser = argparse.ArgumentParser("plot_flight_borders.py")
argparser.add_argument('-s', '--source', required=True,
help='type path with asotr csv data')
argparser.add_argument('-c', '--channel', required=True,
help='type channel (example: 000011)')
argparser.add_argument('-a', '--asotr', required=True,
help='type asotr kit (01 or 02)')
argparser.add_argument('-b', '--begin', required=True,
help='type begin date if dd.mm.YYYY format')
argparser.add_argument('-e', '--end', required=True,
help='type end date if dd.mm.YYYY format')
argparser.add_argument('-f', '--font', required=False,
help='type font size (from 1 to 30)')
argparser.add_argument('-d', '--cmd', required=False,
help='type display commands flag (0/1)')
argparser.add_argument('-p', '--plot', required=False,
help='display data in plot flag (0/1)')
args = argparser.parse_args()
plot_asotr_borders(args.source, args.channel, args.asotr, args.begin, args.end,
args.font, args.cmd, args.plot)