Skip to content
Snippets Groups Projects
script_plot_mestrado.py 9.06 KiB
Newer Older
Your Name's avatar
Fix
Your Name committed
import pandas as pd
import matplotlib.pyplot as plt
import os 
import numpy as np
# Leitura do arquivo

main_folder = "./"

scenarios = [name for name in os.listdir(main_folder) if os.path.isdir(os.path.join(main_folder, name))]

Your Name's avatar
Your Name committed
scenarios = sorted(
    scenarios,
    key=lambda x: (
Your Name's avatar
Your Name committed
        x != "no_slicing", 
Your Name's avatar
Your Name committed
        int(x.split('_')[-1]) if x.startswith('scen_') and x.split('_')[-1].isdigit() else float('inf')
    )
)
Your Name's avatar
Fix
Your Name committed

ue_dataframes = {}

for scenario in scenarios:
    ue_dataframes[scenario] = {}
    scenario_path = main_folder + scenario
Your Name's avatar
Your Name committed
    cap_confs_list = [name for name in os.listdir(scenario_path) if os.path.isdir(os.path.join(scenario_path, name))]  
    for cap_conf_folder in cap_confs_list: 
        ue_dataframes[scenario][cap_conf_folder] = {}
        cap_path = scenario_path + '/' + cap_conf_folder
Your Name's avatar
Your Name committed
        ues = [name for name in os.listdir(cap_path) if os.path.isdir(os.path.join(cap_path, name))]
        for ue in ues: 
            data = []
            ue_path = cap_path + '/' + ue + '/' + 'job_1.txt'
            ##Organização do dataframe
            with open(ue_path, 'r') as file:
                count = 0
                data.append({
                                "Interval": 0,
                                "Transfer": 0,
                                "Bandwidth": 0,
                                "Jitter": 0,
Your Name's avatar
Your Name committed
                                "PacketsLost": 0,
                                "TotalPackets": 0
Your Name's avatar
Your Name committed
                            })
Your Name's avatar
Your Name committed
                for line in file:
Your Name's avatar
Your Name committed
                    print(line)
                    if "[  5]" in line and "sec" in line and "MBytes" in line:
Your Name's avatar
Your Name committed
                        parts = line.split()
                        count += 1
                        if count < 10: 
                            data.append({
                                "Interval": count,
Your Name's avatar
Your Name committed
                                "Transfer": parts[4],
                                "Bandwidth": float(parts[6]),
                                "Jitter": parts[8] if len(parts) > 6 else None,
Your Name's avatar
Your Name committed
                                "PacketsLost": int(parts[-2].split("/")[0]) if "/" in parts[-2] else int(parts[-3].split("/")[0]),
                                "TotalPackets": int(parts[-2].split("/")[1]) if "/" in parts[-2] else int(parts[-2])
Your Name's avatar
Your Name committed
                            })
Your Name's avatar
Your Name committed
                        elif count < 60:
Your Name's avatar
Your Name committed
                            data.append({
                                "Interval": count,
                                "Transfer": parts[4],
                                "Bandwidth": float(parts[6]),
                                "Jitter": parts[8] if len(parts) > 6 else None,
Your Name's avatar
Your Name committed
                                "PacketsLost": int(parts[-2].split("/")[0]) if "/" in parts[-2] else int(parts[-3].split("/")[0]),
                                "TotalPackets": int(parts[-2].split("/")[1]) if "/" in parts[-2] else int(parts[-2])
Your Name's avatar
Your Name committed
                            })
                        else:
                            break
Your Name's avatar
Your Name committed
            ue_dataframes[scenario][cap_conf_folder][ue] = pd.DataFrame(data)
Your Name's avatar
Fix
Your Name committed

Your Name's avatar
Your Name committed
# Configurações gerais do gráfico
plt.rcParams.update({
Your Name's avatar
Your Name committed
    'font.size': 18,         # Tamanho geral da fonte
Your Name's avatar
Your Name committed
    'axes.titlesize': 18,    # Tamanho do título dos eixos
    'axes.labelsize': 18,    # Tamanho dos rótulos dos eixos
    'xtick.labelsize': 18,   # Tamanho dos rótulos do eixo X
    'ytick.labelsize': 18,   # Tamanho dos rótulos do eixo Y
    'legend.fontsize': 14,   # Tamanho da fonte da legenda
Your Name's avatar
Your Name committed
    'figure.titlesize': 16   # Tamanho do título da figura
Your Name's avatar
Your Name committed
})
plt.rcParams['figure.figsize'] = [10, 7]  # Tamanho fixo do gráfico

# Listar cenários, ignorando diretórios ocultos
scenarios = [name for name in os.listdir(main_folder) if os.path.isdir(os.path.join(main_folder, name)) and not name.startswith('.')]

for scenario in scenarios:
    scenario_path = os.path.join(main_folder, scenario)
    description_file_path = os.path.join(scenario_path, "scenario_description.txt")
    
    # Verifica se o arquivo existe
    if not os.path.exists(description_file_path):
        print(f"Arquivo não encontrado: {description_file_path}")
        continue  # Pula para o próximo cenário
    
    with open(description_file_path, 'r') as file:
Your Name's avatar
Your Name committed
        scenario_file = file.read().split("\n")
    scenario_info = {item.split(':', 1)[0].strip(): item.split(':', 1)[1].strip() for item in scenario_file if item}
Your Name's avatar
Your Name committed
    
    # Listar configurações de capacidade para o cenário atual
    cap_confs_list = [name for name in os.listdir(scenario_path) if os.path.isdir(os.path.join(scenario_path, name))]
    cap_confs_list = sorted(cap_confs_list, key=lambda x: (x == 'no_slicing', x))
    
    # Listas para armazenar dados de perda de pacotes e taxa efetiva
    pl_ue1 = []  # Perda de pacotes UE1
    pl_ue2 = []  # Perda de pacotes UE2
    bw_ue1 = []  # Taxa efetiva média UE1
    bw_ue2 = []  # Taxa efetiva média UE2
    conf_list = []  # Rótulos das configurações

Your Name's avatar
Your Name committed
    for cap_conf_folder in cap_confs_list:
Your Name's avatar
Your Name committed
        cap_path = os.path.join(scenario_path, cap_conf_folder)
        cap_conf_description_path = os.path.join(cap_path, "cap_conf_description.txt")
        
        # Verifica se o arquivo existe
        if not os.path.exists(cap_conf_description_path):
            print(f"Arquivo não encontrado: {cap_conf_description_path}")
            continue  # Pula para a próxima configuração
        
        with open(cap_conf_description_path, 'r') as file:
Your Name's avatar
Your Name committed
            cap_conf_description = file.read().split("\n")
        cap_conf_info = {item.split(':', 1)[0].strip(): item.split(':', 1)[1].strip() for item in cap_conf_description if item}
Your Name's avatar
Your Name committed
        
        # Coleta de dados de perda de pacotes
        pl_ue1.append((ue_dataframes[scenario][cap_conf_folder]['ue1']["PacketsLost"].sum() / ue_dataframes[scenario][cap_conf_folder]['ue1']["TotalPackets"].sum()) * 100)
        pl_ue2.append((ue_dataframes[scenario][cap_conf_folder]['ue2']["PacketsLost"].sum() / ue_dataframes[scenario][cap_conf_folder]['ue2']["TotalPackets"].sum()) * 100)
        
        # Coleta de dados de taxa efetiva (média)
        bw_ue1.append(ue_dataframes[scenario][cap_conf_folder]['ue1']["Bandwidth"].mean())
        bw_ue2.append(ue_dataframes[scenario][cap_conf_folder]['ue2']["Bandwidth"].mean())
        
Your Name's avatar
Your Name committed
        if cap_conf_info['UE1_slice'] != '-' and cap_conf_info['UE2_slice'] != '-':
Your Name's avatar
Your Name committed
            conf_list.append(f"({cap_conf_info['UE1_slice']}/{cap_conf_info['UE2_slice']})")
Your Name's avatar
Your Name committed
        else:
Your Name's avatar
Your Name committed
            conf_list.append('Conf. No slice')
Your Name's avatar
Your Name committed
    
Your Name's avatar
Your Name committed
    # Rótulos das configurações
Your Name's avatar
Your Name committed
    conf_list = [f"FSS\n {conf}" for j, conf in enumerate(conf_list)]
Your Name's avatar
Your Name committed
    x = np.arange(len(conf_list))  # Posições das configurações
Your Name's avatar
Your Name committed
    largura = 0.4  # Largura das barras
Your Name's avatar
Your Name committed

Your Name's avatar
Your Name committed
    # Gráfico de Taxa Efetiva (Média)
    plt.figure()
    bars1 = plt.bar(x - largura / 2, bw_ue1, width=largura, label=f"UE1 (Banda: {scenario_info['UE1_bandwidth']} Mbps)", color='#ff7f0e')
    bars2 = plt.bar(x + largura / 2, bw_ue2, width=largura, label=f"UE2 (Banda: {scenario_info['UE2_bandwidth']} Mbps)", color='#1f77b4')
Your Name's avatar
Fix
Your Name committed

Your Name's avatar
Your Name committed
    # Ajustar o posicionamento das labels das barras
    for bar1, bar2, bw1, bw2 in zip(bars1, bars2, bw_ue1, bw_ue2):
        height1 = bar1.get_height()
        height2 = bar2.get_height()
        x1 = bar1.get_x() + bar1.get_width() / 2
        x2 = bar2.get_x() + bar2.get_width() / 2
Your Name's avatar
Your Name committed
        
Your Name's avatar
Your Name committed
        # Colocar a label acima da barra, mas dentro dos limites do eixo y
        plt.text(x1, height1 + 0.5, f'{bw1:.1f}', ha='center', va='bottom', fontsize=14)
        plt.text(x2, height2 + 0.5, f'{bw2:.1f}', ha='center', va='bottom', fontsize=14)

    # Ajustar a legenda para não sobrepor as barras
Your Name's avatar
Up  
Your Name committed
    plt.legend(loc='upper left')  # Legenda dentro do gráfico, no canto superior direito
Your Name's avatar
Fix
Your Name committed

Your Name's avatar
Your Name committed
    plt.ylabel('Taxa efetiva (Mbps)')
    plt.xticks(x, conf_list, fontsize=14)
    plt.tight_layout()  # Ajustar layout para evitar sobreposição
Your Name's avatar
Your Name committed
    
Your Name's avatar
Your Name committed
    # Salvar gráfico de taxa efetiva
    save_path_throughput = os.path.join(scenario_path, f"{scenario}_throughput.png")
    plt.savefig(save_path_throughput, dpi=300, bbox_inches='tight')
Your Name's avatar
Up  
Your Name committed
    plt.close()

    # Gráfico de Perda de Pacotes
    plt.figure()
    plt.bar(x - largura / 2, pl_ue1, width=largura, label=f"UE1 (Banda: {scenario_info['UE1_bandwidth']} Mbps)", color='#ff7f0e')  # Barras para UE1
    plt.bar(x + largura / 2, pl_ue2, width=largura, label=f"UE2 (Banda: {scenario_info['UE2_bandwidth']} Mbps)", color='#1f77b4')  # Barras para UE2

    # Adicionar os valores nas barras
    for i in range(len(x)):
        plt.text(x[i] - largura / 2, pl_ue1[i] + 0.5, f'{pl_ue1[i]:.0f} %', ha='center', va='bottom', fontsize=14)
        plt.text(x[i] + largura / 2, pl_ue2[i] + 0.5, f'{pl_ue2[i]:.0f} %', ha='center', va='bottom', fontsize=14)
        
    # Adicionar rótulos e título
    plt.ylabel('Perda de pacote (%)')
    plt.xticks(x, conf_list, fontsize=14)  # Ajustar rótulos do eixo x
    plt.legend(loc='upper center')  # Adicionar legenda

    # Salvar gráfico de perda de pacotes
    save_path_bar = os.path.join(scenario_path, f"{scenario}_packet_loss.png")
    plt.tight_layout()
    plt.savefig(save_path_bar, dpi=300, bbox_inches='tight')
Your Name's avatar
Your Name committed
    plt.close()