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

root/proc2plot/trunk/proc2plot/meet_flow_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-09 16:49:47 haines>
3 """meet_flow_plot"""
4
5 # plot each month
6
7 import os
8 # import sys, glob, re
9 import datetime, time, dateutil, dateutil.tz
10 import pycdf
11 import numpy
12
13 # sys.path.append('/opt/env/haines/dataproc/raw2proc')
14 # del(sys)
15
16 os.environ["MPLCONFIGDIR"]="/home/haines/.matplotlib/"
17
18 from pylab import figure, twinx, savefig, setp, getp, cm, colorbar
19 from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, DateFormatter, date2num, num2date
20 import procutil
21
22 def timeseries(pi, si, yyyy_mm, plot_type='latest'):
23     """
24     """
25
26
27     print 'meet_flow_plot ...'
28
29     #
30
31     prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
32     yyyy_mm_str = this_month.strftime('%Y_%m')
33
34     ncFile1='/seacoos/data/nccoos/level1/meet/wq/meet_wq_'+prev_month.strftime('%Y_%m')+'.nc'
35     ncFile2='/seacoos/data/nccoos/level1/meet/wq/meet_wq_'+this_month.strftime('%Y_%m')+'.nc'
36
37     have_ncFile1 = os.path.exists(ncFile1)
38     have_ncFile2 = os.path.exists(ncFile2)
39
40     print ' ... loading data for graph from ...'
41     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
42     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
43
44     # open netcdf data
45     if have_ncFile1 and have_ncFile2:
46         nc = pycdf.CDFMF((ncFile1, ncFile2))
47     elif not have_ncFile1 and have_ncFile2:
48         nc = pycdf.CDFMF((ncFile2,))
49     elif have_ncFile1 and not have_ncFile2:
50         nc = pycdf.CDFMF((ncFile1,))
51     else:
52         print ' ... both files do not exist -- NO DATA LOADED'
53         return
54
55     # ncvars = nc.variables()
56     # print ncvars
57     es = nc.var('time')[:]
58     units = nc.var('time').units
59     dt = [procutil.es2dt(e) for e in es]
60     # set timezone info to UTC (since data from level1 should be in UTC!!)
61     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
62     # return new datetime based on computer local
63     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
64     dn = date2num(dt)
65
66     z = nc.var('z')[:]
67     wtemp = nc.var('wtemp')[:]
68     cond = nc.var('cond')[:]
69     turb = nc.var('turb')[:]
70     ph = nc.var('ph')[:]
71     do_mg = nc.var('do_mg')[:]
72     do_sat = nc.var('do_sat')[:]
73     batt = nc.var('battvolts')[:]
74     nc.close()
75
76
77     ncFile1='/seacoos/data/nccoos/level1/meet/flow/meet_flow_'+prev_month.strftime('%Y_%m')+'.nc'
78     ncFile2='/seacoos/data/nccoos/level1/meet/flow/meet_flow_'+this_month.strftime('%Y_%m')+'.nc'
79
80     have_ncFile1 = os.path.exists(ncFile1)
81     have_ncFile2 = os.path.exists(ncFile2)
82
83     print ' ... loading data for graph from ...'
84     print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
85     print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
86
87     # open netcdf data
88     if have_ncFile1 and have_ncFile2:
89         nc = pycdf.CDFMF((ncFile1, ncFile2))
90     elif not have_ncFile1 and have_ncFile2:
91         nc = pycdf.CDFMF((ncFile2,))
92     elif have_ncFile1 and not have_ncFile2:
93         nc = pycdf.CDFMF((ncFile1,))
94     else:
95         print ' ... both files do not exist -- NO DATA LOADED'
96         return
97
98     # ncvars = nc.variables()
99     # print ncvars
100     es2 = nc.var('time')[:]
101     units = nc.var('time').units
102     dt2 = [procutil.es2dt(e) for e in es2]
103     # set timezone info to UTC (since data from level1 should be in UTC!!)
104     dt2 = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt2]
105     dn2 = date2num(dt2)
106
107     r2 = nc.var('rain')[:] # inches of rain in past 15 min
108     have_sontek = False # don't plot sontek
109     # have_sontek = 'sontek_wl' in ncvars.keys() or 'sontek_flow' in ncvars.keys()
110     pwl2 = nc.var('press_wl')[:] # feet
111     pfl2 = nc.var('press_flow')[:] # cfs
112
113     if have_sontek:
114         swl2 = nc.var('sontek_wl')[:] # feet
115         sfl2 = nc.var('sontek_flow')[:] # cfs
116
117     nc.close()
118
119     # last dt in data for labels
120     dtu = dt[-1]
121     dtl = dt_local[-1]
122
123     diff = abs(dtu - dtl)
124     if diff.days>0:
125         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
126     else:
127         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
128                       + dtl.strftime(" on %b %d, %Y")
129
130     #######################################
131     # Plot month all flow (plus battery) the timeseries data
132     #######################################
133
134     fig = figure(figsize=(10, 8))
135     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
136    
137     ax = fig.add_subplot(4,1,1)
138     axs = [ax]
139    
140     # ax.plot returns a list of lines, so unpack tuple
141     (x, y) = procutil.addnan(dt2, r2)
142     l1, = ax.plot_date(x, y, fmt='b-')
143     l1.set_label('Precipitation')
144    
145     ax.set_ylabel('Rain (in)')
146     # ax.set_ylim(0,1.)
147     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
148     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
149     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
150     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
151     ax.set_xticklabels([])
152
153     # right-hand side scale
154     ax2 = twinx(ax)
155     ax2.yaxis.tick_right()
156     # convert (lhs) inches to (rhs) mm
157     f = [procutil.inches2millimeters(val) for val in ax.get_ylim()]
158     ax2.set_ylim(f)
159     ax2.set_ylabel('Rain (mm)')
160     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
161     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
162     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
163     ax2.set_xticklabels([])
164
165     # this only moves the label not the tick labels
166     ax.xaxis.set_label_position('top')
167     ax.set_xlabel('MEET Stream Flow -- ' + yyyy_mm_str)
168    
169     # legend
170     ls1 = l1.get_label()
171     leg = ax.legend((l1,), (ls1,), loc='upper left')
172     ltext  = leg.get_texts()  # all the text.Text instance in the legend
173     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
174     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
175     frame.set_facecolor('0.80')      # set the frame face color to light gray
176     frame.set_alpha(0.5)             # set alpha low to see through
177     setp(ltext, fontsize='small')    # the legend text fontsize
178     setp(llines, linewidth=1.5)      # the legend linewidth
179     # leg.draw_frame(False)           # don't draw the legend frame
180     
181     #######################################
182     #
183     ax = fig.add_subplot(4,1,2)
184     axs.append(ax)
185
186     # ax.plot returns a list of lines, so unpack tuple
187     (x, y) = procutil.addnan(dt2, pwl2)
188     l1, = ax.plot_date(x, y, fmt='b-')
189     l1.set_label('Derived from pressure')
190     if have_sontek:
191         (x, y) = procutil.addnan(dt2, swl2)
192         l2, = ax.plot_date(x, y, fmt='c-')
193         l2.set_label('From Acoustic Sounding')   
194    
195     ax.plot_date((x[1],x[-1]), (0,0), fmt='k:')
196     ax.plot_date((x[1],x[-1]), (2.5,2.5), fmt='k--')
197
198     ax.set_ylabel('Depth (ft)')
199     ax.set_ylim(-0.2,3)
200     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
201     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
202     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
203     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
204     ax.set_xticklabels([])
205
206     # right-hand side scale
207     ax2 = twinx(ax)
208     ax2.yaxis.tick_right()
209     # convert (lhs) feet to (rhs) meters
210     f = [procutil.feet2meters(val) for val in ax.get_ylim()]
211     ax2.set_ylim(f)
212     ax2.set_ylabel('Depth (m)')
213     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
214     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
215     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
216     ax2.set_xticklabels([])
217
218     # legend
219     ls1 = l1.get_label()
220     if have_sontek:
221         ls2 = l2.get_label()
222         leg = ax.legend((l1,l2), (ls1,ls2), loc='upper left')
223     else:
224         leg = ax.legend((l1,), (ls1,), loc='upper left')
225     ltext  = leg.get_texts()  # all the text.Text instance in the legend
226     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
227     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
228     frame.set_facecolor('0.80')      # set the frame face color to light gray
229     frame.set_alpha(0.5)             # set alpha low to see through
230     setp(ltext, fontsize='small')    # the legend text fontsize
231     setp(llines, linewidth=1.5)      # the legend linewidth
232     # leg.draw_frame(False)           # don't draw the legend frame
233     
234     #######################################
235     #
236     ax = fig.add_subplot(4,1,3)
237     axs.append(ax)
238    
239     # ax.plot returns a list of lines, so unpack tuple
240     (x, y) = procutil.addnan(dt2, pfl2)
241     l1, = ax.plot_date(x, y, fmt='b-')
242     l1.set_label('Derived from pressure')
243     if have_sontek:
244         (x, y) = procutil.addnan(dt2, sfl2)
245         l2, = ax.plot_date(x, y, fmt='c-')
246         l2.set_label('Depth-avg Acoustic Profile')   
247    
248     ax.plot_date((x[1],x[-1]), (0,0), fmt='k:')
249
250     ax.set_ylabel('Flow (cfs)')
251     ax.set_ylim(0,350)
252     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
253     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
254     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
255     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
256     ax.set_xticklabels([])
257
258     # legend
259     ls1 = l1.get_label()
260     if have_sontek:
261         ls2 = l2.get_label()
262         leg = ax.legend((l1,l2), (ls1,ls2), loc='upper left')
263     else:
264         leg = ax.legend((l1,), (ls1,), loc='upper left')
265     ltext  = leg.get_texts()  # all the text.Text instance in the legend
266     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
267     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
268     frame.set_facecolor('0.80')      # set the frame face color to light gray
269     frame.set_alpha(0.5)             # set alpha low to see through
270     setp(ltext, fontsize='small')    # the legend text fontsize
271     setp(llines, linewidth=1.5)      # the legend linewidth
272     # leg.draw_frame(False)           # don't draw the legend frame
273
274     #######################################
275     #
276     #######################################
277     #
278     ax = fig.add_subplot(4,1,4)
279     axs.append(ax)
280
281     # ax.plot returns a list of lines, so unpack tuple
282     (x, y) = procutil.addnan(dt, batt)
283     l1, = ax.plot_date(x, y, fmt='b-')
284     l1.set_label('Station Battery')
285    
286     ax.set_ylabel('Battery\n (volts)')
287     ax.set_ylim(12, 14.5)
288     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
289     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
290     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
291     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
292
293     ax.set_xlabel('MEET Stream Flow -- ' + yyyy_mm_str)
294
295     # legend
296     ls1 = l1.get_label()
297     leg = ax.legend((l1,), (ls1,), loc='upper left')
298     ltext  = leg.get_texts()  # all the text.Text instance in the legend
299     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
300     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
301     frame.set_facecolor('0.80')      # set the frame face color to light gray
302     frame.set_alpha(0.5)             # set alpha low to see through
303     setp(ltext, fontsize='small')    # the legend text fontsize
304     setp(llines, linewidth=1.5)      # the legend linewidth
305     # leg.draw_frame(False)           # don't draw the legend frame
306     
307     # save figure   
308     ofn = '/home/haines/rayleigh/img/meet/meet_flow_' + yyyy_mm_str + '.png'
309     print '... ... write: %s' % (ofn,)
310     savefig(ofn)
311
312
313     #######################################
314     # Last 30 days
315     #######################################
316     if plot_type=='latest':
317         print ' ... Last 30 days'
318         for idx, ax in enumerate(axs):
319             ax.set_xlim(date2num(dt[-1])-30, date2num(dt[-1]))
320             ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
321             ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
322             ax.set_xticklabels([])
323             if idx==0:
324                 ax.set_xlabel('MEET Stream Flow -- Last 30 days from ' + last_dt_str)
325             elif idx==len(axs)-1:
326                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
327                 ax.set_xlabel('MEET Stream Flow -- Last 30 days from ' + last_dt_str)
328
329         savefig('/home/haines/rayleigh/img/meet_flow_last30days.png')
330
331
332     #######################################
333     # Last 7 days
334     #######################################
335     if plot_type=='latest':
336         print ' ... Last 7 days'
337         for idx, ax in enumerate(axs):
338             ax.set_xlim(date2num(dt[-1])-7, date2num(dt[-1]))
339             ax.xaxis.set_major_locator( DayLocator(range(0,32,1)) )
340             ax.xaxis.set_minor_locator( HourLocator(range(0,25,6)) )
341             ax.set_xticklabels([])
342             if idx==0:
343                 ax.set_xlabel('MEET Stream Flow -- Last 7 days from ' + last_dt_str)
344             elif idx==len(axs)-1:
345                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
346                 ax.set_xlabel('MEET Stream Flow -- Last 7 days from ' + last_dt_str)
347                
348         savefig('/home/haines/rayleigh/img/meet_flow_last07days.png')
349
350
351     #######################################
352     # Last 1 day (24hrs)
353     #######################################
354     if plot_type=='latest':
355         print ' ... Last 1 days'
356
357         for idx, ax in enumerate(axs):
358             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
359             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
360             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
361             ax.set_xticklabels([])
362             if idx==0:
363                 ax.set_xlabel('MEET  Stream Flow -- Last 24 hours from ' + last_dt_str)
364             elif idx==len(axs)-1:
365                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
366                 ax.set_xlabel('MEET  Stream Flow -- Last 24 hours from ' + last_dt_str)
367
368         savefig('/home/haines/rayleigh/img/meet_flow_last01days.png')
369
370
371
372
Note: See TracBrowser for help on using the browser.