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

Last change on this file since 1014 was 1007, checked in by aslmd, 12 years ago

UTIL PYTHON. various updates on example + mcd + plot scripts. nothing major.

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