#!/usr/bin/env python
# encoding: utf-8

import sys
import getopt
import re
import os
import pylab as plt
import numpy as np

# Define the variables for which the residuals will be plotted
variables = ["Ux", "Uy", "T", "p_rgh", "k", "epsilon"]

# Get the arguments of the script
def usage():
    print("Usage: residuals.py -l logfile\nPlot the residuals versus Time/Iteration")

try:
    options, args = getopt.getopt(sys.argv[1:], 'l:h', ['help', 'logfile='])
except getopt.GetoptError:
    usage()
    sys.exit(2)

for opt, arg in options:
    if opt in ("-l", "--logfile"):
        log_file = arg
    elif opt in ("-h", "--help"):
        usage()
        sys.exit(1)

# Get the lines of the logfile 'log_file'
lines = open(log_file, "r" ).readlines()

# Get the time and continuity values
time = [] # Time(s) or iterations counter
continuity = [] # Continuity values 
for line in lines:
    if re.search(r"^Time = ", line): # Search for string 'Time' at the begining of the line in file
        start = 'Time = '
        value = line.split(start)[1] # Take the Time value as the string just after start
        time.append(np.float(value)) # Transform the string in a float value
    elif re.search(r"continuity errors :", line): # Search for string 'continuity' in the lines of file 'log_file'
        start = 'sum local = '
        end = ', global'
        value = line.split(start)[1].split(end)[0] # Take the continuity value as string between start and end
        continuity.append(np.float(value)) # Transform the string in a float value

# Get the residual values for each variable
for variable in variables:
    data = []
    for line in lines:
        if re.search(r"Solving for " + variable, line):# Search for string variable in line of file 'log_file'
            start = 'Final residual = '
            end = ', No Iterations'
            value = line.split(start)[1].split(end)[0]
            data.append(np.float(value))
    plt.plot(np.array(time),np.array(data), label=variable) # Plot the residual values of variable

plt.plot(np.array(time),np.array(continuity), label="Continuity") # Plot the continuity values

# Plot
plt.title("Residuals plot:\n * logfile: " + log_file + "\n * case dir: " + os.getcwd().split('/')[-1], loc='left')
plt.xlabel("Time(s)/Iterations")
plt.ylabel("Residuals (Log Scale)")
plt.yscale('log')
plt.legend()
plt.grid()
plt.show()

[((63, 0, 63, 32), 'pylab.xlabel', 'plt.xlabel', ({(63, 11, 63, 31): '"""Time(s)/Iterations"""'}, {}), "('Time(s)/Iterations')", True, 'import pylab as plt\n'), ((64, 0, 64, 35), 'pylab.ylabel', 'plt.ylabel', ({(64, 11, 64, 34): '"""Residuals (Log Scale)"""'}, {}), "('Residuals (Log Scale)')", True, 'import pylab as plt\n'), ((65, 0, 65, 17), 'pylab.yscale', 'plt.yscale', ({(65, 11, 65, 16): '"""log"""'}, {}), "('log')", True, 'import pylab as plt\n'), ((66, 0, 66, 12), 'pylab.legend', 'plt.legend', ({}, {}), '()', True, 'import pylab as plt\n'), ((67, 0, 67, 10), 'pylab.grid', 'plt.grid', ({}, {}), '()', True, 'import pylab as plt\n'), ((68, 0, 68, 10), 'pylab.show', 'plt.show', ({}, {}), '()', True, 'import pylab as plt\n'), ((19, 20, 19, 76), 'getopt.getopt', 'getopt.getopt', ({(19, 34, 19, 46): 'sys.argv[1:]', (19, 48, 19, 53): '"""l:h"""', (19, 55, 19, 75): "['help', 'logfile=']"}, {}), "(sys.argv[1:], 'l:h', ['help', 'logfile='])", False, 'import getopt\n'), ((38, 7, 38, 35), 're.search', 're.search', ({(38, 17, 38, 28): '"""^Time = """', (38, 30, 38, 34): 'line'}, {}), "('^Time = ', line)", False, 'import re\n'), ((59, 9, 59, 23), 'numpy.array', 'np.array', ({(59, 18, 59, 22): 'time'}, {}), '(time)', True, 'import numpy as np\n'), ((59, 24, 59, 44), 'numpy.array', 'np.array', ({(59, 33, 59, 43): 'continuity'}, {}), '(continuity)', True, 'import numpy as np\n'), ((22, 4, 22, 15), 'sys.exit', 'sys.exit', ({(22, 13, 22, 14): '(2)'}, {}), '(2)', False, 'import sys\n'), ((42, 9, 42, 48), 're.search', 're.search', ({(42, 19, 42, 41): '"""continuity errors :"""', (42, 43, 42, 47): 'line'}, {}), "('continuity errors :', line)", False, 'import re\n'), ((52, 11, 52, 54), 're.search', 're.search', ({(52, 21, 52, 47): "('Solving for ' + variable)", (52, 49, 52, 53): 'line'}, {}), "('Solving for ' + variable, line)", False, 'import re\n'), ((57, 13, 57, 27), 'numpy.array', 'np.array', ({(57, 22, 57, 26): 'time'}, {}), '(time)', True, 'import numpy as np\n'), ((57, 28, 57, 42), 'numpy.array', 'np.array', ({(57, 37, 57, 41): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((29, 8, 29, 19), 'sys.exit', 'sys.exit', ({(29, 17, 29, 18): '(1)'}, {}), '(1)', False, 'import sys\n'), ((41, 20, 41, 35), 'numpy.float', 'np.float', ({(41, 29, 41, 34): 'value'}, {}), '(value)', True, 'import numpy as np\n'), ((46, 26, 46, 41), 'numpy.float', 'np.float', ({(46, 35, 46, 40): 'value'}, {}), '(value)', True, 'import numpy as np\n'), ((56, 24, 56, 39), 'numpy.float', 'np.float', ({(56, 33, 56, 38): 'value'}, {}), '(value)', True, 'import numpy as np\n'), ((62, 75, 62, 86), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os\n')]