#!/usr/bin/python3

import os
from scipy.optimize import minimize
import subprocess
import sys

cte_file_num = 0

def run(args):
    subprocess.call(args, shell=True)

def calculate_measure(cte_filename):
    num_values = 0
    sum = 0
    with open(cte_filename, 'r') as f:
        for line in f:
            if line.startswith('data:') and not line.startswith('data: nan'):
                num_values += 1
                sum += abs(float(line.split(' ')[1]))
    print(sum, num_values, sum / num_values)
    return sum / num_values

def format_cte_file(p, i, d):
    global cte_file_num
    cte_file_num += 1
    cte_filename = '{0:05d}'.format(cte_file_num)
    cte_filename += '_p_{0:0f}_i_{1:0f}_d_{2:0f}'.format(p, i, d)
    cte_filename += '.cte'
    return cte_filename

def run_sim(x):
    p, i, d = x[0], x[1], x[2]
    cte_filename = format_cte_file(p, i, d)
    run('./run_sim {0} {1} {2} {3}'.format(p, i, d, cte_filename))
    return calculate_measure(cte_filename)

x0 = [float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3])]
res = minimize(run_sim, x0, method='nelder-mead')
print(res.x)

