#!/usr/bin/python -i

# python with pdffit2 loaded - as students are accustomed to

from diffpy.pdffit2 import PdfFit
import readline
import rlcompleter
import sys
import os
import atexit

# tab completion
readline.parse_and_bind("tab: complete")

# record history
histfile = os.path.join(os.environ["HOME"], ".pdffit2hist")
try:
   readline.read_history_file(histfile)
except IOError:
   pass
atexit.register(readline.write_history_file, histfile)
del histfile

# prompt setup
sys.ps1 = "pdffit2> "

# create PdfFit instance and export its members to global namespace
_P = PdfFit()
_P._exportAll(locals())

# make exit() available
from sys import exit

# pylab support:
print "loading pylab ...", ; sys.stdout.flush()
from pylab import *
print "[done]"

# alias to allow help(pdffit)
pdffit = PdfFit
print 'Type  help(pdffit)  or  help(topic)  for information.'
print 'Type  exit()  or  <Ctrl-D>  to exit.\n'

class EasyPDFPlottingInterface:
    def __init__(self, PdfFit_instance):
        self._pdffit = PdfFit_instance
        return
    def r(self):
        return array( self._pdffit.getR() )
    def Gobs(self):
        return array( self._pdffit.getpdf_obs() )
    def Gcalc(self):
        return array( self._pdffit.getpdf_fit() )
    def Gdiff(self):
        return self.Gobs() - self.Gcalc()
    def showfit(self, offset = None):
        cr = self.r()
        cGobs = self.Gobs()
        cGcalc = self.Gcalc()
        cGdiff = self.Gdiff()
        if offset is None:
            offset = floor( min([min(cGobs), min(cGcalc)]) - max(cGdiff) )
        plot(cr, cGobs, 'r.', cr, cGcalc, 'b-',  cr, cGdiff+offset, 'g-' )
        xl = gca().xaxis.get_label().get_text()
        yl = gca().yaxis.get_label().get_text()
        if xl == "": xlabel('r (A)')
        if yl == "": ylabel('G (A**-2)')
        return
    def showRw(self, offset = None):
        cr = self.r()
        cGobs = self.Gobs()
        cGdiff = self.Gdiff()
        cRw = sqrt( cumsum(cGdiff**2) / sum(cGobs**2) )
        plot(cr, cRw)
        title('Cumulative Rw = %.4f' % cRw[-1])
        xlabel('r')
        ylabel('Rw')
        return

pdf = EasyPDFPlottingInterface(_P)

# execute the first argument
if (len(sys.argv)>1):
      execfile(sys.argv[1])
