
# Ehssen Betaieb, MATSPIF-ID 20-09-2020


import os,subprocess,time,shutil,sys
import numpy as np

# User-adapted
Extension = 'ipn'  # Result file extension
Acceptance_Value = 0.1 # Acceptable error (1 for big test and 0.1 for small test)

# Reference simulation path (Standard for all the tests)
Directory = os.getcwd()
Simulation_Path = Directory+'\\'
Test_name = os.path.basename(Directory)
Ref_Simulation_Path = Directory+'\\'+Test_name+'_ref\\'
Comparison_File = Test_name+'.'+ Extension



# Read the reference file and find last (User-adapted)
Ref_File_Path = Ref_Simulation_Path+Comparison_File
with open(Ref_File_Path, 'r') as file:
      Content_Ref = file.read().splitlines()

Time_Res = [0]*(len(Content_Ref)-1)
Nodes_Res = [0]*(len(Content_Ref)-1)
Value_Ref_Pw = [0]*(len(Content_Ref)-1)
Value_Ref_C = [0]*(len(Content_Ref)-1)

for i in range(1,len(Content_Ref)-1):
    Time_Res[i] = (Content_Ref[i].split()[2])
    Nodes_Res[i] = (Content_Ref[i].split()[3])
    Value_Ref_Pw[i] = (Content_Ref[i].split()[6])
    Value_Ref_C[i] = (Content_Ref[i].split()[7])


# Read the result file and find last value (User-adapted)

Res_File_Path = Simulation_Path+Comparison_File
with open(Res_File_Path, 'r') as file:
      Content_Res = file.read().splitlines()

Time_Res = [0]*(len(Content_Res)-1)
Nodes_Res = [0]*(len(Content_Res)-1)
Value_Res_Pw = [0]*(len(Content_Res)-1)
Value_Res_C = [0]*(len(Content_Res)-1)

for i in range(1,len(Content_Res)-1):
    Time_Res[i] = (Content_Res[i].split()[2])
    Nodes_Res[i] = (Content_Res[i].split()[3])
    Value_Res_Pw[i] = (Content_Res[i].split()[6])
    Value_Res_C[i] = (Content_Res[i].split()[7])


# Error Calculation (User-adapted)


Error_Pw = 0
Error_C = 0
for i in range(1,len(Value_Res_Pw)):
        Error_Pw = ((abs(float(Value_Ref_Pw[i]) - float(Value_Res_Pw[i])))/(abs(float(Value_Ref_Pw[i]))))
for i in range(1,len(Value_Res_C)):
    if float(Value_Ref_C[i])!=0:
    	Error_C = ((abs(float(Value_Ref_C[i]) - float(Value_Res_C[i])))/(abs(float(Value_Ref_C[i]))))

Error = (Error_Pw + Error_C)/2
Rep_File_Path = Simulation_Path+Test_name+'.rep'
with open(Rep_File_Path, 'w') as file:
      file.write('Error =  '+str(Error)+' %'+'\n')
      if Error < Acceptance_Value:
              file.write('Success')
      else:
              file.write('Failure')


