NCCOOS Trac Projects: Top | Web | Platforms | Processing | Viz | Sprints | Sandbox | (Wind)

root/proc2plot/trunk/proc2plot/billymitchell_sodar_plot.py

Revision 455 (checked in by haines, 13 years ago)

Fix SVN locks and update code.

Line 
1 #!/usr/bin/env /opt/env/haines/dataproc/bin/python
2 # Last modified:  Time-stamp: <2010-04-12 13:51:06 haines>
3
4 """billymitchell_sodar_plot"""
5
6 #################################################
7 # [1a] search and replace XXXX with platform id
8 # [1b] search and replace YYYY with sensor id
9 # [1c] search and replace ZZZZ plot titles
10 #################################################
11
12 # plot each month
13
14 import os
15 # import sys, glob, re
16 import datetime, time, dateutil, dateutil.tz
17 import pycdf
18 import numpy
19
20 # sys.path.append('/opt/env/haines/dataproc/raw2proc')
21 # del(sys)
22
23 os.environ["MPLCONFIGDIR"]="/home/haines/.matplotlib/"
24
25 from pylab import figure, twinx, savefig, setp, getp, cm, colorbar
26 from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, DateFormatter, date2num, num2date
27 import procutil
28
29 def timeseries(pi, si, yyyy_mm, plot_type='latest'):
30     print 'billymitchell_sodar1_plot ...'
31
32     #
33
34     prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
35     yyyy_mm_str = this_month.strftime('%Y_%m')
36
37     ################################
38     # [2a] load primary data file
39     ################################
40
41     ncFile1='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+prev_month.strftime('%Y_%m')+'.nc'
42     ncFile2='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+this_month.strftime('%Y_%m')+'.nc'
43
44     have_ncFile1 = os.path.exists(ncFile1)
45     have_ncFile2 = os.path.exists(ncFile2)
46
47     print ' ... loading data for graph from ...'
48     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
49     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
50
51     # open netcdf data
52     if have_ncFile1 and have_ncFile2:
53         try:
54             nc = pycdf.CDFMF((ncFile1, ncFile2))
55         except: # files may have different dimensions
56             nc = pycdf.CDFMF((ncFile2,))
57     elif not have_ncFile1 and have_ncFile2:
58         nc = pycdf.CDFMF((ncFile2,))
59     elif have_ncFile1 and not have_ncFile2:
60         nc = pycdf.CDFMF((ncFile1,))
61     else:
62         print ' ... both files do not exist -- NO DATA LOADED'
63         return
64
65     # ncvars = nc.variables()
66     # print ncvars
67     es = nc.var('time')[:]
68     units = nc.var('time').units
69     dt = [procutil.es2dt(e) for e in es]
70     # set timezone info to UTC (since data from level1 should be in UTC!!)
71     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
72     # return new datetime based on computer local
73     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
74     dn = date2num(dt)
75
76
77     ################################
78     # [2b] specify variables
79     ################################
80     z = nc.var('z')[:]
81     # convert cm/s to m/s
82     uu = nc.var('u')[:]
83     vv = nc.var('v')[:]
84     ww = nc.var('w')[:]
85     sigw = nc.var('sigw')[:]
86     echo = nc.var('bck')[:]
87
88     nc.close()
89
90     # retain original dt for addnan
91     dto = dt
92
93     # last dt in data for labels
94     dtu = dt[-1]
95     dtl = dt_local[-1]
96
97     diff = abs(dtu - dtl)
98     if diff.days>0:
99         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
100     else:
101         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
102                       + dtl.strftime(" on %b %d, %Y")
103
104     #######################################
105     # Plot setup
106     #######################################
107
108     fig = figure(figsize=(10, 10))
109     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
110
111     ax = fig.add_subplot(5,1,1)
112     axs = [ax]
113
114     # range for horizontal wind plots
115     cmin, cmax = (-20., 20.)
116     # print "%s : %g %g" % ('uv wind', cmin, cmax)
117     # use masked array to hide NaN's on plot
118     (dt, uu) = procutil.addnan(dto, uu)
119     dn = date2num(dt)
120     um = numpy.ma.masked_where(numpy.isnan(uu), uu)
121     pc = ax.pcolor(dn, z, um.T, vmin=cmin, vmax=cmax)
122     pc.set_label('True Eastward Wind (m s-1)')
123     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
124     ax.set_ylabel('Height (m)')
125
126     # setup colorbar axes instance.
127     l,b,w,h = ax.get_position().bounds
128     cax = fig.add_axes([l, b+h+0.04, 0.25*w, 0.03])
129
130     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
131     cb.set_label('Wind Velocity (m s-1)')
132     cb.ax.xaxis.set_label_position('top')
133     cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
134     xtl = numpy.round(numpy.linspace(cmin, cmax, 10), decimals=0)
135     cb.ax.set_xticklabels([xtl[1], xtl[3], xtl[5], xtl[7], xtl[9]])
136
137     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
138     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
139     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
140     ax.set_xticklabels([])
141
142     # this only moves the label not the tick labels
143     ax.xaxis.set_label_position('top')
144     ax.set_xlabel('BILLY MITCHELL SODAR -- ' + yyyy_mm_str)
145
146     # right-hand side scale
147     ax2 = twinx(ax)
148     ax2.yaxis.tick_right()
149     # convert (lhs) meters to (rhs) feet
150     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
151     ax2.set_ylim(feet)
152     ax2.set_ylabel('Height (ft)')
153
154     #######################################
155     #
156     ax = fig.add_subplot(5,1,2)
157     axs.append(ax)
158
159     # use masked array to hide NaN's on plot
160     (dt, vv) = procutil.addnan(dto, vv)
161     dn = date2num(dt)
162     vm = numpy.ma.masked_where(numpy.isnan(vv), vv)
163     pc = ax.pcolor(dn, z, vm.T, vmin=cmin, vmax=cmax)
164     pc.set_label('True Northward Wind (m s-1)')
165     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
166     ax.set_ylabel('Height (m)')
167
168     # ax.set_xlim(date2num(dt[0]), date2num(dt[-1]))
169     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
170     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
171     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
172     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
173     ax.set_xticklabels([])
174
175     # right-hand side scale
176     ax2 = twinx(ax)
177     ax2.yaxis.tick_right()
178     # convert (lhs) meters to (rhs) feet
179     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
180     ax2.set_ylim(feet)
181     ax2.set_ylabel('Height (ft)')
182    
183     #######################################
184     #
185     ax = fig.add_subplot(5,1,3)
186     axs.append(ax)
187    
188     # range for horizontal wind plots
189     cmin, cmax = (-2., 2.)
190     # print "%s : %g %g" % ('w wind', cmin, cmax)
191
192     # use masked array to hide NaN's on plot
193     (dt, ww) = procutil.addnan(dto, ww)
194     dn = date2num(dt)
195     wm = numpy.ma.masked_where(numpy.isnan(ww), ww)
196     pc = ax.pcolor(dn, z, wm.T, vmin=cmin, vmax=cmax)
197     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
198     ax.set_ylabel('Height (m)')
199    
200     # setup colorbar axes instance.
201     l,b,w,h = ax.get_position().bounds
202     cax = fig.add_axes([l+0.04, b+h-0.06, 0.25*w, 0.03])
203
204     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
205     cb.set_label('Upward Wind Velocity (m s-1)')
206     cb.ax.xaxis.set_label_position('top')
207     cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
208     xtl = numpy.round(numpy.linspace(cmin, cmax, 10), decimals=0)
209     cb.ax.set_xticklabels([xtl[1], xtl[3], xtl[5], xtl[7], xtl[9]])
210
211     # ax.set_xlim(date2num(dt[0]), date2num(dt[-1]))
212     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
213     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
214     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
215     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
216     ax.set_xticklabels([])
217    
218     # right-hand side scale
219     ax2 = twinx(ax)
220     ax2.yaxis.tick_right()
221     # convert (lhs) meters to (rhs) feet
222     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
223     ax2.set_ylim(feet)
224     ax2.set_ylabel('Height (ft)')
225    
226     #######################################
227     #
228     ax = fig.add_subplot(5,1,4)
229     axs.append(ax)
230    
231     cmin, cmax = (0., 2.)
232     # print "%s : %g %g" % ('sigw', cmin, cmax)
233
234     # use masked array to hide NaN's on plot
235     (dt, sigw) = procutil.addnan(dto, sigw)
236     dn = date2num(dt)
237     sm = numpy.ma.masked_where(numpy.isnan(sigw), sigw)
238     pc = ax.pcolor(dn, z, sm.T, vmin=cmin, vmax=cmax)
239     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
240     ax.set_ylabel('Height (m)')
241
242     # setup colorbar axes instance.
243     l,b,w,h = ax.get_position().bounds
244     cax = fig.add_axes([l+0.04, b+h-0.06, 0.25*w, 0.03])
245
246     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
247     cb.set_label('Std. Dev. of Vertical Wind (m s-1)')
248     cb.ax.xaxis.set_label_position('top')
249     cb.ax.set_xticks([0.0, 0.2, 0.4, 0.6, 0.8])
250     xtl = numpy.round(numpy.linspace(cmin, cmax, 10), decimals=1)
251     cb.ax.set_xticklabels([xtl[0], xtl[2], xtl[4], xtl[6], xtl[8]])
252    
253     # ax.set_xlim(date2num(dt[0]), date2num(dt[-1]))
254     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
255     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
256     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
257     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
258     ax.set_xticklabels([])
259    
260     # right-hand side scale
261     ax2 = twinx(ax)
262     ax2.yaxis.tick_right()
263     # convert (lhs) meters to (rhs) feet
264     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
265     ax2.set_ylim(feet)
266     ax2.set_ylabel('Height (ft)')
267
268     #######################################
269     #
270     ax = fig.add_subplot(5,1,5)
271     axs.append(ax)
272
273    
274     # cmin, cmax = (0., 1000.)
275     cmin, cmax = (2., 6.)
276     # print "%s : %g %g" % ('echo', cmin, cmax)
277
278     # use masked array to hide NaN's on plot
279     (dt, echo) = procutil.addnan(dto, numpy.log10(echo))
280     dn = date2num(dt)
281     em = numpy.ma.masked_where(numpy.isnan(echo), echo)
282     pc = ax.pcolor(dn, z, em.T, vmin=cmin, vmax=cmax)
283     # pc = ax.pcolor(dn, z, em.T)
284     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
285     ax.set_ylabel('Height (m)')
286
287     # setup colorbar axes instance.
288     l,b,w,h = ax.get_position().bounds
289     cax = fig.add_axes([l+0.04, b+h-0.06, 0.25*w, 0.03])
290
291     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
292     cb.set_label('log10 Backscatter')
293     cb.ax.xaxis.set_label_position('top')
294     cb.ax.set_xticks([0.0, 1.0])
295     xtl = numpy.round(numpy.linspace(cmin, cmax, 10), decimals=0)
296     cb.ax.set_xticklabels([str(cmin), str(cmax)])
297    
298     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
299     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
300     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
301     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
302     ax.set_xticklabels([])
303    
304     # right-hand side scale
305     ax2 = twinx(ax)
306     ax2.yaxis.tick_right()
307     # convert (lhs) meters to (rhs) feet
308     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
309     ax2.set_ylim(feet)
310     ax2.set_ylabel('Height (ft)')
311
312     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
313     ax.set_xlabel('BILLY MITCHELL SODAR -- ' + yyyy_mm_str)
314     # save figure
315     
316     # save figure for this month
317     ofn = '/home/haines/rayleigh/img/billymitchell/billymitchell_sodar1_'+yyyy_mm_str+'.png'
318     print '... ... write: %s' % (ofn,)
319     savefig(ofn)
320
321
322     #######################################
323     # Last 30 days
324     #######################################
325     if plot_type=='latest':
326         print ' ... Last 30 days'
327         for idx, ax in enumerate(axs):
328             ax.set_xlim(date2num(dt[-1])-30, date2num(dt[-1]))
329             ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
330             ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
331             ax.set_xticklabels([])
332             if idx==0:
333                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 30 days from ' + last_dt_str)
334             elif idx==len(axs)-1:
335                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
336                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 30 days from ' + last_dt_str)
337
338         savefig('/home/haines/rayleigh/img/billymitchell_sodar1_last30days.png')
339
340
341     #######################################
342     # Last 7 days
343     #######################################
344     if plot_type=='latest':
345         print ' ... Last 7 days'
346         for idx, ax in enumerate(axs):
347             ax.set_xlim(date2num(dt[-1])-7, date2num(dt[-1]))
348             ax.xaxis.set_major_locator( DayLocator(range(0,32,1)) )
349             ax.xaxis.set_minor_locator( HourLocator(range(0,25,6)) )
350             ax.set_xticklabels([])
351             if idx==0:
352                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 7 days from ' + last_dt_str)
353             elif idx==len(axs)-1:
354                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
355                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 7 days from ' + last_dt_str)
356                
357         savefig('/home/haines/rayleigh/img/billymitchell_sodar1_last07days.png')
358
359
360     #######################################
361     # Last 1 day (24hrs)
362     #######################################
363     if plot_type=='latest':
364         print ' ... Last 1 days'
365
366         for idx, ax in enumerate(axs):
367             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
368             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
369             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
370             ax.set_xticklabels([])
371             if idx==0:
372                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 24 hours from ' + last_dt_str)
373             elif idx==len(axs)-1:
374                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
375                 ax.set_xlabel('BILLY MITCHELL SODAR -- Last 24 hours from ' + last_dt_str)
376
377         savefig('/home/haines/rayleigh/img/billymitchell_sodar1_last01days.png')
378
379
380 def wind_vectors(pi, si, yyyy_mm, plot_type='latest'):
381     print 'billymitchell_arrows_plot ...'
382
383     #
384
385     prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
386     yyyy_mm_str = this_month.strftime('%Y_%m')
387
388     ################################
389     # [2a] load primary data file
390     ################################
391
392     ncFile1='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+prev_month.strftime('%Y_%m')+'.nc'
393     ncFile2='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+this_month.strftime('%Y_%m')+'.nc'
394
395     have_ncFile1 = os.path.exists(ncFile1)
396     have_ncFile2 = os.path.exists(ncFile2)
397
398     print ' ... loading data for graph from ...'
399     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
400     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
401
402     # open netcdf data
403     if have_ncFile1 and have_ncFile2:
404         try:
405             nc = pycdf.CDFMF((ncFile1, ncFile2))
406         except: # files may have different dimensions
407             nc = pycdf.CDFMF((ncFile2,))
408     elif not have_ncFile1 and have_ncFile2:
409         nc = pycdf.CDFMF((ncFile2,))
410     elif have_ncFile1 and not have_ncFile2:
411         nc = pycdf.CDFMF((ncFile1,))
412     else:
413         print ' ... both files do not exist -- NO DATA LOADED'
414         return
415
416     # ncvars = nc.variables()
417     # print ncvars
418     es = nc.var('time')[:]
419     units = nc.var('time').units
420     dt = [procutil.es2dt(e) for e in es]
421     # set timezone info to UTC (since data from level1 should be in UTC!!)
422     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
423     # return new datetime based on computer local
424     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
425     dn = date2num(dt)
426
427
428     ################################
429     # [2b] specify variables
430     ################################
431     z = nc.var('z')[:]
432     # convert cm/s to m/s
433     uu = nc.var('u')[:]
434     vv = nc.var('v')[:]
435     ww = nc.var('w')[:]
436     sigw = nc.var('sigw')[:]
437     echo = nc.var('bck')[:]
438
439     nc.close()
440
441     # retain original dt for addnan
442     dto = dt
443
444     # last dt in data for labels
445     dtu = dt[-1]
446     dtl = dt_local[-1]
447
448     diff = abs(dtu - dtl)
449     if diff.days>0:
450         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
451     else:
452         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
453                       + dtl.strftime(" on %b %d, %Y")
454
455     #######################################
456     # Plot setup
457     #######################################
458
459     fig = figure(figsize=(10, 10))
460     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
461
462     ax = fig.add_subplot(1,1,1)
463     axs = [ax]
464
465     # range for horizontal wind plots
466     # cmin, cmax = (0., 20.)
467     # print "%s : %g %g" % ('uv wind', cmin, cmax)
468     # use masked array to hide NaN's on plot
469     (dt, uu) = procutil.addnan(dto, uu)
470     dn = date2num(dt)
471     um = numpy.ma.masked_where(numpy.isnan(uu), uu)
472
473     (dt, vv) = procutil.addnan(dto, vv)
474     vm = numpy.ma.masked_where(numpy.isnan(vv), vv)
475     wspd = numpy.sqrt(um*um + vm*vm)
476
477     X,Y = numpy.meshgrid(dn, z)
478
479     q1 = ax.quiver(X, Y, um.T, vm.T, wspd.T, units='inches', scale=40)
480     qk = ax.quiverkey(q1, 0.1, 0.8, 20, r'20 m s-1')
481    
482     ax.set_ylabel('Height (m)')
483
484     # setup colorbar axes instance.
485     l,b,w,h = ax.get_position().bounds
486     cax = fig.add_axes([l+0.02, b+h-0.06, 0.25*w, 0.03])
487
488     cb = colorbar(q1, cax=cax, orientation='horizontal') # draw colorbar
489     cb.set_label('Wind Velocity (m s-1)')
490
491     # lost control of colorbar ... ???
492     #
493     # cb.ax.xaxis.set_label_position('top')
494     # cb.ax.set_xticks([0.0, 0.5, 1.0])
495     # xtl = numpy.round(numpy.linspace(cmin, cmax, 11), decimals=0)
496     # cb.ax.set_xticklabels([xtl[0], xtl[5], xtl[10]])
497
498     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
499     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
500     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
501     ax.set_xticklabels([])
502
503     # this only moves the label not the tick labels
504     ax.xaxis.set_label_position('bottom')
505     ax.set_xlabel('BILLY MITCHELL Wind Profile -- ' + yyyy_mm_str)
506
507     # right-hand side scale
508     ax2 = twinx(ax)
509     ax2.yaxis.tick_right()
510     # convert (lhs) meters to (rhs) feet
511     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
512     ax2.set_ylim(feet)
513     ax2.set_ylabel('Height (ft)')
514
515    
516
517     #######################################
518     # Last 1 day (24hrs)
519     #######################################
520     if plot_type=='latest':
521         print ' ... Last 1 days'
522
523         for idx, ax in enumerate(axs):
524             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
525             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
526             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
527             ax.set_xticklabels([])
528             if idx==0:
529                 ax.set_xlabel('BILLY MITCHELL Wind Profile -- Last 24 hours from ' + last_dt_str)
530             if idx==len(axs)-1:
531                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
532                 ax.set_xlabel('BILLY MITCHELL Wind Profile -- Last 24 hours from ' + last_dt_str)
533
534         savefig('/home/haines/rayleigh/img/billymitchell_wind_last01days.png')
535
536
537 def wind_barbs(pi, si, yyyy_mm, plot_type='latest'):
538     print 'billymitchell_arrows_plot ...'
539
540     #
541
542     prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
543     yyyy_mm_str = this_month.strftime('%Y_%m')
544
545     ################################
546     # [2a] load primary data file
547     ################################
548
549     ncFile1='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+prev_month.strftime('%Y_%m')+'.nc'
550     ncFile2='/seacoos/data/nccoos/level1/billymitchell/sodar1/billymitchell_sfas_'+this_month.strftime('%Y_%m')+'.nc'
551
552     have_ncFile1 = os.path.exists(ncFile1)
553     have_ncFile2 = os.path.exists(ncFile2)
554
555     print ' ... loading data for graph from ...'
556     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
557     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
558
559     # open netcdf data
560     if have_ncFile1 and have_ncFile2:
561         try:
562             nc = pycdf.CDFMF((ncFile1, ncFile2))
563         except: # files may have different dimensions
564             nc = pycdf.CDFMF((ncFile2,))
565     elif not have_ncFile1 and have_ncFile2:
566         nc = pycdf.CDFMF((ncFile2,))
567     elif have_ncFile1 and not have_ncFile2:
568         nc = pycdf.CDFMF((ncFile1,))
569     else:
570         print ' ... both files do not exist -- NO DATA LOADED'
571         return
572
573     # ncvars = nc.variables()
574     # print ncvars
575     es = nc.var('time')[:]
576     units = nc.var('time').units
577     dt = [procutil.es2dt(e) for e in es]
578     # set timezone info to UTC (since data from level1 should be in UTC!!)
579     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
580     # return new datetime based on computer local
581     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
582     dn = date2num(dt)
583
584
585     ################################
586     # [2b] specify variables
587     ################################
588     z = nc.var('z')[:]
589     # convert cm/s to m/s
590     uu = nc.var('u')[:]
591     vv = nc.var('v')[:]
592     ww = nc.var('w')[:]
593     sigw = nc.var('sigw')[:]
594     echo = nc.var('bck')[:]
595
596     nc.close()
597
598     # retain original dt for addnan
599     dto = dt
600
601     # last dt in data for labels
602     dtu = dt[-1]
603     dtl = dt_local[-1]
604
605     diff = abs(dtu - dtl)
606     if diff.days>0:
607         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
608     else:
609         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
610                       + dtl.strftime(" on %b %d, %Y")
611
612     #######################################
613     # Plot setup
614     #######################################
615
616     fig = figure(figsize=(10, 10))
617     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
618
619     ax = fig.add_subplot(1,1,1)
620     axs = [ax]
621
622     # range for horizontal wind plots
623     # cmin, cmax = (0., 20.)
624     # print "%s : %g %g" % ('uv wind', cmin, cmax)
625     # use masked array to hide NaN's on plot
626     (dt, uu) = procutil.addnan(dto, uu)
627     dn = date2num(dt)
628     um = numpy.ma.masked_where(numpy.isnan(uu), uu)
629
630     (dt, vv) = procutil.addnan(dto, vv)
631     vm = numpy.ma.masked_where(numpy.isnan(vv), vv)
632     wspd = numpy.sqrt(um*um + vm*vm)
633
634     X,Y = numpy.meshgrid(dn, z)
635
636     q1 = ax.barbs(X, Y, um.T, vm.T, wspd.T)
637     # qk = ax.quiverkey(q1, 0.1, 0.8, 20, r'20 m s-1')
638     
639     ax.set_ylabel('Height (m)')
640
641     # setup colorbar axes instance.
642     l,b,w,h = ax.get_position().bounds
643     cax = fig.add_axes([l+0.02, b+h-0.06, 0.25*w, 0.03])
644
645     cb = colorbar(q1, cax=cax, orientation='horizontal') # draw colorbar
646     cb.set_label('Wind Velocity (m s-1)')
647
648     # lost control of colorbar ... ???
649     #
650     # cb.ax.xaxis.set_label_position('top')
651     # cb.ax.set_xticks([0.0, 0.5, 1.0])
652     # xtl = numpy.round(numpy.linspace(cmin, cmax, 11), decimals=0)
653     # cb.ax.set_xticklabels([xtl[0], xtl[5], xtl[10]])
654
655     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
656     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
657     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
658     ax.set_xticklabels([])
659
660     # this only moves the label not the tick labels
661     ax.xaxis.set_label_position('bottom')
662     ax.set_xlabel('BILLY MITCHELL Wind Profile -- ' + yyyy_mm_str)
663
664     # right-hand side scale
665     ax2 = twinx(ax)
666     ax2.yaxis.tick_right()
667     # convert (lhs) meters to (rhs) feet
668     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
669     ax2.set_ylim(feet)
670     ax2.set_ylabel('Height (ft)')
671
672    
673
674     #######################################
675     # Last 1 day (24hrs)
676     #######################################
677     if plot_type=='latest':
678         print ' ... Last 1 days'
679
680         for idx, ax in enumerate(axs):
681             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
682             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
683             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
684             ax.set_xticklabels([])
685             if idx==0:
686                 ax.set_xlabel('BILLY MITCHELL Wind Profile -- Last 24 hours from ' + last_dt_str)
687             if idx==len(axs)-1:
688                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
689                 ax.set_xlabel('BILLY MITCHELL Wind Profile -- Last 24 hours from ' + last_dt_str)
690
691         savefig('/home/haines/rayleigh/img/billymitchell_windbarbs_last01days.png')
692
Note: See TracBrowser for help on using the browser.