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 | # personal librairies |
---|
15 | import ppcompute |
---|
16 | ############################################### |
---|
17 | |
---|
18 | ################################# |
---|
19 | # global variables and settings # |
---|
20 | ################################# |
---|
21 | |
---|
22 | # matplotlib settings |
---|
23 | # http://matplotlib.org/users/customizing.html |
---|
24 | # ------------------------------- |
---|
25 | mpl.rcParams['font.family'] = "serif" |
---|
26 | mpl.rcParams['axes.color_cycle'] = "r,g,b,k" |
---|
27 | mpl.rcParams['contour.negative_linestyle'] = "dashed" |
---|
28 | mpl.rcParams['verbose.level'] = "silent" |
---|
29 | mpl.rcParams['lines.linewidth'] = 1.5 |
---|
30 | mpl.rcParams['lines.markersize'] = 10 |
---|
31 | mpl.rcParams['xtick.major.pad'] = 10 |
---|
32 | mpl.rcParams['ytick.major.pad'] = 10 |
---|
33 | |
---|
34 | # global variables |
---|
35 | # ------------------------------- |
---|
36 | # - where settings files are located |
---|
37 | # (None means planetoplot_v2 in PYTHONPATH) |
---|
38 | whereset = None |
---|
39 | # - some good default settings. |
---|
40 | # (bounds) |
---|
41 | how_many_sigma = 3.0 |
---|
42 | # (contours) |
---|
43 | ccol = 'black' |
---|
44 | cline = 0.55 |
---|
45 | # (vectors) |
---|
46 | widthvec = 0.002 |
---|
47 | reducevec = 30. |
---|
48 | # (colorbar) |
---|
49 | zeorientation="vertical" |
---|
50 | zefrac = 0.05 |
---|
51 | # (save figures) |
---|
52 | pad_inches_value=0.25 |
---|
53 | ############################################### |
---|
54 | |
---|
55 | ########################## |
---|
56 | # executed when imported # |
---|
57 | ########################## |
---|
58 | ########################################### |
---|
59 | # we load user-defined automatic settings # |
---|
60 | ########################################### |
---|
61 | # initialize the warning variable about file not present... |
---|
62 | files_not_present = "" |
---|
63 | # ... and the whereset variable |
---|
64 | whereset = ppcompute.findset(whereset) |
---|
65 | |
---|
66 | # - variable settings |
---|
67 | # ------------------------------- |
---|
68 | zefile = "set_var.txt" |
---|
69 | vf = {} ; vc = {} ; vl = {} |
---|
70 | try: |
---|
71 | f = open(whereset+zefile, 'r') |
---|
72 | for line in f: |
---|
73 | if "#" in line: pass |
---|
74 | else: |
---|
75 | var, format, colorb, label = line.strip().split(';') |
---|
76 | ind = var.strip() |
---|
77 | vf[ind] = format.strip() |
---|
78 | vc[ind] = colorb.strip() |
---|
79 | vl[ind] = label.strip() |
---|
80 | f.close() |
---|
81 | except IOError: |
---|
82 | files_not_present = files_not_present + zefile + " " |
---|
83 | |
---|
84 | ## - file settings |
---|
85 | ## ------------------------------- |
---|
86 | #zefile = "set_file.txt" |
---|
87 | #prefix_t = {} ; suffix_t = {} ; name_t = {} ; proj_t = {} ; vecx_t = {} ; vecy_t = {} |
---|
88 | #try: |
---|
89 | # f = open(whereset+zefile, 'r') |
---|
90 | # for line in f: |
---|
91 | # if "#" in line: pass |
---|
92 | # else: |
---|
93 | # prefix, suffix, name, proj, vecx, vecy = line.strip().split(';') |
---|
94 | # ind = name.strip() |
---|
95 | # prefix_t[ind] = prefix.strip() |
---|
96 | # suffix_t[ind] = suffix.strip() |
---|
97 | # #name_t[ind] = name.strip() |
---|
98 | # proj_t[ind] = proj.strip() |
---|
99 | # vecx_t[ind] = vecx.strip() |
---|
100 | # vecy_t[ind] = vecy.strip() |
---|
101 | # f.close() |
---|
102 | #except IOError: |
---|
103 | # files_not_present = files_not_present + zefile + " " |
---|
104 | |
---|
105 | # - multiplot settings |
---|
106 | # ------------------------------- |
---|
107 | zefile = "set_multiplot.txt" |
---|
108 | subv_t = {} ; subh_t = {} ; wspace_t = {} ; hspace_t = {} ; font_t = {} |
---|
109 | try: |
---|
110 | f = open(whereset+zefile, 'r') |
---|
111 | for line in f: |
---|
112 | if "#" in line: pass |
---|
113 | else: |
---|
114 | num, subv, subh, wspace, hspace, font = line.strip().split(';') |
---|
115 | ind = int(num.strip()) |
---|
116 | subv_t[ind] = int(subv.strip()) |
---|
117 | subh_t[ind] = int(subh.strip()) |
---|
118 | wspace_t[ind] = float(wspace.strip()) |
---|
119 | hspace_t[ind] = float(hspace.strip()) |
---|
120 | font_t[ind] = float(font.strip()) |
---|
121 | f.close() |
---|
122 | except IOError: |
---|
123 | files_not_present = files_not_present + zefile + " " |
---|
124 | |
---|
125 | # - background settings |
---|
126 | # ------------------------------- |
---|
127 | zefile = "set_back.txt" |
---|
128 | back = {} |
---|
129 | try: |
---|
130 | f = open(whereset+zefile, 'r') |
---|
131 | for line in f: |
---|
132 | if "#" in line: pass |
---|
133 | else: |
---|
134 | name, link = line.strip().split(';') |
---|
135 | ind = name.strip() |
---|
136 | back[ind] = link.strip() |
---|
137 | f.close() |
---|
138 | except IOError: |
---|
139 | files_not_present = files_not_present + zefile + " " |
---|
140 | |
---|
141 | # - area settings |
---|
142 | # ------------------------------- |
---|
143 | zefile = "set_area.txt" |
---|
144 | area = {} |
---|
145 | try: |
---|
146 | f = open(whereset+zefile, 'r') |
---|
147 | for line in f: |
---|
148 | if "#" in line: pass |
---|
149 | else: |
---|
150 | name, wlat1, wlat2, wlon1, wlon2 = line.strip().split(';') |
---|
151 | area[name.strip()] = [[float(wlon1.strip()),float(wlon2.strip())],\ |
---|
152 | [float(wlat1.strip()),float(wlat2.strip())]] |
---|
153 | f.close() |
---|
154 | except IOError: |
---|
155 | files_not_present = files_not_present + zefile + " " |
---|
156 | # A note to the user about missing files |
---|
157 | if files_not_present != "": |
---|
158 | print "warning: files "+files_not_present+" not in "+whereset+" ; those presets will be missing" |
---|
159 | |
---|
160 | # TBD: should change vector color with colormaps |
---|
161 | #"gist_heat": "white",\ |
---|
162 | #"hot": "white",\ |
---|
163 | #"gray": "red",\ |
---|
164 | |
---|
165 | #################### |
---|
166 | # useful functions # |
---|
167 | #################### |
---|
168 | |
---|
169 | # a function to define subplot |
---|
170 | # ... user can change settings in set_multiplot.txt read above |
---|
171 | # ------------------------------- |
---|
172 | def definesubplot(numplot, fig): |
---|
173 | try: |
---|
174 | mpl.rcParams['font.size'] = font_t[numplot] |
---|
175 | except: |
---|
176 | mpl.rcParams['font.size'] = 18 |
---|
177 | try: |
---|
178 | fig.subplots_adjust(wspace = wspace_t[numplot], hspace = hspace_t[numplot]) |
---|
179 | subv, subh = subv_t[numplot],subh_t[numplot] |
---|
180 | except: |
---|
181 | print "!! WARNING !! no preset found from set_multiplot.txt, or this setting file was not found." |
---|
182 | subv = 1 ; subh = numplot |
---|
183 | return subv,subh |
---|
184 | |
---|
185 | # a function to calculate automatically bounds (or simply prescribe those) |
---|
186 | # ------------------------------- |
---|
187 | def calculate_bounds(field,vmin=None,vmax=None): |
---|
188 | # prescribed cases first |
---|
189 | zevmin = vmin |
---|
190 | zevmax = vmax |
---|
191 | # computed cases |
---|
192 | if zevmin is None or zevmax is None: |
---|
193 | # select values |
---|
194 | ind = np.where(field < 9e+35) |
---|
195 | fieldcalc = field[ ind ] # field must be a numpy array |
---|
196 | # calculate stdev and mean |
---|
197 | dev = np.std(fieldcalc)*how_many_sigma |
---|
198 | damean = ppcompute.mean(fieldcalc) |
---|
199 | # fill min/max if needed |
---|
200 | if vmin is None: zevmin = damean - dev |
---|
201 | if vmax is None: zevmax = damean + dev |
---|
202 | # special case: negative values with stddev while field is positive |
---|
203 | if zevmin < 0. and ppcompute.min(fieldcalc) > 0.: zevmin = 0. |
---|
204 | return zevmin, zevmax |
---|
205 | #### treat vmin = vmax for continuity |
---|
206 | #if vmin == vmax: zevmin = damean - dev ; zevmax = damean + dev |
---|
207 | |
---|
208 | # a function to solve the problem with blank bounds ! |
---|
209 | # ------------------------------- |
---|
210 | def bounds(what_I_plot,zevmin,zevmax,miss=9e+35): |
---|
211 | small_enough = 1.e-7 |
---|
212 | if zevmin < 0: what_I_plot[ what_I_plot < zevmin*(1.-small_enough) ] = zevmin*(1.-small_enough) |
---|
213 | else: what_I_plot[ what_I_plot < zevmin*(1.+small_enough) ] = zevmin*(1.+small_enough) |
---|
214 | what_I_plot[ what_I_plot > miss ] = -miss |
---|
215 | what_I_plot[ what_I_plot > zevmax ] = zevmax*(1.-small_enough) |
---|
216 | return what_I_plot |
---|
217 | |
---|
218 | # a generic function to show (GUI) or save a plot (PNG,EPS,PDF,...) |
---|
219 | # ------------------------------- |
---|
220 | def save(mode="gui",filename="plot",folder="./",includedate=True,res=150,custom=False): |
---|
221 | # a few settings |
---|
222 | possiblesave = ['eps','ps','svg','png','jpg','pdf'] |
---|
223 | # now the main instructions |
---|
224 | if mode == "gui": |
---|
225 | mpl.show() |
---|
226 | elif mode in possiblesave: |
---|
227 | ## name of plot |
---|
228 | name = folder+'/'+filename |
---|
229 | if includedate: |
---|
230 | for ttt in timelib.gmtime(): |
---|
231 | name = name + "_" + str(ttt) |
---|
232 | name = name +"."+mode |
---|
233 | ## save file |
---|
234 | print "**** Saving file in "+mode+" format... Please wait." |
---|
235 | if not custom: |
---|
236 | # ... regular plots |
---|
237 | mpl.savefig(name,dpi=res,pad_inches=pad_inches_value,bbox_inches='tight') |
---|
238 | else: |
---|
239 | # ... mapping mode, adapted space for labels etc... |
---|
240 | mpl.savefig(name,dpi=res) |
---|
241 | else: |
---|
242 | print "!! ERROR !! File format not supported. Supported: ",possiblesave |
---|
243 | |
---|
244 | ################################## |
---|
245 | # a generic class to make a plot # |
---|
246 | ################################## |
---|
247 | class plot(): |
---|
248 | |
---|
249 | # print out a help string when help is invoked on the object |
---|
250 | # ------------------------------- |
---|
251 | def __repr__(self): |
---|
252 | whatprint = 'plot object. \"help(plot)\" for more information\n' |
---|
253 | return whatprint |
---|
254 | |
---|
255 | # default settings |
---|
256 | # -- user can define settings by two methods. |
---|
257 | # -- 1. yeah = plot2d(title="foo") |
---|
258 | # -- 2. yeah = pp() ; yeah.title = "foo" |
---|
259 | # ------------------------------- |
---|
260 | def __init__(self,\ |
---|
261 | var=None,\ |
---|
262 | field=None,\ |
---|
263 | absc=None,\ |
---|
264 | xlabel="",\ |
---|
265 | ylabel="",\ |
---|
266 | div=20,\ |
---|
267 | logx=False,\ |
---|
268 | logy=False,\ |
---|
269 | swap=False,\ |
---|
270 | swaplab=True,\ |
---|
271 | invert=False,\ |
---|
272 | xcoeff=1.,\ |
---|
273 | ycoeff=1.,\ |
---|
274 | title=""): |
---|
275 | ## what could be defined by the user |
---|
276 | self.var = var |
---|
277 | self.field = field |
---|
278 | self.absc = absc |
---|
279 | self.xlabel = xlabel |
---|
280 | self.ylabel = ylabel |
---|
281 | self.title = title |
---|
282 | self.div = div |
---|
283 | self.logx = logx |
---|
284 | self.logy = logy |
---|
285 | self.swap = swap |
---|
286 | self.swaplab = swaplab # NB: swaplab only used if swap=True |
---|
287 | self.invert = invert |
---|
288 | self.xcoeff = xcoeff |
---|
289 | self.ycoeff = ycoeff |
---|
290 | ## other useful arguments |
---|
291 | ## ... not used here in ppplot but need to be attached to plot object |
---|
292 | self.axisbg = "white" |
---|
293 | self.superpose = False |
---|
294 | |
---|
295 | # check |
---|
296 | # ------------------------------- |
---|
297 | def check(self): |
---|
298 | if self.field is None: print "!! ERROR !! Please define a field to be plotted" ; exit() |
---|
299 | |
---|
300 | # define_from_var |
---|
301 | # ... this uses settings in set_var.txt |
---|
302 | # ------------------------------- |
---|
303 | def define_from_var(self): |
---|
304 | if self.var is not None: |
---|
305 | if self.var.upper() in vl.keys(): |
---|
306 | self.title = vl[self.var.upper()] |
---|
307 | |
---|
308 | # make |
---|
309 | # this is generic to all plots |
---|
310 | # ------------------------------- |
---|
311 | def make(self): |
---|
312 | self.check() |
---|
313 | mpl.xlabel(self.xlabel) |
---|
314 | mpl.ylabel(self.ylabel) |
---|
315 | if self.swap: |
---|
316 | if self.swaplab: |
---|
317 | mpl.xlabel(self.ylabel) |
---|
318 | mpl.ylabel(self.xlabel) |
---|
319 | mpl.title(self.title) |
---|
320 | # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes |
---|
321 | if type(self.field).__name__ in 'MaskedArray': |
---|
322 | self.field[self.field.mask] = self.field.fill_value |
---|
323 | |
---|
324 | ################################ |
---|
325 | # a subclass to make a 1D plot # |
---|
326 | ################################ |
---|
327 | class plot1d(plot): |
---|
328 | |
---|
329 | # print out a help string when help is invoked on the object |
---|
330 | # ------------------------------- |
---|
331 | def __repr__(self): |
---|
332 | whatprint = 'plot1d object. \"help(plot1d)\" for more information\n' |
---|
333 | return whatprint |
---|
334 | |
---|
335 | # default settings |
---|
336 | # -- user can define settings by two methods. |
---|
337 | # -- 1. yeah = plot1d(title="foo") |
---|
338 | # -- 2. yeah = pp() ; yeah.title = "foo" |
---|
339 | # ------------------------------- |
---|
340 | def __init__(self,\ |
---|
341 | lstyle='-',\ |
---|
342 | color='b',\ |
---|
343 | marker='x'): |
---|
344 | ## get initialization from parent class |
---|
345 | plot.__init__(self) |
---|
346 | ## what could be defined by the user |
---|
347 | self.lstyle = lstyle |
---|
348 | self.color = color |
---|
349 | self.marker = marker |
---|
350 | |
---|
351 | # define_from_var |
---|
352 | # ... this uses settings in set_var.txt |
---|
353 | # ------------------------------- |
---|
354 | def define_from_var(self): |
---|
355 | # get what is done in the parent class |
---|
356 | plot.define_from_var(self) |
---|
357 | # add specific stuff |
---|
358 | if self.var is not None: |
---|
359 | if self.var.upper() in vl.keys(): |
---|
360 | self.ylabel = vl[self.var.upper()] |
---|
361 | self.title = "" |
---|
362 | |
---|
363 | # make |
---|
364 | # ------------------------------- |
---|
365 | def make(self): |
---|
366 | # get what is done in the parent class |
---|
367 | plot.make(self) |
---|
368 | # add specific stuff |
---|
369 | mpl.grid(color='grey') |
---|
370 | if self.lstyle == "": self.lstyle = " " # to allow for no line at all with "" |
---|
371 | # swapping if requested |
---|
372 | if self.swap: x = self.field ; y = self.absc |
---|
373 | else: x = self.absc ; y = self.field |
---|
374 | # coefficients on axis |
---|
375 | x=x*self.xcoeff ; y=y*self.ycoeff |
---|
376 | # check axis |
---|
377 | if x.size != y.size: |
---|
378 | print "!! ERROR !! x and y sizes don't match on 1D plot.", x.size, y.size |
---|
379 | exit() |
---|
380 | # make the 1D plot |
---|
381 | # either request linestyle or let matplotlib decide |
---|
382 | if self.lstyle is not None and self.color is not None: |
---|
383 | mpl.plot(x,y,self.color+self.lstyle,marker=self.marker) |
---|
384 | else: |
---|
385 | mpl.plot(x,y,marker=self.marker) |
---|
386 | # make log axes and/or invert ordinate |
---|
387 | # ... this must be after plot so that axis bounds are well-defined |
---|
388 | # ... also inverting must be after making the thing logarithmic |
---|
389 | if self.logx: mpl.semilogx() |
---|
390 | if self.logy: mpl.semilogy() |
---|
391 | if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1]) |
---|
392 | ## TBD: set with .div the number of ticks |
---|
393 | ## TBD: be able to control plot limits |
---|
394 | #ticks = self.div + 1 |
---|
395 | #ax = mpl.gca() |
---|
396 | #ax.get_xaxis().set_ticks(np.linspace(ppcompute.min(x),ppcompute.max(x),ticks/2+1)) |
---|
397 | |
---|
398 | ################################ |
---|
399 | # a subclass to make a 2D plot # |
---|
400 | ################################ |
---|
401 | class plot2d(plot): |
---|
402 | |
---|
403 | # print out a help string when help is invoked on the object |
---|
404 | # ------------------------------- |
---|
405 | def __repr__(self): |
---|
406 | whatprint = 'plot2d object. \"help(plot2d)\" for more information\n' |
---|
407 | return whatprint |
---|
408 | |
---|
409 | # default settings |
---|
410 | # -- user can define settings by two methods. |
---|
411 | # -- 1. yeah = plot2d(title="foo") |
---|
412 | # -- 2. yeah = pp() ; yeah.title = "foo" |
---|
413 | # ------------------------------- |
---|
414 | def __init__(self,\ |
---|
415 | ordi=None,\ |
---|
416 | mapmode=False,\ |
---|
417 | proj="cyl",\ |
---|
418 | back=None,\ |
---|
419 | colorb="jet",\ |
---|
420 | trans=1.0,\ |
---|
421 | addvecx=None,\ |
---|
422 | addvecy=None,\ |
---|
423 | addcontour=None,\ |
---|
424 | fmt="%.2e",\ |
---|
425 | blon=None,\ |
---|
426 | blat=None,\ |
---|
427 | area=None,\ |
---|
428 | vmin=None,\ |
---|
429 | vmax=None,\ |
---|
430 | colorvec="black"): |
---|
431 | ## get initialization from parent class |
---|
432 | plot.__init__(self) |
---|
433 | ## what could be defined by the user |
---|
434 | self.ordi = ordi |
---|
435 | self.mapmode = mapmode |
---|
436 | self.proj = proj |
---|
437 | self.back = back |
---|
438 | self.colorb = colorb |
---|
439 | self.trans = trans |
---|
440 | self.addvecx = addvecx |
---|
441 | self.addvecy = addvecy |
---|
442 | self.colorvec = colorvec |
---|
443 | self.addcontour = addcontour |
---|
444 | self.fmt = fmt |
---|
445 | self.blon = blon ; self.blat = blat |
---|
446 | self.area = area |
---|
447 | self.vmin = vmin ; self.vmax = vmax |
---|
448 | |
---|
449 | # define_from_var |
---|
450 | # ... this uses settings in set_var.txt |
---|
451 | # ------------------------------- |
---|
452 | def define_from_var(self): |
---|
453 | # get what is done in the parent class |
---|
454 | plot.define_from_var(self) |
---|
455 | # add specific stuff |
---|
456 | if self.var is not None: |
---|
457 | if self.var.upper() in vl.keys(): |
---|
458 | self.colorb = vc[self.var.upper()] |
---|
459 | self.fmt = vf[self.var.upper()] |
---|
460 | |
---|
461 | # make |
---|
462 | # ------------------------------- |
---|
463 | def make(self): |
---|
464 | # get what is done in the parent class... |
---|
465 | plot.make(self) |
---|
466 | # ... then add specific stuff |
---|
467 | ############################################################################################ |
---|
468 | ### PRE-SETTINGS |
---|
469 | ############################################################################################ |
---|
470 | # transposing if necessary |
---|
471 | shape = self.field.shape |
---|
472 | if shape[0] != shape[1]: |
---|
473 | if len(self.absc) == shape[0] and len(self.ordi) == shape[1]: |
---|
474 | print "!! WARNING !! Transposing axes" |
---|
475 | self.field = np.transpose(self.field) |
---|
476 | # bound field |
---|
477 | zevmin, zevmax = calculate_bounds(self.field,vmin=self.vmin,vmax=self.vmax) |
---|
478 | what_I_plot = bounds(self.field,zevmin,zevmax) |
---|
479 | # define contour field levels. define color palette |
---|
480 | ticks = self.div + 1 |
---|
481 | zelevels = np.linspace(zevmin,zevmax,ticks) |
---|
482 | palette = get_cmap(name=self.colorb) |
---|
483 | # do the same thing for possible contourline entries |
---|
484 | if self.addcontour is not None: |
---|
485 | # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes |
---|
486 | if type(self.addcontour).__name__ in 'MaskedArray': |
---|
487 | self.addcontour[self.addcontour.mask] = self.addcontour.fill_value |
---|
488 | zevminc, zevmaxc = calculate_bounds(self.addcontour) |
---|
489 | what_I_contour = bounds(self.addcontour,zevminc,zevmaxc) |
---|
490 | ticks = self.div + 1 |
---|
491 | zelevelsc = np.linspace(zevminc,zevmaxc,ticks) |
---|
492 | ############################################################################################ |
---|
493 | ### MAIN PLOT |
---|
494 | ### NB: contour lines are done before contour shades otherwise colorar error |
---|
495 | ############################################################################################ |
---|
496 | if not self.mapmode: |
---|
497 | ## A SIMPLE 2D PLOT |
---|
498 | ################### |
---|
499 | # swapping if requested |
---|
500 | if self.swap: x = self.ordi ; y = self.absc |
---|
501 | else: x = self.absc ; y = self.ordi |
---|
502 | # coefficients on axis |
---|
503 | x=x*self.xcoeff ; y=y*self.ycoeff |
---|
504 | # make shaded and line contours |
---|
505 | if self.addcontour is not None: |
---|
506 | mpl.contour(x, y, what_I_contour, \ |
---|
507 | zelevelsc, colors = ccol, linewidths = cline) |
---|
508 | mpl.contourf(x, y, \ |
---|
509 | self.field, \ |
---|
510 | zelevels, cmap=palette) |
---|
511 | # make log axes and/or invert ordinate |
---|
512 | if self.logx: mpl.semilogx() |
---|
513 | if self.logy: mpl.semilogy() |
---|
514 | if self.invert: ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1]) |
---|
515 | else: |
---|
516 | ## A 2D MAP USING PROJECTIONS (basemap) |
---|
517 | ####################################### |
---|
518 | mpl.xlabel("") ; mpl.ylabel("") |
---|
519 | # additional security in case self.proj is None here |
---|
520 | # ... we set cylindrical projection (the simplest one) |
---|
521 | if self.proj is None: self.proj = "cyl" |
---|
522 | # get lon and lat in 2D version. |
---|
523 | # (but first ensure we do have 2D coordinates) |
---|
524 | if self.absc.ndim == 1: [self.absc,self.ordi] = np.meshgrid(self.absc,self.ordi) |
---|
525 | elif self.absc.ndim > 2: print "!! ERROR !! lon and lat arrays must be 1D or 2D" |
---|
526 | # get lat lon intervals and associated settings |
---|
527 | wlon = [np.min(self.absc),np.max(self.absc)] |
---|
528 | wlat = [np.min(self.ordi),np.max(self.ordi)] |
---|
529 | # -- area presets are in set_area.txt |
---|
530 | if self.area is not None: |
---|
531 | if self.area in area.keys(): |
---|
532 | wlon, wlat = area[self.area] |
---|
533 | # -- settings for meridians and parallels |
---|
534 | steplon = abs(wlon[1]-wlon[0])/6. |
---|
535 | steplat = abs(wlat[1]-wlat[0])/3. |
---|
536 | mertab = np.r_[wlon[0]:wlon[1]:steplon] ; merlab = [0,0,0,1] |
---|
537 | partab = np.r_[wlat[0]:wlat[1]:steplat] ; parlab = [1,0,0,0] |
---|
538 | format = '%.1f' |
---|
539 | # -- center of domain and bounding lats |
---|
540 | lon_0 = 0.5*(wlon[0]+wlon[1]) |
---|
541 | lat_0 = 0.5*(wlat[0]+wlat[1]) |
---|
542 | # some tests, bug fixes, and good-looking settings |
---|
543 | # ... cyl is good for global and regional |
---|
544 | if self.proj == "cyl": |
---|
545 | format = '%.0f' |
---|
546 | # ... global projections |
---|
547 | elif self.proj in ["ortho","moll","robin"]: |
---|
548 | wlat[0] = None ; wlat[1] = None ; wlon[0] = None ; wlon[1] = None |
---|
549 | steplon = 30. ; steplat = 30. |
---|
550 | if self.proj == "robin": steplon = 60. |
---|
551 | mertab = np.r_[-360.:360.:steplon] |
---|
552 | partab = np.r_[-90.:90.:steplat] |
---|
553 | if self.proj == "ortho": |
---|
554 | merlab = [0,0,0,0] ; parlab = [0,0,0,0] |
---|
555 | # in ortho projection, blon and blat can be used to set map center |
---|
556 | if self.blon is not None: lon_0 = self.blon |
---|
557 | if self.blat is not None: lat_0 = self.blat |
---|
558 | elif self.proj == "moll": |
---|
559 | merlab = [0,0,0,0] |
---|
560 | format = '%.0f' |
---|
561 | # ... regional projections |
---|
562 | elif self.proj in ["lcc","laea","merc"]: |
---|
563 | if self.proj in ["lcc","laea"] and wlat[0] == -wlat[1]: |
---|
564 | print "!! ERROR !! with Lambert lat1 must be different than lat2" ; exit() |
---|
565 | if wlat[0] < -80. and wlat[1] > 80.: |
---|
566 | print "!! ERROR !! set an area (not global)" ; exit() |
---|
567 | format = '%.0f' |
---|
568 | elif self.proj in ["npstere","spstere"]: |
---|
569 | # in polar projections, blat gives the bounding lat |
---|
570 | # if not set, set something reasonable |
---|
571 | if self.blat is None: self.blat = 60. |
---|
572 | # help the user who forgets self.blat would better be negative in spstere |
---|
573 | # (this actually serves for the default setting just above) |
---|
574 | if self.proj == "spstere" and self.blat > 0: self.blat = -self.blat |
---|
575 | # ... unsupported projections |
---|
576 | else: |
---|
577 | print "!! ERROR !! unsupported projection. supported: "+\ |
---|
578 | "cyl, npstere, spstere, ortho, moll, robin, lcc, laea, merc" |
---|
579 | # finally define projection |
---|
580 | m = Basemap(projection=self.proj,\ |
---|
581 | lat_0=lat_0,lon_0=lon_0,\ |
---|
582 | boundinglat=self.blat,\ |
---|
583 | llcrnrlat=wlat[0],urcrnrlat=wlat[1],\ |
---|
584 | llcrnrlon=wlon[0],urcrnrlon=wlon[1]) |
---|
585 | # draw meridians and parallels |
---|
586 | ft = int(mpl.rcParams['font.size']*3./4.) |
---|
587 | m.drawmeridians(mertab,labels=merlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format) |
---|
588 | m.drawparallels(partab,labels=parlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format) |
---|
589 | # define background (see set_back.txt) |
---|
590 | if self.back is not None: |
---|
591 | if self.back in back.keys(): |
---|
592 | print "**** info: loading a background, please wait.",self.back |
---|
593 | if back not in ["coast","sea"]: m.warpimage(back[self.back],scale=0.75) |
---|
594 | elif back == "coast": m.drawcoastlines() |
---|
595 | elif back == "sea": m.drawlsmask(land_color='white',ocean_color='aqua') |
---|
596 | else: |
---|
597 | print "!! ERROR !! requested background not defined. change name or fill in set_back.txt" ; exit() |
---|
598 | # define x and y given the projection |
---|
599 | x, y = m(self.absc, self.ordi) |
---|
600 | # contour field. first line contour then shaded contour. |
---|
601 | if self.addcontour is not None: |
---|
602 | m.contour(x, y, what_I_contour, \ |
---|
603 | zelevelsc, colors = ccol, linewidths = cline) |
---|
604 | m.contourf(x, y, what_I_plot, zelevels, cmap = palette, alpha = self.trans) |
---|
605 | ############################################################################################ |
---|
606 | ### COLORBAR |
---|
607 | ############################################################################################ |
---|
608 | if self.trans > 0.: |
---|
609 | ## draw colorbar. settings are different with projections. or if not mapmode. |
---|
610 | if not self.mapmode: orientation=zeorientation ; frac = 0.075 ; pad = 0.03 |
---|
611 | elif self.proj in ['moll']: orientation="horizontal" ; frac = 0.075 ; pad = 0.03 |
---|
612 | elif self.proj in ['cyl']: orientation="vertical" ; frac = 0.023 ; pad = 0.03 |
---|
613 | else: orientation = zeorientation ; frac = zefrac ; pad = 0.03 |
---|
614 | zelevpal = np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])) |
---|
615 | zecb = mpl.colorbar(fraction=frac,pad=pad,\ |
---|
616 | format=self.fmt,orientation=orientation,\ |
---|
617 | ticks=zelevpal,\ |
---|
618 | extend='neither',spacing='proportional') |
---|
619 | if zeorientation == "horizontal": zecb.ax.set_xlabel(self.title) ; self.title = "" |
---|
620 | ############################################################################################ |
---|
621 | ### VECTORS. must be after the colorbar. we could also leave possibility for streamlines. |
---|
622 | ############################################################################################ |
---|
623 | ### not expecting NaN in self.addvecx and self.addvecy. masked arrays is just enough. |
---|
624 | stride = 3 |
---|
625 | if self.addvecx is not None and self.addvecy is not None and self.mapmode: |
---|
626 | ## for metwinds only ??? |
---|
627 | [vecx,vecy] = m.rotate_vector(self.addvecx,self.addvecy,self.absc,self.ordi) |
---|
628 | # reference vector is scaled |
---|
629 | zescale = ppcompute.mean(np.sqrt(self.addvecx*self.addvecx+self.addvecy*self.addvecy)) |
---|
630 | # make vector field |
---|
631 | q = m.quiver( x[::stride,::stride],y[::stride,::stride],\ |
---|
632 | vecx[::stride,::stride],vecy[::stride,::stride],\ |
---|
633 | angles='xy',color=self.colorvec,pivot='middle',\ |
---|
634 | scale=zescale*reducevec,width=widthvec ) |
---|
635 | # make vector key. default is on upper left corner. |
---|
636 | p = mpl.quiverkey(q,-0.03,1.08,\ |
---|
637 | zescale,str(int(zescale)),\ |
---|
638 | color='black',labelpos='S',labelsep = 0.07) |
---|
639 | #### streamplot!!! avec basemap |
---|