Example #1
0
def process(fname):
    """Process verif output file.

    fname: name of file

    return: tuple of (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)"""

    # extract errors
    ncf = Scientific.IO.NetCDF.NetCDFFile(fname)
    diff = ncf.variables['thke'][-1,:,:] - ncf.variables['thk'][-1,:,:]
    centre = (Numeric.shape(diff)[0]-1)/2
    dome_e = diff[centre,centre]
    diff = Numeric.ravel(diff)
    max_e = max(abs(diff))
    min_e = min(abs(diff))
    hist = histogram.histogram(100)
    hist.set_ranges_uniform(PyGMT.round_down(min_e),PyGMT.round_up(max_e))
    for e in diff.tolist():
        hist.increment(e)
    mean_e = hist.mean()
    sd_e = hist.sigma()

    (exp_name,solver,dx,dt) = parse_title(ncf.title)
    
    ncf.close()

    return (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)
Example #2
0
def process(fname):
    """Process verif output file.

    fname: name of file

    return: tuple of (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)"""

    # extract errors
    ncf = Scientific.IO.NetCDF.NetCDFFile(fname)
    diff = ncf.variables['thke'][-1,:,:] - ncf.variables['thk'][-1,:,:]
    centre = (Numeric.shape(diff)[0]-1)/2
    dome_e = diff[centre,centre]
    diff = Numeric.ravel(diff)
    max_e = max(abs(diff))
    min_e = min(abs(diff))
    hist = histogram.histogram(100)
    hist.set_ranges_uniform(PyGMT.round_down(min_e),PyGMT.round_up(max_e))
    for e in diff.tolist():
        hist.increment(e)
    mean_e = hist.mean()
    sd_e = hist.sigma()

    (exp_name,solver,dx,dt) = parse_title(ncf.title)
    
    ncf.close()

    return (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)
    def plot(self):
        """Plot RSL histogram."""

        if self.__cmap == None:
            self.setcolourmap()

        self.area2d = None
        self.area1d = None

        y = 0.0
        if self.plot_key:
            PyGMT.colourkey(self, self.__cmap.name, pos=[self.size[0] / 8.0, 0.0], size=[3.0 * self.size[0] / 4.0, 0.5])
            y = 2.0

        if self.plot_2dhist and self.__plot_1dhist:
            self.area2d = PyGMT.AutoXY(self, pos=[0.0, y], size=[3.0 * self.size[0] / 4.0, self.size[1] - y])
            self.area1d = PyGMT.AutoXY(
                self, pos=[3.0 * self.size[0] / 4.0, y], size=[self.size[0] / 4.0, self.size[1] - y]
            )
        else:
            if self.plot_2dhist:
                self.area2d = PyGMT.AutoXY(self, pos=[0.0, y], size=[self.size[0], self.size[1] - y])
            if self.plot_1dhist:
                self.area1d = PyGMT.AutoXY(self, pos=[0.0, y], size=[self.size[0], self.size[1] - y])

        if self.plot_2dhist:
            self.area2d.axis = "WSen"
            self.area2d.xlabel = "time [ka]"
            self.area2d.ylabel = "residuals [m]"
            self.area2d.image(self.__rsldata, self.__cmap.name)

        if self.plot_1dhist:
            counts = numpy.sum(self.__rsldata.data, 0)
            dx = (self.__rsldata.y_minmax[1] - self.__rsldata.y_minmax[0]) / (len(counts) - 1)
            bins = numpy.arange(self.__rsldata.y_minmax[0], self.__rsldata.y_minmax[1] + dx, dx)

            if self.plot_2dhist:
                self.area1d.steps("-W1", counts, bins)
                self.area1d.ur[0] = PyGMT.round_up(self.area1d.ur[0])
                self.area1d.xlabel = "count"
                self.area1d.axis = "wSen"
            else:
                self.area1d.steps("-W1", bins, counts)
                self.area1d.ur[1] = PyGMT.round_up(self.area1d.ur[1])
                self.area1d.xlabel = "residuals [m]"
                self.area1d.ylabel = "count"
                self.area1d.axis = "WSen"
    def plot(self):
        """Plot RSL histogram."""

        if self.__cmap==None:
            self.setcolourmap()

        self.area2d = None
        self.area1d = None

        y = 0.
        if self.plot_key:
            PyGMT.colourkey(self,self.__cmap.name,pos=[self.size[0]/8.,0.],size=[3.*self.size[0]/4.,.5])
            y = 2.

        if self.plot_2dhist and self.__plot_1dhist:
            self.area2d = PyGMT.AutoXY(self,pos=[0.,y],size=[3.*self.size[0]/4.,self.size[1]-y])
            self.area1d = PyGMT.AutoXY(self,pos=[3.*self.size[0]/4.,y],size=[self.size[0]/4.,self.size[1]-y])
        else:
            if self.plot_2dhist:
                self.area2d = PyGMT.AutoXY(self,pos=[0.,y],size=[self.size[0],self.size[1]-y])
            if self.plot_1dhist:
                self.area1d = PyGMT.AutoXY(self,pos=[0.,y],size=[self.size[0],self.size[1]-y])

        if self.plot_2dhist:
            self.area2d.axis='WSen'
            self.area2d.xlabel = 'time [ka]'
            self.area2d.ylabel = 'residuals [m]'
            self.area2d.image(self.__rsldata,self.__cmap.name)

        if self.plot_1dhist:
            counts = Numeric.sum(self.__rsldata.data,0)
            dx = (self.__rsldata.y_minmax[1]-self.__rsldata.y_minmax[0])/(len(counts)-1)
            bins = Numeric.arange(self.__rsldata.y_minmax[0],self.__rsldata.y_minmax[1]+dx,dx)

            if self.plot_2dhist:
                self.area1d.steps('-W1',counts,bins)
                self.area1d.ur[0] = PyGMT.round_up(self.area1d.ur[0])
                self.area1d.xlabel = 'count'
                self.area1d.axis='wSen'
            else:
                self.area1d.steps('-W1',bins,counts)
                self.area1d.ur[1] = PyGMT.round_up(self.area1d.ur[1])
                self.area1d.xlabel = 'residuals [m]'
                self.area1d.ylabel = 'count'
                self.area1d.axis='WSen'
    def getRSLresiduals(self, rsldb, time=None):
        """Get RSL residuals.

        rsldb: RSL data base
        time: time interval to be processed"""

        hnx = 50
        hny = 50

        # get times
        if time == None:
            t = [self.timeslice(rsldb.mint * self.timescale, "d"), self.timeslice(0.0)]
        else:
            t = [self.timeslice(time[0], "d"), self.timeslice(time[1], "u")]
        times = self.time(t)

        # loop over locations
        res_times = []
        residuals = []
        for loc in rsldb.getLocationRange(self.minmax_long, self.minmax_lat):
            try:
                res = self.get_rslres(rsldb, loc[0])
            except:
                continue
            for i in range(0, len(res[0])):
                res_times.append(res[0][i])
                residuals.append(res[1][i])
        # create histogram
        hist = histogram.histogram2d(hnx, hny)
        hist.set_ranges_uniform(times[0], times[-1], PyGMT.round_down(min(residuals)), PyGMT.round_up(max(residuals)))

        for i in range(0, len(residuals)):
            hist.increment(res_times[i], residuals[i])
        # turn into a grid
        grid = PyGMT.Grid()
        grid.x_minmax = [times[0], times[-1]]
        grid.y_minmax = [PyGMT.round_down(min(residuals)), PyGMT.round_up(max(residuals))]
        grid.data = numpy.zeros([hnx, hny], "f")
        for j in range(0, hny):
            for i in range(0, hnx):
                grid.data[i, j] = hist[i, j]
        return grid
    def setcolourmap(self,vmin=None,vmax=None):
        """Set colourmap for residual plot.

        vmin: minimum value
        vmax: maximum value"""

        if vmin==None:
            v0 = 1
        else:
            v0 = vmin
        if vmax==None:
            v1 = max(Numeric.ravel((self.__rsldata.data)))
        else:
            v1 = vmax

        self.__cmap = tempfile.NamedTemporaryFile(suffix='cpt')
        PyGMT.command('makecpt','-Ccool -T%f/%f/%f -Z > %s'%(v0,v1,(v1-v0),self.__cmap.name))
        self.__cmap.seek(0,2)
        self.__cmap.write('B       255     255     255\n')
        self.__cmap.flush()
    def setcolourmap(self,vmin=None,vmax=None):
        """Set colourmap for residual plot.

        vmin: minimum value
        vmax: maximum value"""

        if vmin==None:
            v0 = 1
        else:
            v0 = vmin
        if vmax==None:
            v1 = max(Numeric.ravel((self.__rsldata.data)))
        else:
            v1 = vmax

        self.__cmap = '.__auto.cpt'
        PyGMT.command('makecpt','-Ccool -T%f/%f/%f -Z > %s'%(v0,v1,(v1-v0),self.__cmap))
        cpt = open(self.__cmap,'a')
        cpt.write('B       255     255     255\n')
        cpt.close()
 def __get_cptfile(self):
     if self.__cptfile == '.__auto.cpt':
         v0 = min(Numeric.ravel(self.var.var))
         v1 = max(Numeric.ravel(self.var.var))
         PyGMT.command('makecpt','-Crainbow -T%f/%f/%f > .__auto.cpt'%(v0,v1,(v1-v0)/10.))
     return self.__cptfile
plot=None
numx = int((opts.papersize[0])/(sizex))
numy = int((opts.papersize[1])/(sizey))
numpages = int(float(numplots-0.1)/float(numx*numy))
p=-1

if opts.options.velocity:
    bvel = infile.getvar('bvel')
    colourmap = PyCF.CFcolourmap(bvel).cptfile
    ctitle = "average velocity [m/a]"
else:
    # create a colour map
    v0 = 0.1
    v1 = 1.
    cmapfile = tempfile.NamedTemporaryFile(suffix='.cpt')
    PyGMT.command('makecpt','-Cjet -T%f/%f/%f > %s'%(v0,v1,(v1-v0)/10.,cmapfile.name))
    cmapfile.seek(0,2)
    cmapfile.write('B       255     255     255\n')
    cmapfile.flush()    
    colourmap = cmapfile.name
    ctitle = "residency"

for i in range(0,numplots):
    if i%(numx*numy)==0:
        # need to open a new plot file
        if plot!=None:
            plot.close()
        if numpages>0:
            p=p+1
            plot = opts.plot(number=p)
        else:
    def plothist(self,var,level=0,clip=None):
        """Plot a colourmap of the difference histogram.

        var: name of variable to be plotted
        level: horizontal slice
        clip: only display data where clip>0.
        """

        fill = -1000000.
        v1 = self.cffile1.getvar(var)
        v2 = self.cffile2.getvar(var)
        if clip in ['topg','thk','usurf'] :
            cv1 = self.cffile1.getvar(clip)
            cv2 = self.cffile2.getvar(clip)
        else:
            cv1 = None
            cv2 = None

        self.ylabel = '%s [%s]'%(v1.long_name,v1.units)

        # find min and max differences
        maxv = -1000000.
        minv = 1000000.

        for t in range(0,self.t1[1]-self.t1[0]):
            diff = v1.get2Dfield(self.t1[0]+t,level=level) - v2.get2Dfield(self.t1[0]+t,level=level)
            if cv1 != None:
                cvar = cv1.get2Dfield(self.t1[0]+t,level=level) + cv2.get2Dfield(self.t1[0]+t,level=level)
                maxv = max(maxv, max(numpy.ravel( numpy.where(cvar > 0. , diff, -1000000.))))
                minv = min(minv, min(numpy.ravel( numpy.where(cvar > 0. , diff, 1000000.))))
            else:
                maxv = max(maxv, max(numpy.ravel(diff)))
                minv = min(minv, min(numpy.ravel(diff)))

        # get data
        hist_grid = numpy.zeros([self.t1[1]-self.t1[0],self.bins],'d')
        for t in range(0,self.t1[1]-self.t1[0]):
            diff = v1.get2Dfield(self.t1[0]+t,level=level) - v2.get2Dfield(self.t1[0]+t,level=level)
            if cv1 != None:
                cvar = cv1.get2Dfield(self.t1[0]+t,level=level) + cv2.get2Dfield(self.t1[0]+t,level=level)
                count = sum(numpy.where(cvar > 0. , 1., 0.).flat)
                diff = numpy.where(cvar > 0. , diff, -1000000.)
            else:
                count = diff.flat.shape[0]
            hist = Scientific.Statistics.Histogram.Histogram(numpy.ravel(diff),self.bins,[minv,maxv])
            if count>0:
                hist_grid[t,:] = hist.array[:,1]/count

        # creating grid
        grid = PyGMT.Grid()
        grid.x_minmax = [self.cffile1.time(self.t1[0]),self.cffile1.time(self.t1[1])]
        grid.y_minmax = [minv,maxv]
        grid.data = numpy.where(hist_grid>0.,hist_grid,-10)

        # creating a colourmap
        min_h = PyGMT.round_down(min(numpy.ravel(hist_grid)))
        max_h = PyGMT.round_up(max(numpy.ravel(hist_grid)))
        self.colourmap = tempfile.NamedTemporaryFile(suffix='.cpt')
        PyGMT.command('makecpt','-Crainbow -Z -T%f/%f/%f > %s'%(min_h,max_h,(max_h-min_h)/10.,self.colourmap.name))
        self.colourmap.seek(0,2)
        self.colourmap.write('B       255     255     255')
        self.colourmap.flush()

        # plotting image
        PyGMT.AutoXY.image(self,grid,self.colourmap.name)

        # and a colourkey
        cm = PyGMT.colourkey(self,self.colourmap.name,pos=[self.size[0]+0.5,0],size=[.75,self.size[1]])
        cffile = opts.cfprofile(fnum)
    else:
        cffile = opts.cffile(fnum)

    times = cffile.time(None)

    key.plot_line(cffile.title,'1/%s'%PyCF.CFcolours[fnum])

    ice_area = cffile.getIceArea()
    ice_vol = cffile.getIceVolume()

    iv.line('-W1/%s'%PyCF.CFcolours[fnum],times,ice_vol)
    ia.line('-W1/%s'%PyCF.CFcolours[fnum],times,ice_area)

    if do_extent:
        interval = int(PyGMT.round_down(len(times)/100.))
        if interval == 0:
            interval = 1
        
        ice_extent = cffile.getExtent(interval=interval)
        ie.line('-W1/%s'%PyCF.CFcolours[fnum],times[::interval],ice_extent)

    if mf != None:
        melt_data = cffile.getFracMelt()
        mf.line('-W1/%s'%PyCF.CFcolours[fnum],times,melt_data)

    if ithick != None:
        mthick =[]
        for i in range(0,len(ice_area)):
            if ice_area[i]>0:
                mthick.append(ice_vol[i]/ice_area[i])
                # insert new profile type into dir
                if id not in profile_data:
                    profile_data[id] = {}
                    profile_data[id]['name'] = string.join(l[4:])
                    profile_data[id]['time'] = []
                    profile_data[id]['duration'] = []
                    profile_data[id]['model_t'] = []
                profile_data[id]['time'].append(float(l[0]))
                profile_data[id]['duration'].append(float(l[1]))
                profile_data[id]['model_t'].append(float(l[3]))
    return profile_data


data = read_profile('glide.profile')

plot = PyGMT.Canvas('profile.ps',size='A4')
plot.defaults['LABEL_FONT_SIZE']='12p'
plot.defaults['ANOT_FONT_SIZE']='10p'

area = PyGMT.AutoXY(plot,size=[18.,10.],pos=[0.,4.])
keyarea = PyGMT.KeyArea(plot,size=[18.,2.])
keyarea.num=[4,4]
i = 0
for id in data.keys():
    area.line('-W1/%s'%Colours[i],data[id]['time'], data[id]['duration'])
    keyarea.plot_line(data[id]['name'],'1/%s'%Colours[i])
    i = i+1
area.finalise()
area.xlabel='total elapsed time [CPU time]'
area.ylabel='duration of operation [CPU time]'
area.axis='WeSn'
Example #13
0
    exp = verif.keys()[0]

    grids = {}
    gn = 0
    for s in verif[exp]:
        for g in verif[exp][s]:
            if g not in grids:
                grids[g] = gn
                gn = gn+1
    print grids
    key_y=2.5
    ysize = 7.
    dy = 1.

    # create plot
    plot = PyGMT.Canvas('blub.ps',size='A4')
    plot.defaults['LABEL_FONT_SIZE']='12p'
    plot.defaults['ANOT_FONT_SIZE']='10p'

    bigarea = PyGMT.AreaXY(plot,size=[30,30])

    bigarea.text([7.5,2*ysize+3*dy+key_y],"Experiment %s"%exp,textargs='20 0 0 CM')

    area_dome = PyGMT.AutoXY(bigarea,pos=[0.,key_y+dy],size=[15,ysize],logx=True)
    area_dome.xlabel = 'time step [a]'
    area_dome.ylabel = 'dome error [m]'
    area_dome.axis = 'WeSn'

    area_max = PyGMT.AutoXY(bigarea,pos=[0.,ysize+2*dy+key_y],size=[15,ysize],logx=True)
    area_max.xlabel = 'time step [a]'
    area_max.ylabel = 'max error [m]'
Example #14
0
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PyGMT 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 PyGMT; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import PyGMT,string
print dir(PyGMT)

l= PyGMT.command('gmtdefaults','-L')
for i in string.split(l,'\n'):
    print i

l = PyGMT.command('mapproject','-R7.000000/49.000000/60.182301/71.915405r -JB33.500000/60.500000/52.833332/68.166664/10',20*'20 50\n')
print len(l)
print l[0:40]

defaults = PyGMT.Defaults()
print defaults.GetCurrentKeys()
defaults['X_ORIGIN'] = '0.c'
print defaults
del defaults['X_ORIGIN']

defaults['X_ORIGIN'] = '0.c'
defaults['Y_ORIGIN'] = '0.c'
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

plot = opts.plot()
plot.defaults['LABEL_FONT_SIZE']='12p'
plot.defaults['ANNOT_FONT_SIZE']='10p'

area = PyCF.CFProfileAreaTS(plot,profile,time=[t0,t1],clip=opts.options.clip,level=level)
if opts.options.profvar != None:
    area.plot_profs(opts.options.profvar)
if opts.options.epoch != None:
    epoch = PyCF.CFEpoch(opts.options.epoch)
    area.plot_epoch(epoch)
area.coordsystem()

if opts.options.dolegend:
    PyGMT.colourkey(areats,profile.colourmap.cptfile,title=profile.long_name,args='-L',pos=[(opts.papersize[0]-10.)/2.,-2.8])

plot.close()

area.axis='wESN'
area.image(btmp,time,clip = 'thk',level=-1)
area.coordsystem()
area.profile(args='-W5/0/0/0')
for i in range(0,len(spots)):
    area.plotsymbol([spots_loc[i][0]],[spots_loc[i][1]],size='0.3',symbol='a',args='-G%s'%PyCF.CFcolours[i])
    area.text(spots_loc[i],'%s'%Labels[i],'12 0 0 MC',comargs='-D0/0.4')
area.stamp(btmp.long_name)

# plot some stats
area = PyGMT.AreaXY(bigarea,pos=[2*(mapheight+deltay)+0.3,ypos],size=[mapheight+0.5,mapheight])
area.text([0.,mapheight],'Ice thickness at divide: %.2fm'%thk.getSpotIJ(divide,time=time),'12 0 0 TL',comargs='-N')
area.text([0.,mapheight-.5],'Basal temp at divide: %.2fC'%btmp.getSpotIJ(divide,time=time,level=-1),'12 0 0 TL',comargs='-N')
area.text([0.,mapheight-1.],'Basal temp at midpnt: %.2fC'%btmp.getSpotIJ(midpoint,time=time,level=-1),'12 0 0 TL',comargs='-N')
# plot colour keys
PyGMT.colourkey(area,thk.colourmap.cptfile,title=thk.long_name,pos=[0,3],size=[mapheight+0.5,0.4])
PyGMT.colourkey(area,btmp.colourmap.cptfile,title=btmp.long_name,pos=[0,1],size=[mapheight+0.5,0.4])

# plot profiles
thk_prof = infile.getprofile('thk')
horiz_prof = infile.getprofile('uvel_avg')
btmp_prof = infile.getprofile('temp')
btmp_prof.pmt=opts.options.pmt

ypos = ypos-3*ProfileHeight-2.
area = PyCF.CFProfileMArea(bigarea,pos=[2.,ypos],size=[Width-3.,ProfileHeight])
area.newprof(horiz_prof,time)
area.newprof(btmp_prof,time,level=-1)
area.newprof(btmp_prof,time)
area.finalise(expandy=True)
area.coordsystem()
if __name__ == '__main__':

    parser = PyCF.CFOptParser()
    parser.width = 12.5
    parser.time()
    parser.plot()
    opts = PyCF.CFOptions(parser,2)

    infile = opts.cffile()
    time = opts.times(infile)

    exact = infile.getvar('thke')
    diff = infile.getvar('thk').getGMTgrid(time)
    diff.data = Numeric.transpose(infile.file.variables['thk'][time,:,:] - infile.file.variables['thke'][time,:,:])

    plot = opts.plot()
    plot.defaults['LABEL_FONT_SIZE']='12p'
    plot.defaults['ANOT_FONT_SIZE']='10p'
    bigarea = PyGMT.AreaXY(plot,size=[30,30])

    area = PyCF.CFArea(bigarea,infile,pos=[0.,3.],size=opts.options.width)
    area.raw_image(infile,time,diff,'../data/error.cpt')
    area.contour(exact,[0.01],'-W2/0/0/0',time)
    area.coordsystem()
    PyGMT.colourkey(area,'../data/error.cpt',title='H@-num@--H@-exact@-',pos=[0.,-1.75],size=[opts.options.width,.75],args='-L')

    bigarea.text([opts.options.width/2.,opts.options.width+4.],"Experiment %s"%infile.title,textargs='20 0 0 CM')

    plot.close()
 def __get_cptfile(self):
     if self.__cptf != None:
         v0 = PyGMT.round_down(min(Numeric.ravel(self.var.var)))
         v1 = PyGMT.round_up(max(Numeric.ravel(self.var.var)))
         PyGMT.command('makecpt','-Crainbow -T%f/%f/%f > %s'%(v0,v1,(v1-v0)/10.,self.__cptfile))
     return self.__cptfile
import PyGMT,PyCF,Numeric,sys

# creating option parser
parser = PyCF.CFOptParser()
parser.width=15.
parser.profile()
parser.time()
parser.plot()
opts = PyCF.CFOptions(parser,-2)

plot = opts.plot()
plot.defaults['LABEL_FONT_SIZE']='12p'
plot.defaults['ANOT_FONT_SIZE']='10p'
bigarea = PyGMT.AreaXY(plot,size=opts.papersize)

area = PyCF.CFProfileMArea(bigarea,pos=[0,1.5],size=[opts.options.width,opts.options.width/5.])
for i in range(0,opts.nfiles):
    infile = opts.cfprofile(i)
    profile = opts.profs(infile)
    time = opts.times(infile,0)
    prof_area = area.newprof(profile,time)
    prof_area.ur=[prof_area.ur[0],4000.]
    prof_area.printinfo(time)

area.finalise(expandy=True)
area.coordsystem()
PyGMT.colourkey(bigarea,profile.colourmap.cptfile,title=profile.long_name,
                pos=[(opts.options.width-10)/2,-2.25],size=[10,0.5],args='-L')

plot.close()
    proj4 = PyCF.getCFProj(proj)
    proj4.setOrigin(origin[0],origin[1])
    proj.false_easting = proj4.params['x_0']
    proj.false_northing = proj4.params['y_0']
    if upper != None:
        u = proj4.proj4(upper)
        num = [int(u[0]/delta[0])+1,int(u[1]/delta[1])+1]
    # projecting topography
    proj_gmt='-J%s/1:1 -R%s -A -D%f/%f'%(
        proj4.getGMTprojection(),
        proj4.getGMTregion([0.,0.],[delta[0]*num[0],delta[1]*num[1]]),
        delta[0],delta[1])

    projfile = tempfile.NamedTemporaryFile(suffix='.bin')
    PyGMT.command('grdproject','%s -G%s=1 %s'%(inname,projfile.name,proj_gmt))

    projtopo = PyGMT.read_grid(projfile.file)
    projfile.close()

    (numx,numy) = projtopo.data.shape    
    
    # creating output netCDF file
    cffile = PyCF.CFcreatefile(outname)
    # global attributes
    if title is not None:
        cffile.title = title
    if institution is not None:
        cffile.institution = institution
    if source  is not None:
        cffile.source = source
def munch_erosion(cfprofile,epochs,etime,yrange=None):
    """Produce erosion surfaces.

    cfprofile: CF file containing erosion.
    epochs: time slices at which to create new polynoms.
    etime: last time slice"""

    time = [0,etime]
    times = cfprofile.time(time)

    seds1 = cfprofile.getprofile('seds1').getProfileTS(time=time).data
    seds2 = cfprofile.getprofile('seds2').getProfileTS(time=time).data
    seds3 = cfprofile.getprofile('seds3').getProfileTS(time=time).data
    
    init_seds = seds1[:,0] + seds2[:,0] + seds3[:,0]
    hb = cfprofile.getprofile('erosion').getProfile(time=etime) - init_seds

    upper_x = Numeric.zeros(len(init_seds)+2,Numeric.Float)
    upper_x[:-2] = Numeric.array(cfprofile.xvalues)
    upper_x[-2] = upper_x[-3]
    upper_x[-1] = upper_x[0]
    lower_x = Numeric.zeros(len(init_seds)+2,Numeric.Float)
    lower_x[2:] = Numeric.array(cfprofile.xvalues)
    lower_x[0] = lower_x[-1]
    lower_x[1] = lower_x[2]

    # loop over time
    for j in range(0,len(seds1[0,:])):
        seds1[:,j] = seds1[:,j] + seds2[:,j] + seds3[:,j] - init_seds[:]

    minseds = PyGMT.round_down(min(hb))
    if yrange!=None:
        minseds = min(minseds,yrange[0])
    maxseds = PyGMT.round_up(max(Numeric.ravel(seds1)))

    upper_y = Numeric.zeros(len(init_seds)+2,Numeric.Float)
    upper_y[-2:] = maxseds
    lower_y = Numeric.zeros(len(init_seds)+2,Numeric.Float)
    lower_y[:2] = minseds

    polygons = []
    colours = []
    stages = []
    # initial sediment distribution
    polygons.append( Polygon.Polygon( Numeric.transpose(Numeric.array([lower_x,lower_y])) ) )
    colours.append('255/255/0')
    stages.append('orig seds')
    current_epoch = epochs.get_epoch(times[0])
    for j in range(0,len(seds1[0,:])):
        e = epochs.get_epoch(times[j])
        if e != current_epoch:
            # add a new stage
            lower_y[2:] = seds1[:,j]
            polygons.append( Polygon.Polygon( Numeric.transpose(Numeric.array([lower_x,lower_y])) ) )
            current_epoch = e
            colours.append(epochs.get_colour(times[j]))
            stages.append(current_epoch)
        
        upper_y[:-2] = seds1[:,j]
        upoly = Polygon.Polygon( Numeric.transpose(Numeric.array([upper_x,upper_y])) )
        for p in range(0,len(polygons)):
            polygons[p] = polygons[p] - upoly

    # hard bedrock erosion
    lower_y[2:] = hb[:]
    polygons.insert(0, Polygon.Polygon( Numeric.transpose(Numeric.array([lower_x,lower_y])) ) )
    colours.insert(0, '202/119/74')
    stages.insert(0, 'Bedrock')

    coords = []
    for p in range(0,len(polygons)):
        c = []
        for i in range(0,len(polygons[p])):
            c.append({'x':[],'y':[]})
            for j in range(0,len(polygons[p][i])):
                c[i]['x'].append(polygons[p][i][j][0])
                c[i]['y'].append(polygons[p][i][j][1])
        coords.append(c)
        
    return (coords,colours,stages)
            pass
        if parser.profile!=None:
            area.profile(args='-W5/0/0/0')
        area.axis='wesn'
        area.coordsystem()
        area.printinfo(time)
else:
    plot = opts.plot()
    area = PyCF.CFArea(plot,infile,pos=[0.,3.],size=sizex-deltax)
    if opts.options.land:
        area.land(time)
    area.image(var,time,clip = opts.options.clip,level=level,mono=opts.options.mono)
    if var.name=="vel":
        area.velocity_field(time,level=level)
    area.coastline()
    try:
        thk = infile.getvar('thk')
        area.contour(thk,[0.1],'-W2/0/0/0',time)
    except:
        pass
    if var.name == 'is' or var.name == 'thk':
        area.contour(var,[500,1000,2500,3000],'-W1/255/255/255',time)
    if parser.profile!=None:
        area.profile(args='-W5/0/0/0')
    area.coordsystem()
    area.printinfo(time)
    if opts.options.dolegend:
        PyGMT.colourkey(area,var.colourmap.cptfile,title=var.long_name,pos=[0,-2])
    
plot.close()
plot=None
numx = int((opts.papersize[0])/(sizex))
numy = int((opts.papersize[1])/(sizey))
numpages = int(float(numplots-0.1)/float(numx*numy))
p=-1

if opts.options.velocity:
    bvel = infile.getvar('bvel')
    colourmap = PyCF.CFcolourmap(bvel).cptfile
    ctitle = "average velocity [m/a]"
else:
    # create a colour map
    v0 = 0.1
    v1 = 1.
    PyGMT.command('makecpt','-Cjet -T%f/%f/%f > .__auto.cpt'%(v0,v1,(v1-v0)/10.))
    cpt = open('.__auto.cpt','a')
    cpt.write('B       255     255     255\n')
    cpt.close()    
    colourmap = '.__auto.cpt'
    ctitle = "residency"

for i in range(0,numplots):
    if i%(numx*numy)==0:
        # need to open a new plot file
        if plot!=None:
            plot.close()
        if numpages>0:
            p=p+1
            plot = opts.plot(number=p)
        else: