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