#!/usr/bin/python3

import re
import sys
import numpy as np
import pandas as pd

# Read argument: either D-0.01 or D-0.10
exp_name = sys.argv[1]
defect = exp_name[2:]
pattern = r"-0\.125-" + re.escape(defect) + r"\.pec"
# Tool names from BenchExec
tool_list = ["ABC", "DC-SSAT", "Cachet", "ApproxMC"]
# Read CSV file generated by table-generator
df = pd.read_csv("./csv/PEC-" + exp_name + ".table.csv", sep="\t")
df = df.fillna(value=np.nan)
# Drop useless rows
df = df.drop([0, 1])
# Adjust circuit names
df = df.replace(regex=pattern, value="")
df = df.replace(regex=r"mem_ctrl", value="mem\_ctrl")
# Erase CPU time if the task is not done
for tool in tool_list:
    df[tool + " .1"][df[tool + " "] != "done"] = np.nan
# Compute probabilities of ApproxMC
df["ApproxMC-prob"] = df["ApproxMC .3"].apply(
    lambda x: eval(x) if type(x) == str else x
).astype(float) / np.power(2, df["ApproxMC .2"].astype(float))
# Drop useless columns
for tool in tool_list:
    df = df.drop([tool + " "], axis=1)
df = df.drop(["ApproxMC .2", "ApproxMC .3"], axis=1)
df.columns = [
    "Circuit",
    "ABC-T",
    "ABC-P",
    "DC-T",
    "DC-P",
    "Cachet-T",
    "Cachet-P",
    "AMC-T",
    "AMC-P",
]
# Drop all-empty rows
df = df.dropna(how="all", subset=df.columns[1:])
# Write out a parsed csv file
df.to_csv("./csv/parsed-PEC-" + exp_name + ".csv", sep="\t", na_rep="nan", index=False)
