test-app-ldat/latency.py
2025-10-31 21:35:09 +03:00

98 lines
3.9 KiB
Python
Raw 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.

from latencyPlots import plot_delay_histogram_with_ci, plot_horizontal_hist_with_ci, plot_point_cloud
from latencyData import LatencyData
from confidence import compare_confidence_intervals
import argparse
import glob, logging, yaml, os
import numpy as np
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file',
type=str,
help='Path to the csv or yml file, depends on the mode',
required=True)
parser.add_argument('-m', '--mode',
type=int,
default=0,
help='Mode of the script; 0 - one file, 1 - dir')
return parser.parse_args()
def one_file_run():
csv_file = parse_args().file
path_splitted = csv_file.split(os.sep)
title = path_splitted[len(path_splitted) - 1].split('.')[0]
print("АНАЛИЗ ДОВЕРИТЕЛЬНЫХ ИНТЕРВАЛОВ ДЛЯ ЗАДЕРЖЕК")
print("=" * 50)
l = None
try:
l = LatencyData(csv_file, confidence_level=0.99)
except FileNotFoundError:
print(f"✗ Ошибка: Файл '{csv_file}' не найден")
exit(1)
results = plot_delay_histogram_with_ci(
save_to_file=True,
show_plot=False,
title=title,
l=l
)
print("\n" + "=" * 50)
compare_results = compare_confidence_intervals(
csv_file, [0.90, 0.95, 0.99])
if results:
print("\n--- ИНТЕРПРЕТАЦИЯ РЕЗУЛЬТАТОВ ---")
print(f"С вероятностью 95% истинное среднее значение задержки ")
print(
f"находится в интервале от {results['ci_lower']:.2f} до {results['ci_upper']:.2f} мс.")
print(f"Это означает, что если бы мы повторили эксперимент много раз,")
print(f"95% вычисленных таким образом интервалов содержали бы истинное среднее значение.")
def validate_csv_list(csv_arr: list, dirConfig: dict) -> bool:
is_colors_valid = all(file in dirConfig['colors'].keys() for file in csv_arr)
is_labels_valid = all(file in dirConfig['labels'].keys() for file in csv_arr)
if not is_labels_valid:
logging.error("Labels in yaml is not fully valid")
if not is_colors_valid:
logging.error("Colors in yaml is not fully valid")
return is_colors_valid & is_labels_valid
def dir_run():
dirConfig = None
with open(parse_args().file + os.sep + 'dir.yml', encoding='utf-8') as f:
dirConfig = yaml.safe_load(f)
if dirConfig is None:
raise Exception("File not found or not loaded")
path_separated = parse_args().file.split(os.sep)
title = path_separated[len(path_separated) - 2]
all_csv_in_dir = glob.glob(parse_args().file + os.sep +'*.csv')
logging.info(f"Found {len(all_csv_in_dir)} csv files in directory {parse_args().file}")
lDataArr = {os.path.basename(file): LatencyData(file) for file in all_csv_in_dir}
validate_csv_list([os.path.basename(file) for file in all_csv_in_dir], dirConfig)
plot_point_cloud(lDataArr,
dirConfig['colors'],
dirConfig['labels'],
float(dirConfig['point_cloud']['dT']),
title=title)
plot_horizontal_hist_with_ci(lDataArr,
dirConfig['colors'],
dirConfig['labels'],
title=title)
if __name__ == "__main__":
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Arial'
args = parse_args()
mode = args.mode
if mode == 0:
one_file_run()
elif mode == 1:
dir_run()