MH-P2/src/execution.py

101 lines
3.3 KiB
Python

from glob import glob
from subprocess import run
from sys import executable
from numpy import mean, std
from pandas import DataFrame, ExcelWriter
def file_list(path):
file_list = []
for fname in glob(path):
file_list.append(fname)
return file_list
def create_dataframes():
greedy = DataFrame()
local = DataFrame()
return greedy, local
def process_output(results):
distances = []
time = []
for element in results:
for line in element:
if line.startswith(bytes("Total distance:", encoding="utf-8")):
line_elements = line.split(sep=bytes(":", encoding="utf-8"))
distances.append(float(line_elements[1]))
if line.startswith(bytes("Execution time:", encoding="utf-8")):
line_elements = line.split(sep=bytes(":", encoding="utf-8"))
time.append(float(line_elements[1]))
return distances, time
def populate_dataframes(greedy, local, greedy_list, local_list, dataset):
greedy_distances, greedy_time = process_output(greedy_list)
local_distances, local_time = process_output(local_list)
greedy_dict = {
"dataset": dataset.removeprefix("data/"),
"media distancia": mean(greedy_distances),
"desviacion distancia": std(greedy_distances),
"media tiempo": mean(greedy_time),
"desviacion tiempo": std(greedy_time),
}
local_dict = {
"dataset": dataset.removeprefix("data/"),
"media distancia": mean(local_distances),
"desviacion distancia": std(local_distances),
"media tiempo": mean(local_time),
"desviacion tiempo": std(local_time),
}
greedy = greedy.append(greedy_dict, ignore_index=True)
local = local.append(local_dict, ignore_index=True)
return greedy, local
def script_execution(filenames, greedy, local, iterations=3):
script = "src/main.py"
for dataset in filenames:
print(f"Running on dataset {dataset}")
greedy_list = []
local_list = []
for _ in range(iterations):
greedy_cmd = run(
[executable, script, dataset, "greedy"], capture_output=True
).stdout.splitlines()
local_cmd = run(
[executable, script, dataset, "local"], capture_output=True
).stdout.splitlines()
greedy_list.append(greedy_cmd)
local_list.append(local_cmd)
greedy, local = populate_dataframes(
greedy, local, greedy_list, local_list, dataset
)
return greedy, local
def export_results(greedy, local):
dataframes = {"Greedy": greedy, "Local search": local}
writer = ExcelWriter(path="docs/algorithm-results.xlsx", engine="xlsxwriter")
for name, df in dataframes.items():
df.to_excel(writer, sheet_name=name, index=False)
worksheet = writer.sheets[name]
for index, column in enumerate(df):
series = df[column]
max_length = max(series.astype(str).str.len().max(), len(str(series.name)))
worksheet.set_column(index, index, width=max_length + 5)
writer.save()
def main():
datasets = file_list(path="data/*.txt")
greedy, local = create_dataframes()
populated_greedy, populated_local = script_execution(datasets, greedy, local)
export_results(populated_greedy, populated_local)
if __name__ == "__main__":
main()