#!/usr/bin/env python
# This script runs the simulation with different number of processes.
# To run the tests: 
# 1. The folder should have input file <lua  script for musubi> with proper path to mesh folder.
# 2. Input parameter should be set in "params_runsim.list"
# "Number of processes" and "input file name" are the parameters that can be set in  "params_runsim.list"
# usage : ./1_runsim.py
# output/outputs generated:
# A file timing.res_<date> is generated in the folder.
# The plots can be plotted by running ./2_plot.py

import os
import subprocess
from subprocess import call
import re
import shutil
import sys
from time import strftime


date = strftime("%d-%m-%Y")

# path where scaling test is run from
path_para = os.getcwd()
solver = 'musubi'

#Read parameters from params.list
param_file = open("params.list", "r")
param_list = param_file.read()
param_file.close()

# Read the Number of processes list
line_procs = re.findall(r"NumProcs.*$", param_list,re.MULTILINE)
for x in line_procs:
  proc_temp = re.split(r"= ", x)
  list_proc = re.split(r"\s", proc_temp[1])
#  print list_proc

# read the path to the input lua script
line_path = re.findall(r"lua_script =.*$",param_list,re.MULTILINE)
for y in line_path:
  path_temp = re.split(r"= ",y)
  list_path = re.split(r"\s",path_temp[1])
#  print list_path

for x in list_path:
  inp_file = x


# find the path to executable from current folder
c =0
while not os.path.isdir('source'):
   os.chdir('../')
   c = c+1

ex = './'
for i in range(1,c):
  ex = ex+'../'

exec_path = ex+'build/musubi'


# configure and build

success = call(['./waf','configure'])
call(['./waf','build'])


os.chdir(path_para)

# delete the timing.res file
if os.path.exists('timing.res'):
  os.remove('timing.res')

# Run the code in parallel
for procs in list_proc:
   print procs
   cmd =  ['mpirun -np '+str(procs)+' .'+exec_path+' '+ inp_file]
   print cmd
   subprocess.call(cmd,shell=True)


# Rename the output file with date
cmd = ['mv timing.res timing.res_'+date]
subprocess.call(cmd,shell=True)




