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