## This is the user-script for plotting using gleaner tool.

import sys
import os
# Path to gleaner (Better use environment variable PYTHONPATH!)
if os.path.exists('/work/ws-tmp/gk779-SimTec-II/apes_executables/'):
  glrPath = '/work/ws-tmp/gk779-SimTec-II/apes_executables/'
elif os.path.exists( os.getenv('HOME')+'/apes/gleaner'): 
  glrPath = os.getenv('HOME')+'/apes/gleaner'
else:
  print('Gleaner library not found')
  exit

# Import gleaner module
sys.path.append(glrPath)
import gleaner

# Do not use X-server to create and save plot
import matplotlib
matplotlib.use('Agg')

## Import all required modules
import matplotlib.ticker as mtick
import matplotlib.pyplot as mplt
import logging

# font setting
from matplotlib import rc
font_size = 12

#axis without scientific notation
y_formatter = mtick.ScalarFormatter(useOffset=False)

## -------------------------------------------------------------------------- ##
logging.basicConfig(level=logging.INFO)
logging.info('Started creating plots ...') 

# data base filename
dbname = 'channel.db'
# load database if exist else load tracking files and add to database
if os.path.isfile(dbname):
  logging.info('Processing data from existing database')
#  os.remove(dbname)
  import sqlite3
  sqlcon = sqlite3.connect(dbname)
else:
  logging.info('Processing data from tracking files')
  
  sqlcon = gleaner.tracking_to_db(fname = ['tracking/*vel_spatial*.res'], \
                                  dbname=dbname, tabname='vel_spatial')

  sqlcon = gleaner.tracking_to_db(fname = ['tracking/*press_line*.res'], \
                                  dbname=dbname, tabname='press_line')

  sqlcon = gleaner.tracking_to_db(fname = ['tracking/*wss_spatial*.res'], \
                                  dbname=dbname, tabname='wss_spatial')

  sqlcon = gleaner.tracking_to_db(fname = ['tracking/*vel_centerLine*.res'], \
                                  dbname=dbname, tabname='vel_centerline')

  sqlcon = gleaner.tracking_to_db(fname = ['tracking/*probe*.res'], \
                                  dbname=dbname, tabname='probe')
## -------------------------------------------------------------------------- ##
logging.info('Velocity Mag profile across the channel height:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['coordY','vel_mag_phy','vel_an']
[x, y,z] = gleaner.get_columns(sqlcon, tabname='vel_spatial', \
                             columns=get_data_for_cols)
x, y,z = zip(*sorted(zip(x,y,z))) # sort of needed
mplt.plot(x, y, '-s', color = 'k', label = 'Simulation')

mplt.plot(x, z, '-', color = 'r', label = 'Analytic')

# plot setting
mplt.legend(loc=8, ncol=1,borderaxespad=0, \
            prop={'size':font_size}).get_frame().set_lw(0.0)
mplt.xlabel('y (m)')
mplt.ylabel('Velocity ($m/s$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)
mplt.xlim(0.0,0.45)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('Velocity_Profile.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)

## -------------------------------------------------------------------------- ##
logging.info('Pressure drop across the channel length:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['coordX','pressure_phy','press_an']
[x, y,z] = gleaner.get_columns(sqlcon, tabname='press_line', \
                             columns=get_data_for_cols)
x, y,z = zip(*sorted(zip(x,y,z))) # sort of needed
mplt.plot(x, y, '-s', color = 'k', label = 'Simulation')

mplt.plot(x, z, '-', color = 'r', label = 'Analytic')

# plot setting
mplt.legend(loc=1, ncol=1,borderaxespad=0, \
            prop={'size':font_size}).get_frame().set_lw(0.0)
mplt.xlabel('x (m)')
mplt.ylabel('Pressure ($Pa$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)
mplt.xlim(0.0,2.5)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('Pressure_Profile.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)
## -------------------------------------------------------------------------- ##
logging.info('Wall shear stress profile across the channel height:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['coordY','wss_phy','wss_an']
[x, y,z] = gleaner.get_columns(sqlcon, tabname='wss_spatial', \
                             columns=get_data_for_cols)
x, y,z = zip(*sorted(zip(x,y,z))) # sort of needed
mplt.plot(x, y, '-s', color = 'k', label = 'Simulation')

mplt.plot(x, z, '-', color = 'r', label = 'Analytic')

# plot setting
mplt.legend(loc=5, ncol=1,borderaxespad=0, \
            prop={'size':font_size}).get_frame().set_lw(0.0)
mplt.xlabel('x (m)')
mplt.ylabel('WSS ($Pa$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)
mplt.xlim(0.0,0.45)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('WSS_Profile.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)
## -------------------------------------------------------------------------- ##
logging.info('Velocity X across the channel length:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['coordX','velocity_phy_01']
[x, y] = gleaner.get_columns(sqlcon, tabname='vel_centerline', \
                             columns=get_data_for_cols)
x, y = zip(*sorted(zip(x,y))) # sort of needed
mplt.plot(x, y, '-s', color = 'k', label = 'Simulation')

# plot setting
mplt.legend(loc=1, ncol=1,borderaxespad=0, \
            prop={'size':font_size}).get_frame().set_lw(0.0)
mplt.xlabel('x (m)')
mplt.ylabel('Velocity X ($m/s$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)
mplt.xlim(0.0,2.5)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('VelLine_Profile.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)
## -------------------------------------------------------------------------- ##
logging.info('Pressure over time:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['time','pressure_phy']
[x, y] = gleaner.get_columns(sqlcon, tabname='probe', \
                             columns=get_data_for_cols)
x, y = zip(*sorted(zip(x,y))) # sort of needed
mplt.plot(x, y, '-', color = 'r')

# plot setting
mplt.xlabel('time (s)')
mplt.ylabel('Pressure ($Pa$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('PressureOverTime.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)
## -------------------------------------------------------------------------- ##
logging.info('Velocity X over time:')
fig = mplt.figure()
ax = fig.add_subplot(111)
# Plot x, y ... at certain time step
# Simulation result
get_data_for_cols = ['time','velocity_phy_01']
[x, y] = gleaner.get_columns(sqlcon, tabname='probe', \
                             columns=get_data_for_cols)
x, y = zip(*sorted(zip(x,y))) # sort of needed
mplt.plot(x, y, '-', color = 'r')

# plot setting
mplt.xlabel('time (s)')
mplt.ylabel('Velocity X ($m/s$)')
mplt.grid(True,which="major",ls="-")
ax.yaxis.set_major_formatter(y_formatter)

# save fig
figsize = [8,6]
fig = mplt.gcf()
fig.set_size_inches(figsize[0],figsize[1])
mplt.savefig('VelocityXOverTime.png', dpi=100, format='png', \
             bbox_inches="tight",interpolation=None)
## -------------------------------------------------------------------------- ##

logging.info('Plots created')
