#! /usr/bin/env python 

description="""\
Plots the residuals generated by the tools
pyFoamStandardLogAnalyzer.py, pyFoamSteadyRunner.py or
pyFoamRunner.py.  The argument should be the directory with the result
files (usually PyFoamSolve.analyzed)
"""

from PyFoam.Basics.FoamOptionParser import FoamOptionParser

parse=FoamOptionParser(description=description,usage="%prog [options] <datadir>",interspersed=True)

try:
    import PyFoam.ThirdParty.Gnuplot as Gnuplot
except ImportError,e:
    parse.error("Gnuplot module missing. Can't plot")
    
parse.parse(nr=1)

import sys,os
from os import path

from PyFoam.Basics.Helpers import getLinearNames
    
data=parse.getArgs()[0]
dDir=path.basename(data)

names=getLinearNames(data)

if sys.stdout.isatty():
    g=Gnuplot.Gnuplot(persist=1)
else:
    g=Gnuplot.Gnuplot()
    

plots=[]

for n in names:
    plots.append(Gnuplot.File(path.join(data,"linear_"+n),using="1:2",with='steps',title=n))

g.set_string("logscale y")
g.title("Residuals")

apply(g.plot,plots)

if not sys.stdout.isatty():
    tmpfile="/tmp/Gnuplot_temp.ps"
    Gnuplot.GnuplotOpts.default_lpr=" "+tmpfile
    g.hardcopy()
    f=open(tmpfile,"r")
    sys.stdout.write(f.read())
    f.close()
    os.remove(tmpfile)
