#! /usr/bin/env python

# Copyright (C) 2004, 2009, 2010
# Glimmer-CISM contributors - see AUTHORS file for list of contributors
#
# This file is part of Glimmer-CISM.
#
# Glimmer-CISM is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or (at
# your option) any later version.
#
# Glimmer-CISM is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Glimmer-CISM.  If not, see <http://www.gnu.org/licenses/>.
#
# Glimmer-CISM is hosted on BerliOS.de:
# https://developer.berlios.de/projects/glimmer-cism/

"""Plot EISMINT-2 statistics."""

import PyGC
import sys,os
import numpy
import matplotlib.pyplot
import math

single = ['A','G','H']
CFstat_names = ['Volume','Area','Melt fraction','Divide thickness','Divide basal temp']
CFstat_units = {'single':[' [10@+6@+km@+3@+]',' [10@+6@+km@+2@+]','',' [m]',' [\\353C]'], 'comp':[' [%]',' [%]',' [%]',' [%]',' [\\353C]']}

def parse_eis2file(name):
    """Parse the eismint2 data file

    name: name of file containing EISMINT2 data"""
    

    eis2file = open(name)

    eis2data = {}
    for line in eis2file.readlines():
        line = line.strip()
        if len(line)==0:
            continue
        if line[0] == '#':
            continue
        elif line[0] == '[':
            exp = {}
            end = line.find(']')
            exp_name = line[1:end]
            eis2data[exp_name]=exp
            continue
        else:
            data = []
            line = line.split()
            for i in range(1,len(line)):
                if i==5 and exp_name in single:
                        data.append(float(line[i])-273.15)
                else:
                    data.append(float(line[i]))
            exp[line[0]] = data
    eis2file.close()
    return eis2data

def getstats(ncfile,time):
    """Get ice statistics.

    cffile: CF file object
    time: time slice to be processed

    returns a numpy array: [volume, area, melt fraction,divide thickness,divide basal temp]"""


    stats = numpy.zeros([5],float)

    stats[0] = ncfile.getIceVolume(time=time,scale=1.e-15)
    stats[1] = ncfile.getIceArea(time=time,scale=1.e-12)
    stats[2] = ncfile.getFracMelt(time=time)
    divide   = [len(ncfile.file.variables['x1'][:])/2,len(ncfile.file.variables['y1'][:])/2]
    thick = ncfile.getvar('thk')
    stats[3] = thick.getSpotIJ(divide,time=time)
    temp = ncfile.getvar('temp')
    stats[4] = temp.getSpotIJ(divide,time=time,level=-1)

    return stats



if __name__ == '__main__':

    EIS2_DATA=os.path.join(PyGC.GC_sharedir,'eismint2.data')
        
    parser = PyGC.GCOptParser("""usage: %prog [options] infile1 [infile2 ... infileN]
    plots statistics of EISMINT-2 experiments.""")
    parser.plot()
    parser.add_option("-e","--experiment",default="A",metavar="EXP",type="choice",choices=['A','B','C','D','G','H'],help="select EISMINT-2 experiment to be plotted. If one of ['B','C','D'] is selected you need to give pairs of input files containing the experiment and the exp A to be compared to.")
    parser.add_option("-d","--data",metavar="FILE",default=EIS2_DATA,help="load EISMINT-2 statistics from FILE (default: %s)"%EIS2_DATA)
    
    opts = PyGC.GCOptions(parser,-1)

    exp=opts.options.experiment
    eis2data = parse_eis2file(opts.options.data)[exp]


    if exp in single:
        increment = 1
        unit='single'
        # title
        title = 'Experiment %s'%exp
    else:
        increment = 2
        unit='comp'
        # title
        title = 'Differences between Experiment %s and A'%exp
    nfiles = opts.nfiles/increment

    # rearrange data into array
    data=numpy.zeros((len(CFstat_names),len(eis2data.keys())+nfiles),float)
    ksorted=eis2data.keys()
    ksorted.sort()
    for i in range(0,len(ksorted)):
        k = ksorted[i]
        data[:,i] = eis2data[k]

    # extract data from netCDF files and add to array
    for f in range(0,nfiles):
        gcfile = opts.gcfile(f*increment)
        if increment == 1:
            eis = getstats(gcfile,-1)
        else:
            compfile = opts.gcfile(f*increment+1)
            comp = getstats(compfile,-1)
            eis = getstats(gcfile,-1)
            eis = eis - comp
            for i in range(0,4):
                eis[i]=100.*eis[i]/abs(comp[i])
        data[:,len(ksorted)+f] = eis



    fig = matplotlib.pyplot.figure(figsize=opts.plotsize)

    matplotlib.pyplot.suptitle(title)

    x = numpy.arange(0,len(eis2data.keys())+nfiles)
    width=0.8

    for i in range(0,len(CFstat_names)):
        a = matplotlib.pyplot.subplot(int((len(CFstat_names)+1)/2.),2,i+1)
        bars = a.bar(x,data[i,:],width)
        a.set_ylabel(CFstat_names[i])
        a.autoscale_view(tight=True,scaley=False)
        matplotlib.pyplot.xticks(x+width/2.,ksorted+['']*nfiles)
        for b in bars[-nfiles:]:
            b.set_facecolor('red')

        dmin=min(data[i,:])
        dmax=max(data[i,:])
        a.set_ylim(dmin,dmax)
        yt=a.get_yticks()
        dy=yt[1]-yt[0]
        dmin=numpy.floor(dmin/dy)*dy
        dmax=numpy.ceil(dmax/dy)*dy
        a.set_ylim(dmin,dmax)
        
    if opts.options.output==None:
        matplotlib.pyplot.show()
    else:
        matplotlib.pyplot.savefig(opts.options.output)


