#! /usr/bin/env python

# Copyright (C) 2005, 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/

"""A plot of CF profile timeseries."""

import PyGC,numpy,sys
import matplotlib.pyplot
import numpy,numpy.ma

SIZE_Y = 4.

# creating option parser
parser = PyGC.GCOptParser()
parser.width=15.
parser.variable()
parser.add_option("--profvar",metavar='NAME',type="string",dest='profvar',help="plot variable NAME at beginning and end of time interval")
parser.epoch()
parser.profile_file()
parser.timeint()
parser.plot()
opts = PyGC.GCOptions(parser,1)
infile = opts.cfprofile()
profile = opts.profs(infile)
try:
    t0 = opts.times(infile,0)
    t1 = opts.times(infile,1)
except:
    t0=0
    t1=infile.numt-1

if opts.options.level == None:
    level = 0
else:
    level = opts.options.level

extent = [infile.time(t0),infile.time(t1),infile.xvalues[0],infile.xvalues[-1]]

fig = matplotlib.pyplot.figure(figsize=opts.plotsize)
vstart=0.1
height=0.8
width=0.8
profileWidth=0.15

# create axes for legend
if opts.options.legend=='h':
    vstart+=0.11
    height-=0.05
    legAxes = fig.add_axes([0.1,0.1,width,0.03])
if opts.options.legend=='v':
    width-=0.1
    legAxes = fig.add_axes([0.85,0.1,0.03,height])

if opts.options.profvar != None:
    width-=profileWidth

# create axes for plotting epochs
epochAxes=None
if opts.options.epoch != None:
    epochAxes = fig.add_axes([0.1,vstart,width,0.05],sharex=epochAxes)
    vstart+=0.05
    height-=0.05
    epochAxes.set_yticks([])
    epochAxes.set_xlabel("time [ka]")

    epoch = PyGC.IO.GCEpoch(opts.options.epoch,sharedir=PyGC.GC_sharedir)
    e=epoch.data
    for c in range(0,len(e)):
        te0 = e[c]['start']*epoch.timescale
        te1 = e[c]['end']*epoch.timescale
        if te1<infile.time(t0) or te0>infile.time(t1):
            continue
        te0=max(infile.time(t0),te0)
        te1=min(infile.time(t1),te1)
        epochAxes.bar([te0],[1],width=[te1-te0],color=e[c]['colour'])
        epochAxes.text(te0+(te1-te0)/2.,0.5,e[c]['name'],horizontalalignment='center',verticalalignment='center')

# create axes for plotting profile at time t0 and t1
profAxes=None
if opts.options.profvar != None:
    profAxes = fig.add_axes([0.1+width,vstart,profileWidth,height],sharey=profAxes)
    profAxes.get_yaxis().set_visible(False)
    pdata = infile.getprofile(opts.options.profvar)
    profAxes.plot(pdata.getProfile(t0),infile.xvalues)
    profAxes.plot(pdata.getProfile(t1),infile.xvalues)
    labels = profAxes.get_xticklabels()
    matplotlib.pyplot.setp(labels,rotation=90)

dataAxes = fig.add_axes([0.1,vstart,width,height],sharex=epochAxes,sharey=profAxes)
dataAxes.set_xlabel("time [ka]")
dataAxes.set_ylabel("distance along profile [km]")

thk = infile.getprofile('thk').getProfileTS(time=[t0,t1])
data = profile.getProfileTS(time=[t0,t1])
if opts.options.clip!=None:
    if opts.options.clip=='thk':
        clip = thk
    else:
        clip = infile.getprofile(opts.options.clip).getProfileTS(time=[t0,t1])
    data = numpy.ma.array(data,mask=numpy.where(clip>0.1,False,True))


norm,cmap,title = opts.colourmap(infile)
im = dataAxes.imshow(data,norm=norm,cmap=cmap,origin='lower',extent=extent,aspect='auto')

dataAxes.contour(thk,[0.1],origin='lower',extent=extent)

# plot vertical lines
if opts.options.epoch != None:
    dataAxes.get_xaxis().set_visible(False)
    dataAxes.set_xlabel("")
    for c in range(0,len(e)):
        te0 = e[c]['start']*epoch.timescale
        te1 = e[c]['end']*epoch.timescale
        if te0>=infile.time(t0) and te0<=infile.time(t1):
            dataAxes.axvline(te0,color='k',ls=':')
        if te1>=infile.time(t0) and te1<=infile.time(t1):
            dataAxes.axvline(te1,color='k',ls=':')

# plot legend
if opts.options.legend!=None:
    if opts.options.legend=='v':
        orientation='vertical'
    else:
        orientation='horizontal'
    cb = fig.colorbar(im, extend='both', spacing='uniform',orientation=orientation,cax=legAxes)
    cb.set_label(title)

# display title
if opts.options.title:
    matplotlib.pyplot.title(infile.title)

if opts.options.output==None:
    matplotlib.pyplot.show()
else:
    matplotlib.pyplot.savefig(opts.options.output)


