#!/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()

[((2258, 2290), 'pylab.xlabel', 'plt.xlabel', (['"""Time(s)/Iterations"""'], {}), "('Time(s)/Iterations')\n", (2268, 2290), True, 'import pylab as plt\n'), ((2291, 2326), 'pylab.ylabel', 'plt.ylabel', (['"""Residuals (Log Scale)"""'], {}), "('Residuals (Log Scale)')\n", (2301, 2326), True, 'import pylab as plt\n'), ((2327, 2344), 'pylab.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (2337, 2344), True, 'import pylab as plt\n'), ((2345, 2357), 'pylab.legend', 'plt.legend', ([], {}), '()\n', (2355, 2357), True, 'import pylab as plt\n'), ((2358, 2368), 'pylab.grid', 'plt.grid', ([], {}), '()\n', (2366, 2368), True, 'import pylab as plt\n'), ((2369, 2379), 'pylab.show', 'plt.show', ([], {}), '()\n', (2377, 2379), True, 'import pylab as plt\n'), ((404, 460), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""l:h"""', "['help', 'logfile=']"], {}), "(sys.argv[1:], 'l:h', ['help', 'logfile='])\n", (417, 460), False, 'import getopt\n'), ((897, 924), 're.search', 're.search', (['"""^Time = """', 'line'], {}), "('^Time = ', line)\n", (906, 924), False, 'import re\n'), ((2049, 2063), 'numpy.array', 'np.array', (['time'], {}), '(time)\n', (2057, 2063), True, 'import numpy as np\n'), ((2064, 2084), 'numpy.array', 'np.array', (['continuity'], {}), '(continuity)\n', (2072, 2084), True, 'import numpy as np\n'), ((504, 515), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (512, 515), False, 'import sys\n'), ((1192, 1230), 're.search', 're.search', (['"""continuity errors :"""', 'line'], {}), "('continuity errors :', line)\n", (1201, 1230), False, 'import re\n'), ((1668, 1710), 're.search', 're.search', (["('Solving for ' + variable)", 'line'], {}), "('Solving for ' + variable, line)\n", (1677, 1710), False, 'import re\n'), ((1953, 1967), 'numpy.array', 'np.array', (['time'], {}), '(time)\n', (1961, 1967), True, 'import numpy as np\n'), ((1968, 1982), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1976, 1982), True, 'import numpy as np\n'), ((658, 669), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (666, 669), False, 'import sys\n'), ((1126, 1141), 'numpy.float', 'np.float', (['value'], {}), '(value)\n', (1134, 1141), True, 'import numpy as np\n'), ((1491, 1506), 'numpy.float', 'np.float', (['value'], {}), '(value)\n', (1499, 1506), True, 'import numpy as np\n'), ((1923, 1938), 'numpy.float', 'np.float', (['value'], {}), '(value)\n', (1931, 1938), True, 'import numpy as np\n'), ((2218, 2229), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2227, 2229), False, 'import os\n')]