source: trunk/UTIL/PYTHON/planetoplot_v2/ppplot.py @ 997

Last change on this file since 997 was 991, checked in by aslmd, 12 years ago

UTIL PYTHON planetoplot_v2. added --modx to produce a modulo on x labelling (e.g. for local time plots or Ls plots). thanks Tanguy for the request.

File size: 33.2 KB
Line 
1###############################################
2## PLANETOPLOT                               ##
3## --> PPPLOT                                ##
4###############################################
5## Author: Aymeric Spiga. 02-03/2013         ##
6###############################################
7# python built-in librairies
8import time as timelib
9# added librairies
10import numpy as np
11import matplotlib.pyplot as mpl
12from matplotlib.cm import get_cmap
13from mpl_toolkits.basemap import Basemap
14from matplotlib.ticker import FormatStrFormatter,MaxNLocator
15# personal librairies
16import ppcompute
17###############################################
18
19#################################
20# global variables and settings #
21#################################
22
23# matplotlib settings
24# http://matplotlib.org/users/customizing.html
25# -------------------------------
26mpl.rcParams['font.family'] = "serif"
27mpl.rcParams['axes.color_cycle'] = "b,r,g,k"
28mpl.rcParams['contour.negative_linestyle'] = "dashed" # ou "solid"
29mpl.rcParams['verbose.level'] = "silent"
30mpl.rcParams['lines.linewidth'] = 1.5
31mpl.rcParams['lines.markersize'] = 10
32mpl.rcParams['xtick.major.pad'] = 10
33mpl.rcParams['ytick.major.pad'] = 10
34
35# global variables
36# -------------------------------
37# - where settings files are located
38#   (None means planetoplot_v2 in PYTHONPATH)
39whereset = None
40# - some good default settings.
41# (bounds)
42how_many_sigma = 3.0 
43# (contours)
44ccol = 'black'
45cline = 0.55
46# (vectors)
47widthvec = 0.002
48reducevec = 30.
49# (colorbar)
50zeorientation="vertical"
51zefrac = 0.05
52# (save figures)
53pad_inches_value=0.25
54# (negative mode)
55def_negative = False
56###############################################
57
58### settings for 'negative-like' mode
59if def_negative:
60    mpl.rc('figure', facecolor='k', edgecolor='k')
61    mpl.rcParams['text.color'] = 'w'
62    mpl.rc('axes',labelcolor='w',facecolor='k',edgecolor='w')
63    mpl.rcParams['xtick.color'] = 'w'
64    mpl.rcParams['ytick.color'] = 'w'
65    mpl.rcParams['grid.color'] = 'w'
66    mpl.rc('savefig',facecolor='k',edgecolor='k')
67
68##########################
69# executed when imported #
70##########################
71###########################################
72# we load user-defined automatic settings #
73###########################################
74# initialize the warning variable about file not present...
75files_not_present = ""
76# ... and the whereset variable
77whereset = ppcompute.findset(whereset)
78
79# - variable settings
80# -------------------------------
81zefile = "set_var.txt"
82vf = {} ; vc = {} ; vl = {} ; vu = {}
83try: 
84    f = open(whereset+zefile, 'r')
85    for line in f:
86        if "#" in line: pass
87        else:
88            var, format, colorb, label, units = line.strip().split(';')
89            ind = var.strip() 
90            vf[ind] = format.strip()
91            vc[ind] = colorb.strip()
92            vl[ind] = label.strip()
93            vu[ind] = units.strip()
94    f.close()
95except IOError: 
96    files_not_present = files_not_present + zefile + " "
97
98## - file settings
99## -------------------------------
100#zefile = "set_file.txt"
101#prefix_t = {} ; suffix_t = {} ; name_t = {} ; proj_t = {} ; vecx_t = {} ; vecy_t = {}
102#try:
103#    f = open(whereset+zefile, 'r')
104#    for line in f:
105#        if "#" in line: pass
106#        else:
107#            prefix, suffix, name, proj, vecx, vecy = line.strip().split(';')
108#            ind = name.strip()
109#            prefix_t[ind] = prefix.strip()
110#            suffix_t[ind] = suffix.strip()
111#            #name_t[ind] = name.strip()
112#            proj_t[ind] = proj.strip()
113#            vecx_t[ind] = vecx.strip()
114#            vecy_t[ind] = vecy.strip()
115#    f.close()
116#except IOError:
117#    files_not_present = files_not_present + zefile + " "
118
119# - multiplot settings
120# -------------------------------
121zefile = "set_multiplot.txt"
122subv_t = {} ; subh_t = {} ; wspace_t = {} ; hspace_t = {} ; font_t = {}
123try:
124    f = open(whereset+zefile, 'r')
125    for line in f:
126        if "#" in line: pass
127        else:
128            num, subv, subh, wspace, hspace, font = line.strip().split(';')
129            ind = int(num.strip())
130            subv_t[ind] = int(subv.strip())
131            subh_t[ind] = int(subh.strip())
132            wspace_t[ind] = float(wspace.strip())
133            hspace_t[ind] = float(hspace.strip())
134            font_t[ind] = float(font.strip())
135    f.close()
136except IOError:
137    files_not_present = files_not_present + zefile + " "
138
139# - background settings
140# -------------------------------
141zefile = "set_back.txt"
142back = {}
143try:
144    f = open(whereset+zefile, 'r')
145    for line in f:
146        if "#" in line: pass
147        else:
148            name, link = line.strip().split(';')
149            ind = name.strip() 
150            back[ind] = link.strip()
151    f.close()
152except IOError:
153    files_not_present = files_not_present + zefile + " "
154
155# - area settings
156# -------------------------------
157zefile = "set_area.txt"
158area = {}
159try:
160    f = open(whereset+zefile, 'r')
161    for line in f:
162        if "#" in line: pass
163        else:
164            name, wlat1, wlat2, wlon1, wlon2 = line.strip().split(';')
165            area[name.strip()] = [[float(wlon1.strip()),float(wlon2.strip())],\
166                                  [float(wlat1.strip()),float(wlat2.strip())]]
167    f.close()
168except IOError:
169    files_not_present = files_not_present + zefile + " "
170# A note to the user about missing files
171if files_not_present != "":
172    print "warning: files "+files_not_present+" not in "+whereset+" ; those presets will be missing"
173
174# TBD: should change vector color with colormaps
175#"gist_heat":    "white",\
176#"hot":          "white",\
177#"gray":         "red",\
178
179####################
180# useful functions #
181####################
182
183# a function to change color lines according to a color map (idea by A. Pottier)
184# ... two optional arguments: color maps + a number telling how much intervals are needed
185def rainbow(cb="jet",num=8):
186    ax = mpl.gca()
187    pal = mpl.cm.get_cmap(name=cb)
188    ax._get_lines.set_color_cycle([pal(i) for i in np.linspace(0,0.9,num)])
189
190# a function to define subplot
191# ... user can change settings in set_multiplot.txt read above
192# -------------------------------
193def definesubplot(numplot, fig):
194    try: 
195        mpl.rcParams['font.size'] = font_t[numplot]
196    except: 
197        mpl.rcParams['font.size'] = 18
198    try: 
199        fig.subplots_adjust(wspace = wspace_t[numplot], hspace = hspace_t[numplot])
200        subv, subh = subv_t[numplot],subh_t[numplot]
201    except: 
202        print "!! WARNING !! no preset found from set_multiplot.txt, or this setting file was not found."
203        subv = 1 ; subh = numplot
204    return subv,subh
205
206# a function to calculate automatically bounds (or simply prescribe those)
207# -------------------------------
208def calculate_bounds(field,vmin=None,vmax=None):
209    # prescribed cases first
210    zevmin = vmin
211    zevmax = vmax
212    # computed cases
213    if zevmin is None or zevmax is None:
214       # select values
215       ind = np.where(field < 9e+35)
216       fieldcalc = field[ ind ] # field must be a numpy array
217       # calculate stdev and mean
218       dev = np.std(fieldcalc)*how_many_sigma
219       damean = ppcompute.mean(fieldcalc)
220       # fill min/max if needed
221       if vmin is None: zevmin = damean - dev
222       if vmax is None: zevmax = damean + dev
223       # special case: negative values with stddev while field is positive
224       if zevmin < 0. and ppcompute.min(fieldcalc) >= 0.: zevmin = 0.
225    # check that bounds are not too tight given the field
226    amin = ppcompute.min(field)
227    amax = ppcompute.max(field)
228    if np.abs(amin) < 1.e-15: 
229        cmin = 0.
230    else:
231        cmin = 100.*np.abs((amin - zevmin)/amin)
232    cmax = 100.*np.abs((amax - zevmax)/amax)
233    if cmin > 150. or cmax > 150.:
234        print "!! WARNING !! Bounds are a bit too tight. Might need to reconsider those."
235        print "!! WARNING !! --> actual",amin,amax,"adopted",zevmin,zevmax
236    return zevmin, zevmax   
237    #### treat vmin = vmax for continuity
238    #if vmin == vmax:  zevmin = damean - dev ; zevmax = damean + dev
239
240# a function to solve the problem with blank bounds !
241# -------------------------------
242def bounds(what_I_plot,zevmin,zevmax,miss=9e+35):
243    small_enough = 1.e-7
244    if zevmin < 0: what_I_plot[ what_I_plot < zevmin*(1.-small_enough) ] = zevmin*(1.-small_enough)
245    else:          what_I_plot[ what_I_plot < zevmin*(1.+small_enough) ] = zevmin*(1.+small_enough)
246    what_I_plot[ what_I_plot > miss  ] = -miss
247    what_I_plot[ what_I_plot > zevmax ] = zevmax*(1.-small_enough)
248    return what_I_plot
249
250# a function to change labels with modulo
251# ---------------------------------------
252def labelmodulo(ax,mod):
253    mpl.draw()
254    strtab = []
255    for tick in ax.get_xaxis().get_ticklabels():
256        num = float(tick.get_text())
257        strtab.append(num % mod)
258    ax.get_xaxis().set_ticklabels(strtab)
259    return ax
260
261# a function to output an ascii file
262# ----------------------------------
263def writeascii (field=None,absc=None,name=None):
264    if name is None:
265        name = "prof"
266        for ttt in timelib.gmtime():
267            name = name + "_" + str(ttt)
268    if field is None or absc is None:
269        print "!! WARNING !! Not printing the file, incorrect field or absc."
270    else:
271        if field.ndim == 1:
272            myfile = open(name, 'w')
273            for ix in range(len(absc)):
274                myfile.write("%15.5e%15.5e\n" % ( absc[ix], field[ix] ))
275            myfile.close()
276        else:
277            print "!! WARNING !! Not printing the file, 2D fields not supported yet."
278    return
279
280# a generic function to show (GUI) or save a plot (PNG,EPS,PDF,...)
281# -------------------------------
282def save(mode="gui",filename="plot",folder="./",includedate=True,res=150,custom=False):
283    if mode != "nothing":
284      # a few settings
285      possiblesave = ['eps','ps','svg','png','jpg','pdf'] 
286      # now the main instructions
287      if mode == "gui": 
288          mpl.show()
289      elif mode in possiblesave:
290          ## name of plot
291          name = folder+'/'+filename
292          if includedate:
293              for ttt in timelib.gmtime():
294                  name = name + "_" + str(ttt)
295          name = name +"."+mode
296          ## save file
297          print "**** Saving file in "+mode+" format... Please wait."
298          if not custom:
299              # ... regular plots
300              mpl.savefig(name,dpi=res,pad_inches=pad_inches_value,bbox_inches='tight')
301          else:
302              # ... mapping mode, adapted space for labels etc...
303              mpl.savefig(name,dpi=res)
304      else:
305          print "!! ERROR !! File format not supported. Supported: ",possiblesave
306
307##################################
308# a generic class to make a plot #
309##################################
310class plot():
311
312    # print out a help string when help is invoked on the object
313    # -------------------------------
314    def __repr__(self):
315        whatprint = 'plot object. \"help(plot)\" for more information\n'
316        return whatprint
317
318    # default settings
319    # -- user can define settings by two methods.
320    # -- 1. yeah = plot2d(title="foo")
321    # -- 2. yeah = pp() ; yeah.title = "foo"
322    # -------------------------------
323    def __init__(self,\
324                 var=None,\
325                 field=None,\
326                 absc=None,\
327                 xlabel="",\
328                 ylabel="",\
329                 div=20,\
330                 logx=False,\
331                 logy=False,\
332                 swap=False,\
333                 swaplab=True,\
334                 invert=False,\
335                 xcoeff=1.,\
336                 ycoeff=1.,\
337                 fmt=None,\
338                 colorb="jet",\
339                 units="",\
340                 modx=None,\
341                 title=""):
342        ## what could be defined by the user
343        self.var = var
344        self.field = field
345        self.absc = absc
346        self.xlabel = xlabel
347        self.ylabel = ylabel
348        self.title = title
349        self.div = div
350        self.logx = logx
351        self.logy = logy
352        self.swap = swap
353        self.swaplab = swaplab # NB: swaplab only used if swap=True
354        self.invert = invert
355        self.xcoeff = xcoeff
356        self.ycoeff = ycoeff
357        self.fmt = fmt
358        self.units = units
359        self.colorb = colorb
360        self.modx = modx
361        ## other useful arguments
362        ## ... not used here in ppplot but need to be attached to plot object
363        self.axisbg = "white"
364        self.superpose = False
365
366    # check
367    # -------------------------------
368    def check(self):
369        if self.field is None: print "!! ERROR !! Please define a field to be plotted" ; exit()
370
371    # define_from_var
372    # ... this uses settings in set_var.txt
373    # -------------------------------
374    def define_from_var(self):
375        if self.var is not None:
376         if self.var.upper() in vl.keys():
377          self.title = vl[self.var.upper()]
378          self.units = vu[self.var.upper()]
379
380    # make
381    # this is generic to all plots
382    # -------------------------------
383    def make(self):
384        self.check()
385        # labels, title, etc...
386        mpl.xlabel(self.xlabel)
387        mpl.ylabel(self.ylabel)
388        if self.swap:
389         if self.swaplab:
390           mpl.xlabel(self.ylabel)
391           mpl.ylabel(self.xlabel)
392        mpl.title(self.title)
393        # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
394        if type(self.field).__name__ in 'MaskedArray':
395            self.field[self.field.mask] = self.field.fill_value
396
397################################
398# a subclass to make a 1D plot #
399################################
400class plot1d(plot):
401
402    # print out a help string when help is invoked on the object
403    # -------------------------------
404    def __repr__(self):
405        whatprint = 'plot1d object. \"help(plot1d)\" for more information\n'
406        return whatprint
407
408    # default settings
409    # -- user can define settings by two methods.
410    # -- 1. yeah = plot1d(title="foo")
411    # -- 2. yeah = pp() ; yeah.title = "foo"
412    # -------------------------------
413    def __init__(self,\
414                 lstyle=None,\
415                 color=None,\
416                 marker='x',\
417                 label=None):
418        ## get initialization from parent class
419        plot.__init__(self)
420        ## what could be defined by the user
421        self.lstyle = lstyle
422        self.color = color
423        self.marker = marker
424        self.label = label
425        self.xmin = None
426        self.ymin = None
427        self.xmax = None
428        self.ymax = None
429
430    # define_from_var
431    # ... this uses settings in set_var.txt
432    # -------------------------------
433    def define_from_var(self):
434        # get what is done in the parent class
435        plot.define_from_var(self)
436        # add specific stuff
437        if self.var is not None:
438         if self.var.upper() in vl.keys():
439          self.ylabel = vl[self.var.upper()] + " (" + vu[self.var.upper()] + ")"
440          self.title = ""
441          self.fmt = vf[self.var.upper()]
442
443    # make
444    # -------------------------------
445    def make(self):
446        # get what is done in the parent class
447        plot.make(self)
448        if self.fmt is None: self.fmt = '%.0f'
449        # add specific stuff
450        mpl.grid(color='grey')
451        if self.lstyle == "": self.lstyle = " " # to allow for no line at all with ""
452        # set dummy x axis if not defined
453        if self.absc is None: 
454            self.absc = np.array(range(self.field.shape[0]))
455            print "!! WARNING !! dummy coordinates on x axis"
456        # swapping if requested
457        if self.swap:  x = self.field ; y = self.absc
458        else:          x = self.absc ; y = self.field
459        # coefficients on axis
460        x=x*self.xcoeff ; y=y*self.ycoeff
461        # check axis
462        if x.size != y.size:
463            print "!! ERROR !! x and y sizes don't match on 1D plot.", x.size, y.size
464            exit()
465        # make the 1D plot
466        # either request linestyle or let matplotlib decide
467        if self.lstyle is not None and self.color is not None:
468            mpl.plot(x,y,self.color+self.lstyle,marker=self.marker,label=self.label)
469        elif self.color is not None:
470            mpl.plot(x,y,color=self.color,marker=self.marker,label=self.label)
471        elif self.lstyle is not None:
472            mpl.plot(x,y,linestyle=self.lstyle,marker=self.marker,label=self.label)
473        else:
474            mpl.plot(x,y,marker=self.marker,label=self.label)
475        # make log axes and/or invert ordinate
476        # ... this must be after plot so that axis bounds are well-defined
477        # ... also inverting must be after making the thing logarithmic
478        if self.logx: mpl.xscale("log") # not mpl.semilogx() because excludes log on y
479        if self.logy: mpl.yscale("log") # not mpl.semilogy() because excludes log on x
480        if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
481        # add a label for line(s)
482        if self.label is not None:
483            if self.label != "":
484                mpl.legend(loc="best",fancybox=True)
485        # AXES
486        ax = mpl.gca()
487        # format labels
488        if self.swap: ax.xaxis.set_major_formatter(FormatStrFormatter(self.fmt))
489        else: ax.yaxis.set_major_formatter(FormatStrFormatter(self.fmt))
490        # plot limits: ensure that no curve would be outside the window
491        # x-axis
492        x1, x2 = ax.get_xbound()
493        xmin = ppcompute.min(x)
494        xmax = ppcompute.max(x)
495        if xmin < x1: x1 = xmin
496        if xmax > x2: x2 = xmax
497        if self.xmin is not None: x1 = self.xmin
498        if self.xmax is not None: x2 = self.xmax
499        ax.set_xbound(lower=x1,upper=x2)
500        # y-axis
501        y1, y2 = ax.get_ybound()
502        ymin = ppcompute.min(y)
503        ymax = ppcompute.max(y)
504        if ymin < y1: y1 = ymin
505        if ymax > y2: y2 = ymax
506        if self.ymin is not None: y1 = self.ymin
507        if self.ymax is not None: y2 = self.ymax
508        ax.set_ybound(lower=y1,upper=y2)
509        ## set with .div the number of ticks. (is it better than automatic?)
510        if not self.logx:
511            ax.xaxis.set_major_locator(MaxNLocator(self.div/2))
512        else:
513            print "!! WARNING. in logx mode, ticks are set automatically."
514        ## specific modulo labels
515        if self.modx is not None:
516            ax = labelmodulo(ax,self.modx)
517
518################################
519# a subclass to make a 2D plot #
520################################
521class plot2d(plot):
522
523    # print out a help string when help is invoked on the object
524    # -------------------------------
525    def __repr__(self):
526        whatprint = 'plot2d object. \"help(plot2d)\" for more information\n'
527        return whatprint
528
529    # default settings
530    # -- user can define settings by two methods.
531    # -- 1. yeah = plot2d(title="foo")
532    # -- 2. yeah = pp() ; yeah.title = "foo"
533    # -------------------------------
534    def __init__(self,\
535                 ordi=None,\
536                 mapmode=False,\
537                 proj="cyl",\
538                 back=None,\
539                 trans=1.0,\
540                 addvecx=None,\
541                 addvecy=None,\
542                 addcontour=None,\
543                 blon=None,\
544                 blat=None,\
545                 area=None,\
546                 vmin=None,\
547                 vmax=None,\
548                 showcb=True,\
549                 wscale=None,\
550                 stridevecx=1,\
551                 stridevecy=1,\
552                 colorvec="black"):
553        ## get initialization from parent class
554        plot.__init__(self)
555        ## what could be defined by the user
556        self.ordi = ordi
557        self.mapmode = mapmode
558        self.proj = proj
559        self.back = back
560        self.trans = trans
561        self.addvecx = addvecx
562        self.addvecy = addvecy
563        self.colorvec = colorvec
564        self.addcontour = addcontour
565        self.blon = blon ; self.blat = blat
566        self.area = area
567        self.vmin = vmin ; self.vmax = vmax
568        self.showcb = showcb
569        self.wscale = wscale
570        self.stridevecx = stridevecx
571        self.stridevecy = stridevecy
572
573    # define_from_var
574    # ... this uses settings in set_var.txt
575    # -------------------------------
576    def define_from_var(self):
577        # get what is done in the parent class
578        plot.define_from_var(self)
579        # add specific stuff
580        if self.var is not None:
581         if self.var.upper() in vl.keys():
582          self.colorb = vc[self.var.upper()]
583          self.fmt = vf[self.var.upper()]
584
585    # make
586    # -------------------------------
587    def make(self):
588        # get what is done in the parent class...
589        plot.make(self)
590        if self.fmt is None: self.fmt = "%.1e"
591        # ... then add specific stuff
592        ############################################################################################
593        ### PRE-SETTINGS
594        ############################################################################################
595        # set dummy xy axis if not defined
596        if self.absc is None: 
597            self.absc = np.array(range(self.field.shape[0]))
598            self.mapmode = False
599            print "!! WARNING !! dummy coordinates on x axis"
600        if self.ordi is None: 
601            self.ordi = np.array(range(self.field.shape[1]))
602            self.mapmode = False
603            print "!! WARNING !! dummy coordinates on y axis"
604        # transposing if necessary
605        shape = self.field.shape
606        if shape[0] != shape[1]:
607         if len(self.absc) == shape[0] and len(self.ordi) == shape[1]:
608            print "!! WARNING !! Transposing axes"
609            self.field = np.transpose(self.field)
610        # bound field
611        zevmin, zevmax = calculate_bounds(self.field,vmin=self.vmin,vmax=self.vmax)
612        what_I_plot = bounds(self.field,zevmin,zevmax)
613        # define contour field levels. define color palette
614        ticks = self.div + 1
615        zelevels = np.linspace(zevmin,zevmax,ticks)
616        palette = get_cmap(name=self.colorb)
617        # do the same thing for possible contourline entries
618        if self.addcontour is not None:
619            # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
620            if type(self.addcontour).__name__ in 'MaskedArray':
621               self.addcontour[self.addcontour.mask] = self.addcontour.fill_value
622            zevminc, zevmaxc = calculate_bounds(self.addcontour)
623            what_I_contour = bounds(self.addcontour,zevminc,zevmaxc)
624            ticks = self.div + 1
625            zelevelsc = np.linspace(zevminc,zevmaxc,ticks)
626        ############################################################################################
627        ### MAIN PLOT
628        ### NB: contour lines are done before contour shades otherwise colorar error
629        ############################################################################################
630        if not self.mapmode:
631            ## A SIMPLE 2D PLOT
632            ###################
633            # swapping if requested
634            if self.swap:  x = self.ordi ; y = self.absc
635            else:          x = self.absc ; y = self.ordi
636            # coefficients on axis
637            x=x*self.xcoeff ; y=y*self.ycoeff
638            # make shaded and line contours
639            if self.addcontour is not None: 
640                objC = mpl.contour(x, y, what_I_contour, \
641                            zelevelsc, colors = ccol, linewidths = cline)
642                #mpl.clabel(objC, inline=1, fontsize=10)
643            mpl.contourf(x, y, \
644                         self.field, \
645                         zelevels, cmap=palette)
646            # make log axes and/or invert ordinate
647            if self.logx: mpl.semilogx()
648            if self.logy: mpl.semilogy()
649            if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
650        else:
651            ## A 2D MAP USING PROJECTIONS (basemap)
652            #######################################
653            mpl.xlabel("") ; mpl.ylabel("")
654            # additional security in case self.proj is None here
655            # ... we set cylindrical projection (the simplest one)
656            if self.proj is None: self.proj = "cyl"
657            # get lon and lat in 2D version.
658            # (but first ensure we do have 2D coordinates)
659            if self.absc.ndim == 1:     [self.absc,self.ordi] = np.meshgrid(self.absc,self.ordi)
660            elif self.absc.ndim > 2:    print "!! ERROR !! lon and lat arrays must be 1D or 2D"
661            # get lat lon intervals and associated settings
662            wlon = [np.min(self.absc),np.max(self.absc)]
663            wlat = [np.min(self.ordi),np.max(self.ordi)]
664            # -- area presets are in set_area.txt
665            if self.area is not None:
666             if self.area in area.keys():
667                wlon, wlat = area[self.area]
668            # -- settings for meridians and parallels
669            steplon = int(abs(wlon[1]-wlon[0])/6.)
670            steplat = int(abs(wlat[1]-wlat[0])/3.)
671            #mertab = np.r_[wlon[0]:wlon[1]:steplon] ; merlab = [0,0,0,1]
672            #partab = np.r_[wlat[0]:wlat[1]:steplat] ; parlab = [1,0,0,0]
673            mertab = np.r_[-180.:180.:steplon] ; merlab = [0,0,0,1] #-360:360.
674            partab = np.r_[-90.:90.:steplat] ; parlab = [1,0,0,0]
675            format = '%.1f'
676            # -- center of domain and bounding lats
677            lon_0 = 0.5*(wlon[0]+wlon[1])
678            lat_0 = 0.5*(wlat[0]+wlat[1])
679            # some tests, bug fixes, and good-looking settings
680            # ... cyl is good for global and regional
681            if self.proj == "cyl":
682                format = '%.0f'
683            # ... global projections
684            elif self.proj in ["ortho","moll","robin"]:
685                wlat[0] = None ; wlat[1] = None ; wlon[0] = None ; wlon[1] = None
686                steplon = 30. ; steplat = 30.
687                if self.proj in ["robin","moll"]: steplon = 60.
688                mertab = np.r_[-360.:360.:steplon]
689                partab = np.r_[-90.:90.:steplat]
690                if self.proj == "ortho": 
691                    merlab = [0,0,0,0] ; parlab = [0,0,0,0]
692                    # in ortho projection, blon and blat can be used to set map center
693                    if self.blon is not None: lon_0 = self.blon
694                    if self.blat is not None: lat_0 = self.blat
695                elif self.proj == "moll":
696                    merlab = [0,0,0,0]
697                format = '%.0f'
698            # ... regional projections
699            elif self.proj in ["lcc","laea","merc"]:
700                if self.proj in ["lcc","laea"] and wlat[0] == -wlat[1]: 
701                    print "!! ERROR !! with Lambert lat1 must be different than lat2" ; exit()
702                if wlat[0] < -80. and wlat[1] > 80.:
703                    print "!! ERROR !! set an area (not global)" ; exit()
704                format = '%.0f'
705            elif self.proj in ["npstere","spstere"]:
706                # in polar projections, blat gives the bounding lat
707                # if not set, set something reasonable
708                if self.blat is None:   self.blat = 60.
709                # help the user who forgets self.blat would better be negative in spstere
710                # (this actually serves for the default setting just above)
711                if self.proj == "spstere" and self.blat > 0: self.blat = -self.blat
712                # labels
713                mertab = np.r_[-360.:360.:15.]
714                partab = np.r_[-90.:90.:5.]
715            # ... unsupported projections
716            else:
717                print "!! ERROR !! unsupported projection. supported: "+\
718                      "cyl, npstere, spstere, ortho, moll, robin, lcc, laea, merc"
719            # finally define projection
720            m = Basemap(projection=self.proj,\
721                        lat_0=lat_0,lon_0=lon_0,\
722                        boundinglat=self.blat,\
723                        llcrnrlat=wlat[0],urcrnrlat=wlat[1],\
724                        llcrnrlon=wlon[0],urcrnrlon=wlon[1])
725            # draw meridians and parallels
726            ft = int(mpl.rcParams['font.size']*3./4.)
727            zelatmax = 85.
728            m.drawmeridians(mertab,labels=merlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
729            m.drawparallels(partab,labels=parlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
730            # define background (see set_back.txt)
731            if self.back is not None:
732              if self.back in back.keys():
733                 print "**** info: loading a background, please wait.",self.back
734                 if self.back not in ["coast","sea"]:   m.warpimage(back[self.back],scale=0.75)
735                 elif self.back == "coast":             m.drawcoastlines()
736                 elif self.back == "sea":               m.drawlsmask(land_color='white',ocean_color='aqua')
737              else:
738                 print "!! ERROR !! requested background not defined. change name or fill in set_back.txt" ; exit()
739            # define x and y given the projection
740            x, y = m(self.absc, self.ordi)
741            # contour field. first line contour then shaded contour.
742            if self.addcontour is not None: 
743                objC2 = m.contour(x, y, what_I_contour, \
744                            zelevelsc, colors = ccol, linewidths = cline)
745                #mpl.clabel(objC2, inline=1, fontsize=10)
746            m.contourf(x, y, what_I_plot, zelevels, cmap = palette, alpha = self.trans)
747        ############################################################################################
748        ### COLORBAR
749        ############################################################################################
750        if self.trans > 0. and self.showcb:
751            ## draw colorbar. settings are different with projections. or if not mapmode.
752            if not self.mapmode: orientation=zeorientation ; frac = 0.075 ; pad = 0.03 ; lu = 0.5
753            elif self.proj in ['moll']: orientation="horizontal" ; frac = 0.08 ; pad = 0.03 ; lu = 1.0
754            elif self.proj in ['cyl']: orientation="vertical" ; frac = 0.023 ; pad = 0.03 ; lu = 0.5
755            else: orientation = zeorientation ; frac = zefrac ; pad = 0.03 ; lu = 0.5
756            zelevpal = np.linspace(zevmin,zevmax,num=min([ticks/2+1,21]))
757            zecb = mpl.colorbar(fraction=frac,pad=pad,\
758                                format=self.fmt,orientation=orientation,\
759                                ticks=zelevpal,\
760                                extend='neither',spacing='proportional')
761            if zeorientation == "horizontal": zecb.ax.set_xlabel(self.title) ; self.title = ""
762            # colorbar title --> units
763            if self.units not in ["dimless",""]:
764                zecb.ax.set_title("["+self.units+"]",fontsize=3.*mpl.rcParams['font.size']/4.,x=lu,y=1.025)
765
766        ############################################################################################
767        ### VECTORS. must be after the colorbar. we could also leave possibility for streamlines.
768        ############################################################################################
769        ### not expecting NaN in self.addvecx and self.addvecy. masked arrays is just enough.
770        if self.addvecx is not None and self.addvecy is not None: 
771                # vectors on map projection or simple 2D mapping
772                if self.mapmode: [vecx,vecy] = m.rotate_vector(self.addvecx,self.addvecy,self.absc,self.ordi) # for metwinds only ?
773                else: vecx,vecy = self.addvecx,self.addvecy ; x,y = np.meshgrid(x,y)
774                # reference vector is scaled
775                if self.wscale is None: self.wscale = ppcompute.mean(np.sqrt(self.addvecx*self.addvecx+self.addvecy*self.addvecy))
776                # make vector field
777                if self.mapmode: 
778                    q = m.quiver( x[::self.stridevecy,::self.stridevecx],y[::self.stridevecy,::self.stridevecx],\
779                                  vecx[::self.stridevecy,::self.stridevecx],vecy[::self.stridevecy,::self.stridevecx],\
780                                  angles='xy',color=self.colorvec,pivot='tail',\
781                                  scale=self.wscale*reducevec,width=widthvec )
782                else:
783                    q = mpl.quiver( x[::self.stridevecy,::self.stridevecx],y[::self.stridevecy,::self.stridevecx],\
784                                    vecx[::self.stridevecy,::self.stridevecx],vecy[::self.stridevecy,::self.stridevecx],\
785                                    angles='xy',color=self.colorvec,pivot='tail',\
786                                    scale=self.wscale*reducevec,width=widthvec )
787                # make vector key.
788                #keyh = 1.025 ; keyv = 1.05 # upper right corner over colorbar
789                keyh = 0.97 ; keyv = 1.05
790                #keyh = -0.03 ; keyv = 1.08 # upper left corner
791                p = mpl.quiverkey(q,keyh,keyv,\
792                                  self.wscale,str(int(self.wscale)),\
793                                  fontproperties={'size': 'small'},\
794                                  color='black',labelpos='S',labelsep = 0.07)
795        ############################################################################################
796        ### TEXT. ANYWHERE. add_text.txt should be present with lines x ; y ; text ; color
797        ############################################################################################
798        try:
799            f = open("add_text.txt", 'r')
800            for line in f:
801              if "#" in line: pass
802              else:
803                  userx, usery, usert, userc = line.strip().split(';')
804                  userc = userc.strip()
805                  usert = usert.strip()
806                  userx = float(userx.strip())
807                  usery = float(usery.strip())
808                  if self.mapmode: userx,usery = m(userx,usery)
809                  mpl.text(userx,usery,usert,\
810                           color = userc,\
811                           horizontalalignment='center',\
812                           verticalalignment='center')
813            f.close()
814        except IOError:
815            pass
Note: See TracBrowser for help on using the repository browser.