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

root/proc2plot/trunk/proc2plot/bogue_adcp_plot.py

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

Fix SVN locks and update code.

  • Property svn:executable set to
Line 
1 #!/usr/bin/env /opt/env/haines/dataproc/bin/python
2 # Last modified:  Time-stamp: <2010-08-17 15:47:11 haines>
3
4 """bogue_adcp_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     """
31     """
32
33
34     print 'bogue_adcp_plot ...'
35
36     #
37
38     prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
39     yyyy_mm_str = this_month.strftime('%Y_%m')
40
41     ################################
42     # [2a] load primary data file
43     ################################
44
45     ncFile1='/seacoos/data/nccoos/level1/bogue/adcp/bogue_adcp_'+prev_month.strftime('%Y_%m')+'.nc'
46     ncFile2='/seacoos/data/nccoos/level1/bogue/adcp/bogue_adcp_'+this_month.strftime('%Y_%m')+'.nc'
47
48     have_ncFile1 = os.path.exists(ncFile1)
49     have_ncFile2 = os.path.exists(ncFile2)
50
51     print ' ... loading data for graph from ...'
52     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
53     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
54
55     # open netcdf data
56     if have_ncFile1 and have_ncFile2:
57         nc = pycdf.CDFMF((ncFile1, ncFile2))
58     elif not have_ncFile1 and have_ncFile2:
59         nc = pycdf.CDFMF((ncFile2,))
60     elif have_ncFile1 and not have_ncFile2:
61         nc = pycdf.CDFMF((ncFile1,))
62     else:
63         print ' ... both files do not exist -- NO DATA LOADED'
64         return
65
66     # ncvars = nc.variables()
67     # print ncvars
68     es = nc.var('time')[:]
69     units = nc.var('time').units
70     dt = [procutil.es2dt(e) for e in es]
71     # set timezone info to UTC (since data from level1 should be in UTC!!)
72     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
73     # return new datetime based on computer local
74     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
75     dn = date2num(dt)
76
77     ################################
78     # [2b] specify variables
79     ################################
80     z = nc.var('z')[:]
81     wd = nc.var('wd')[:]
82     wl = nc.var('wl')[:]
83     # en = nc.var('en')[:]
84     u = nc.var('u')[:]
85     v = nc.var('v')[:]
86     e1 = nc.var('e1')[:]
87
88     nc.close()
89
90     # last dt in data for labels
91     dtu = dt[-1]
92     dtl = dt_local[-1]
93
94     diff = abs(dtu - dtl)
95     if diff.days>0:
96         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
97     else:
98         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
99                       + dtl.strftime(" on %b %d, %Y")
100
101     #######################################
102     # Plot setup
103     #######################################
104     # range for pcolor plots
105     cmin, cmax = (-0.5, 0.5)
106
107     fig = figure(figsize=(10, 8))
108     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
109
110     ax = fig.add_subplot(4,1,1)
111     axs = [ax]
112
113     # replace gaps in time with NaN
114     (x, y) = procutil.addnan(dt, u, maxdelta=2./24)
115     dnx = date2num(x)
116     # use masked array to hide NaN's on plot
117     um = numpy.ma.masked_where(numpy.isnan(y), y)
118     pc = ax.pcolor(dnx, z, um.T, vmin=cmin, vmax=cmax)
119     pc.set_label('True Eastward Current (m s-1)')
120     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
121
122     # setup colorbar axes instance
123     l,b,w,h = ax.get_position().bounds
124     cax = fig.add_axes([l, b+h+0.04, 0.25*w, 0.03])
125
126     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
127     cb.set_label('Current Velocity (m s-1)')
128     cb.ax.xaxis.set_label_position('top')
129     cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
130     cb.ax.set_xticklabels([-0.4, -0.2, 0, 0.2, 0.4])
131
132     # ax.plot returns a list of lines, so unpack tuple
133     (x, y) = procutil.addnan(dt, wl, maxdelta=2./24)
134     l1, = ax.plot_date(x, y, fmt='k-')
135     l1.set_label('Water Level')
136
137     ax.set_ylabel('Depth (m)')
138     ax.set_ylim(-10., 2.)
139     # ax.set_xlim(dt[0], dt[-1]) # first to last regardless of what 
140     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
141     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
142     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
143     ax.set_xticklabels([])
144
145     # this only moves the label not the tick labels
146     ax.xaxis.set_label_position('top')
147     ax.set_xlabel('BOGUE Current Profile -- ' + yyyy_mm_str)
148
149     # right-hand side scale
150     ax2 = twinx(ax)
151     ax2.yaxis.tick_right()
152     # convert (lhs) meters to (rhs) feet
153     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
154     ax2.set_ylim(feet)
155     ax2.set_ylabel('Depth (ft)')
156
157     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
158     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
159     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
160     ax2.set_xticklabels([])
161
162     # legend
163     ls1 = l1.get_label()
164     leg = ax.legend((l1,), (ls1,), loc='upper left')
165     ltext  = leg.get_texts()  # all the text.Text instance in the legend
166     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
167     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
168     frame.set_facecolor('0.80')      # set the frame face color to light gray
169     frame.set_alpha(0.5)             # set alpha low to see through
170     setp(ltext, fontsize='small')    # the legend text fontsize
171     setp(llines, linewidth=1.5)      # the legend linewidth
172     # leg.draw_frame(False)           # don't draw the legend frame
173
174     #######################################
175     #
176     ax = fig.add_subplot(4,1,2)
177     axs.append(ax)
178
179     # replace gaps in time with NaN
180     (x, y) = procutil.addnan(dt, v, maxdelta=2./24)
181     dnx = date2num(x)
182     # use masked array to hide NaN's on plot
183     vm = numpy.ma.masked_where(numpy.isnan(y), y)
184     # (x, y) = procutil.addnan(dt, vm, maxdelta=2./24)
185     pc = ax.pcolor(dnx, z, vm.T, vmin=cmin, vmax=cmax)
186     pc.set_label('True Northward Current (m s-1)')
187     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
188
189     # ax.plot returns a list of lines, so unpack tuple
190     (x, y) = procutil.addnan(dt, wl, maxdelta=2./24)
191     l1, = ax.plot_date(x, y, fmt='k-')
192     l1.set_label('Water Level')
193
194     ax.set_ylabel('Depth (m)')
195     ax.set_ylim(-10.,2.)
196     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
197     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
198     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
199
200     # right-hand side scale
201     ax2 = twinx(ax)
202     ax2.yaxis.tick_right()
203     # convert (lhs) meters to (rhs) feet
204     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
205     ax2.set_ylim(feet)
206     ax2.set_ylabel('Depth (ft)')
207
208     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
209     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
210     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
211
212     # legend
213     ls1 = l1.get_label()
214     leg = ax.legend((l1,), (ls1,), loc='upper left')
215     ltext  = leg.get_texts()  # all the text.Text instance in the legend
216     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
217     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
218     frame.set_facecolor('0.80')      # set the frame face color to light gray
219     frame.set_alpha(0.5)             # set alpha low to see through
220     setp(ltext, fontsize='small')    # the legend text fontsize
221     setp(llines, linewidth=1.5)      # the legend linewidth
222     # leg.draw_frame(False)           # don't draw the legend frame
223
224     #######################################
225     #
226     ax = fig.add_subplot(4,1,3)
227     axs.append(ax)
228
229     # replace gaps in time with NaN
230     (x, y) = procutil.addnan(dt, e1, maxdelta=2./24)
231     dnx = date2num(x)
232     # use masked array to hide NaN's on plot
233     vm = numpy.ma.masked_where(numpy.isnan(y), y)
234     # (x, y) = procutil.addnan(dt, vm, maxdelta=2./24)
235     pc = ax.pcolor(dnx, z, vm.T, vmin=0., vmax=150.)
236     pc.set_label('Amplitude Beam 1 (count)')
237     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
238
239     # ax.plot returns a list of lines, so unpack tuple
240     (x, y) = procutil.addnan(dt, wl, maxdelta=2./24)
241     l1, = ax.plot_date(x, y, fmt='k-')
242     l1.set_label('Water Level')
243
244     ax.set_ylabel('Depth (m)')
245     ax.set_ylim(-10.,2.)
246     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
247     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
248     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
249     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
250
251     ax.set_xlabel('BOGUE Current Profile -- ' + yyyy_mm_str)
252
253     # right-hand side scale
254     ax2 = twinx(ax)
255     ax2.yaxis.tick_right()
256     # convert (lhs) meters to (rhs) feet
257     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
258     ax2.set_ylim(feet)
259     ax2.set_ylabel('Depth (ft)')
260
261     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
262     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
263     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
264     ax2.xaxis.set_major_formatter( DateFormatter('%m/%d') )
265
266     # legend
267     ls1 = l1.get_label()
268     leg = ax.legend((l1,), (ls1,), loc='upper left')
269     ltext  = leg.get_texts()  # all the text.Text instance in the legend
270     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
271     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
272     frame.set_facecolor('0.80')      # set the frame face color to light gray
273     frame.set_alpha(0.5)             # set alpha low to see through
274     setp(ltext, fontsize='small')    # the legend text fontsize
275     setp(llines, linewidth=1.5)      # the legend linewidth
276     # leg.draw_frame(False)           # don't draw the legend frame
277
278
279     # save figure for this month
280     ofn = '/home/haines/rayleigh/img/bogue/bogue_adcp_'+yyyy_mm_str+'.png'
281     print '... ... write: %s' % (ofn,)
282     savefig(ofn)
283
284
285     #######################################
286     # Last 30 days
287     #######################################
288     if plot_type=='latest':
289         print ' ... Last 30 days'
290         for idx, ax in enumerate(axs):
291             ax.set_xlim(date2num(dt[-1])-30, date2num(dt[-1]))
292             ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
293             ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
294             ax.set_xticklabels([])
295             if idx==0:
296                 ax.set_xlabel('BOGUE Current Profiles -- Last 30 days from ' + last_dt_str)
297             elif idx==len(axs)-1:
298                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
299                 ax.set_xlabel('BOGUE Current Profiles -- Last 30 days from ' + last_dt_str)
300
301         savefig('/home/haines/rayleigh/img/bogue_adcp_last30days.png')
302
303
304     #######################################
305     # Last 7 days
306     #######################################
307     if plot_type=='latest':
308         print ' ... Last 7 days'
309         for idx, ax in enumerate(axs):
310             ax.set_xlim(date2num(dt[-1])-7, date2num(dt[-1]))
311             ax.xaxis.set_major_locator( DayLocator(range(0,32,1)) )
312             ax.xaxis.set_minor_locator( HourLocator(range(0,25,6)) )
313             ax.set_xticklabels([])
314             if idx==0:
315                 ax.set_xlabel('BOGUE Current Profiles -- Last 7 days from ' + last_dt_str)
316             elif idx==len(axs)-1:
317                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
318                 ax.set_xlabel('BOGUE Current Profiles -- Last 7 days from ' + last_dt_str)
319                
320         savefig('/home/haines/rayleigh/img/bogue_adcp_last07days.png')
321
322
323     #######################################
324     # Last 1 day (24hrs)
325     #######################################
326     if plot_type=='latest':
327         print ' ... Last 1 days'
328
329         for idx, ax in enumerate(axs):
330             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
331             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
332             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
333             ax.set_xticklabels([])
334             if idx==0:
335                 ax.set_xlabel('BOGUE Current Profiles -- Last 24 hours from ' + last_dt_str)
336             elif idx==len(axs)-1:
337                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
338                 ax.set_xlabel('BOGUE Current Profiles -- Last 24 hours from ' + last_dt_str)
339
340         savefig('/home/haines/rayleigh/img/bogue_adcp_last01days.png')
341
Note: See TracBrowser for help on using the browser.