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

root/proc2plot/trunk/proc2plot/bogue_adcp_plot.py

Revision 329 (checked in by haines, 14 years ago)

import first verison proc2plot

  • Property svn:executable set to
Line 
1 #!/usr/bin/env /opt/env/haines/dataproc/bin/python
2 # Last modified:  Time-stamp: <2010-04-12 13:37:36 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         exit()
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
87     nc.close()
88
89     # last dt in data for labels
90     dtu = dt[-1]
91     dtl = dt_local[-1]
92
93     diff = abs(dtu - dtl)
94     if diff.days>0:
95         last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
96     else:
97         last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
98                       + dtl.strftime(" on %b %d, %Y")
99
100     #######################################
101     # Plot setup
102     #######################################
103     # range for pcolor plots
104     cmin, cmax = (-0.5, 0.5)
105
106     fig = figure(figsize=(10, 8))
107     fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
108
109     ax = fig.add_subplot(4,1,1)
110     axs = [ax]
111
112     # replace gaps in time with NaN
113     (x, y) = procutil.addnan(dt, u, maxdelta=2./24)
114     dnx = date2num(x)
115     # use masked array to hide NaN's on plot
116     um = numpy.ma.masked_where(numpy.isnan(y), y)
117     pc = ax.pcolor(dnx, z, um.T, vmin=cmin, vmax=cmax)
118     pc.set_label('True Eastward Current (m s-1)')
119     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
120
121     # setup colorbar axes instance
122     l,b,w,h = ax.get_position().bounds
123     cax = fig.add_axes([l, b+h+0.04, 0.25*w, 0.03])
124
125     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
126     cb.set_label('Current Velocity (m s-1)')
127     cb.ax.xaxis.set_label_position('top')
128     cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
129     cb.ax.set_xticklabels([-0.4, -0.2, 0, 0.2, 0.4])
130
131     # ax.plot returns a list of lines, so unpack tuple
132     (x, y) = procutil.addnan(dt, wl, maxdelta=2./24)
133     l1, = ax.plot_date(x, y, fmt='k-')
134     l1.set_label('Water Level')
135
136     ax.set_ylabel('Depth (m)')
137     ax.set_ylim(-10., 2.)
138     # ax.set_xlim(dt[0], dt[-1]) # first to last regardless of what 
139     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
140     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
141     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
142     ax.set_xticklabels([])
143
144     # this only moves the label not the tick labels
145     ax.xaxis.set_label_position('top')
146     ax.set_xlabel('BOGUE Current Profile -- ' + yyyy_mm_str)
147
148     # right-hand side scale
149     ax2 = twinx(ax)
150     ax2.yaxis.tick_right()
151     # convert (lhs) meters to (rhs) feet
152     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
153     ax2.set_ylim(feet)
154     ax2.set_ylabel('Depth (ft)')
155
156     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
157     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
158     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
159     ax2.set_xticklabels([])
160
161     # legend
162     ls1 = l1.get_label()
163     leg = ax.legend((l1,), (ls1,), loc='upper left')
164     ltext  = leg.get_texts()  # all the text.Text instance in the legend
165     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
166     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
167     frame.set_facecolor('0.80')      # set the frame face color to light gray
168     frame.set_alpha(0.5)             # set alpha low to see through
169     setp(ltext, fontsize='small')    # the legend text fontsize
170     setp(llines, linewidth=1.5)      # the legend linewidth
171     # leg.draw_frame(False)           # don't draw the legend frame
172
173     #######################################
174     #
175     ax = fig.add_subplot(4,1,2)
176     axs.append(ax)
177
178     # replace gaps in time with NaN
179     (x, y) = procutil.addnan(dt, v, maxdelta=2./24)
180     dnx = date2num(x)
181     # use masked array to hide NaN's on plot
182     vm = numpy.ma.masked_where(numpy.isnan(y), y)
183     # (x, y) = procutil.addnan(dt, vm, maxdelta=2./24)
184     pc = ax.pcolor(dnx, z, vm.T, vmin=cmin, vmax=cmax)
185     pc.set_label('True Northward Current (m s-1)')
186     ax.text(0.025, 0.1, pc.get_label(), fontsize="small", transform=ax.transAxes)
187
188     # ax.plot returns a list of lines, so unpack tuple
189     (x, y) = procutil.addnan(dt, wl, maxdelta=2./24)
190     l1, = ax.plot_date(x, y, fmt='k-')
191     l1.set_label('Water Level')
192
193     ax.set_ylabel('Depth (m)')
194     ax.set_ylim(-10.,2.)
195     ax.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
196     ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
197     ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
198     ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
199
200     ax.set_xlabel('BOGUE Current Profile -- ' + yyyy_mm_str)
201
202     # right-hand side scale
203     ax2 = twinx(ax)
204     ax2.yaxis.tick_right()
205     # convert (lhs) meters to (rhs) feet
206     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
207     ax2.set_ylim(feet)
208     ax2.set_ylabel('Depth (ft)')
209
210     ax2.set_xlim(date2num(this_month), date2num(next_month-datetime.timedelta(seconds=1)))
211     ax2.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
212     ax2.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
213     ax2.xaxis.set_major_formatter( DateFormatter('%m/%d') )
214
215     # legend
216     ls1 = l1.get_label()
217     leg = ax.legend((l1,), (ls1,), loc='upper left')
218     ltext  = leg.get_texts()  # all the text.Text instance in the legend
219     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
220     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
221     frame.set_facecolor('0.80')      # set the frame face color to light gray
222     frame.set_alpha(0.5)             # set alpha low to see through
223     setp(ltext, fontsize='small')    # the legend text fontsize
224     setp(llines, linewidth=1.5)      # the legend linewidth
225     # leg.draw_frame(False)           # don't draw the legend frame
226
227     # save figure for this month
228     ofn = '/home/haines/rayleigh/img/bogue/bogue_adcp_'+yyyy_mm_str+'.png'
229     print '... ... write: %s' % (ofn,)
230     savefig(ofn)
231
232
233     #######################################
234     # Last 30 days
235     #######################################
236     if plot_type=='latest':
237         print ' ... Last 30 days'
238         for idx, ax in enumerate(axs):
239             ax.set_xlim(date2num(dt[-1])-30, date2num(dt[-1]))
240             ax.xaxis.set_major_locator( DayLocator(range(2,32,2)) )
241             ax.xaxis.set_minor_locator( HourLocator(range(0,25,12)) )
242             ax.set_xticklabels([])
243             if idx==0:
244                 ax.set_xlabel('BOGUE Current Profiles -- Last 30 days from ' + last_dt_str)
245             elif idx==len(axs)-1:
246                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
247                 ax.set_xlabel('BOGUE Current Profiles -- Last 30 days from ' + last_dt_str)
248
249         savefig('/home/haines/rayleigh/img/bogue_adcp_last30days.png')
250
251
252     #######################################
253     # Last 7 days
254     #######################################
255     if plot_type=='latest':
256         print ' ... Last 7 days'
257         for idx, ax in enumerate(axs):
258             ax.set_xlim(date2num(dt[-1])-7, date2num(dt[-1]))
259             ax.xaxis.set_major_locator( DayLocator(range(0,32,1)) )
260             ax.xaxis.set_minor_locator( HourLocator(range(0,25,6)) )
261             ax.set_xticklabels([])
262             if idx==0:
263                 ax.set_xlabel('BOGUE Current Profiles -- Last 7 days from ' + last_dt_str)
264             elif idx==len(axs)-1:
265                 ax.xaxis.set_major_formatter( DateFormatter('%m/%d') )
266                 ax.set_xlabel('BOGUE Current Profiles -- Last 7 days from ' + last_dt_str)
267                
268         savefig('/home/haines/rayleigh/img/bogue_adcp_last07days.png')
269
270
271     #######################################
272     # Last 1 day (24hrs)
273     #######################################
274     if plot_type=='latest':
275         print ' ... Last 1 days'
276
277         for idx, ax in enumerate(axs):
278             ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1]))
279             ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
280             ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
281             ax.set_xticklabels([])
282             if idx==0:
283                 ax.set_xlabel('BOGUE Current Profiles -- Last 24 hours from ' + last_dt_str)
284             elif idx==len(axs)-1:
285                 ax.xaxis.set_major_formatter( DateFormatter('%H') )
286                 ax.set_xlabel('BOGUE Current Profiles -- Last 24 hours from ' + last_dt_str)
287
288         savefig('/home/haines/rayleigh/img/bogue_adcp_last01days.png')
289
Note: See TracBrowser for help on using the browser.