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

root/proc2plot/trunk/proc2plot/jpier_dspec_plot.py

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

import first verison proc2plot

  • Property svn:executable set to
Line 
1 #!/usr/bin/env python
2 # Last modified:  Time-stamp: <2008-08-13 14:54:33 haines>
3 """jpier_dspec_plot"""
4
5 import os, sys
6 import datetime, time, dateutil, dateutil.tz
7 import pycdf
8 import numpy
9
10 sys.path.append('/home/haines/nccoos/raw2proc')
11 del(sys)
12
13 os.environ["MPLCONFIGDIR"]="/home/haines/.matplotlib/"
14
15 from pylab import figure, twinx, twiny, savefig, setp, getp, cm, colorbar
16 from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, DateFormatter, date2num, num2date
17 from matplotlib.ticker import MaxNLocator, FormatStrFormatter, ScalarFormatter
18 import procutil
19
20 def which_to_plot(odir, ncfn):
21     """
22     Finds which timestamp in netCDF data file (ncfn) does not have a
23     corresponding directional spectrum plot png in output dir (odir)
24
25    :Parameters:
26        odir : string, path to location of png's
27        ncfn : string, filename and path to netCDF file
28
29    :Returns:
30        j_seq : integer sequence, for indices of data to plot
31        
32     """
33
34     nc = pycdf.CDF(ncFile1)
35     # nc = pycdf.CDFMF((ncFile1, ncFile2))
36     ncvars = nc.variables()
37     # print ncvars
38     es = nc.var('time')[:]
39     units = nc.var('time').units
40     dt = [procutil.es2dt(e) for e in es]
41     dts = [d.strftime('%Y_%m_%d_%H%M') for d in dt]
42     # list all pngs
43     import glob
44     gs = os.path.join(odir, '*.png')
45     all_pngs = glob.glob(gs)
46     ap = ''.join(all_pngs)
47     # find index of dts not in all_pngs
48     j_seq = [j for j in range(len(dts)) if ap.find(dts[j]) == -1]
49     # return index values to plot (j)
50     return j_seq
51
52 print 'jpier_dspec_plot ...'
53 prev_month, this_month, next_month = procutil.find_months(procutil.this_month())
54 # ncFile1='/home/haines/test_data/nccoos/level1/jpier/adcpwaves/jpier_adcpwaves_2008_03.nc'
55 # ncFile2='/seacoos/data/nccoos/level1/jpier/adcpwaves/jpier_adcpwaves_2008_03.nc'
56 # ncFile1='/seacoos/data/nccoos/level1/jpier/adcpwaves/jpier_adcpwaves_'+prev_month.strftime('%Y_%m')+'.nc'
57 ncFile1='/seacoos/data/nccoos/level1/jpier/adcpwaves/jpier_adcpwaves_'+this_month.strftime('%Y_%m')+'.nc'
58 odir = os.path.join('/seacoos/data/nccoos/level3/jpier/adcpwaves/dspec', this_month.strftime('%Y_%m'))
59 if not os.path.exists(odir):
60     os.mkdir(odir)
61
62 j_seq = which_to_plot(odir, ncFile1)
63 # print j_seq
64
65 if not j_seq:
66     j_seq = [-1]
67
68 # load data
69 print ' ... loading data for graph from ...'
70 print ' ... ... ' + ncFile1
71 # print ' ... ... ' + ncFile2
72 for j in j_seq:
73     nc = pycdf.CDF(ncFile1)
74     # nc = pycdf.CDFMF((ncFile1, ncFile2))
75     ncvars = nc.variables()
76     # print ncvars
77     es = nc.var('time')[:]
78     units = nc.var('time').units
79     dt = [procutil.es2dt(e) for e in es]
80     # set timezone info to UTC (since data from level1 should be in UTC!!)
81     dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
82     # return new datetime based on computer local
83     dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
84     dn = date2num(dt)
85     f = nc.var('f')[:]
86     d = nc.var('d')[:]
87     Sxx = nc.var('Sxx')[j]
88     Sf = nc.var('Sf')[j]
89     Stheta = nc.var('Stheta')[j]
90     Stheta_wind = nc.var('Stheta_wind')[j]
91     Stheta_swell = nc.var('Stheta_swell')[j]
92     Tp = nc.var('Tp')[j]
93     Tpw = nc.var('Tp_wind')[j]
94     Tps = nc.var('Tp_swell')[j]
95     Dp = nc.var('Dp')[j]
96     Dpw = nc.var('Dp_wind')[j]
97     Dps = nc.var('Dp_swell')[j]
98     Hs = nc.var('Hs')[:]
99     Hss = nc.var('Hs_swell')[:]
100     Hsw = nc.var('Hs_wind')[:]
101     nc.close()
102
103     print '... ... ' + dt[j].strftime('%Y_%m_%d_%H%M')
104
105     # range for pcolor plots
106     cmin, cmax = (0.0, 0.05)
107     # last dt in data for labels
108     dt1 = dt[j]
109     dt2 = dt_local[j]
110
111     diff = abs(dt1 - dt2)
112     if diff.days>0:
113         last_dt_str = dt1.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dt2.strftime("%H:%M %Z, %b %d") + ')'
114     else:
115         last_dt_str = dt1.strftime("%H:%M %Z") + ' (' + dt2.strftime("%H:%M %Z") + ')' \
116                       + dt2.strftime(" on %b %d, %Y")
117        
118     fn_dt_str = dt1.strftime("%Y_%m_%d_%H%M")
119        
120     fig = figure(figsize=(9, 7))
121    
122     #######################################
123     # full directional spectrum S(f,d)
124     #######################################
125     # print ' ... Sxx'
126     ax = fig.add_axes((.1,.4,.4,.45))
127     axs = [ax]
128
129     # use masked array to hide NaN's on plot
130     Sxxm = numpy.ma.masked_where(Sxx==0.0, Sxx)
131     pc = ax.pcolor(f, d, Sxxm.T, vmin=cmin, vmax=cmax)
132     # pc = ax.pcolor(f, d, Sxxm.T)
133     ax.set_ylabel('Direction (deg N)')
134     ax.set_ylim(0., 360.)
135     l0 = ax.axvline(x=0.1, color='k', linestyle=':', linewidth=1.5)
136     ax.set_xlim(0., 0.635)
137     ax.set_xlabel('Frequency (Hz)')
138    
139     # setup colorbar axes instance.
140     l,b,w,h = ax.get_position()
141     cax = fig.add_axes([l+w+0.025, b-0.06, 1.0*w, 0.03])
142    
143     cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
144     cb.set_label('Spectral Density (m2/Hz/deg)')
145     cb.ax.xaxis.set_label_position('top')
146     # cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
147     # cb.ax.set_xticklabels([-0.4, -0.2, 0, 0.2, 0.4])
148
149     # top scale wave period
150     ax2 = twiny(ax)
151     ax2.set_xlim(0., 0.635)
152     ax2.xaxis.tick_top()
153     # convert (bottom) Hertz to (top scale) seconds (1/Hz)
154     Hertz = ax.get_xticks()
155     Hertz = [val for val in Hertz if val!=0 ]
156     ax2.set_xticks(Hertz)
157     s = [round(1./val,2) for val in Hertz]
158     ax2.set_xticklabels(s)
159     ax2.set_xlabel('Wave Period (sec)')
160    
161     #######################################
162     # print ' ... all, swell, and wind labels'
163     ax = fig.add_axes((.1,.875,.4,.10))
164     axs.append(ax)
165    
166     ax.set_axis_off()
167     ax.set_axis_bgcolor(None)
168     ax.axvline(x=0.1, color='k', linestyle=':', linewidth=1.5)
169     ax.plot([0., 0.635], [0.6, 0.6], 'k-')
170     ax.plot([0.005], [0.6],'k<')
171     ax.plot([0.63],[0.6],'k>')
172     ax.text(0.5, 0.65, 'ALL FREQs',
173             horizontalalignment='center',
174             #        verticalalignment='center',
175             transform=ax.transAxes,
176             bbox=dict(facecolor=None, edgecolor='k', alpha=1))
177    
178     ax.plot([0.0, 0.1], [0.3,0.3], 'g-')
179     ax.plot([0.005], [0.3],'g<')
180     ax.plot([0.095],[0.3],'g>')
181     ax.text(0.05, .35, 'SWELL', color='g',
182             horizontalalignment='center',
183             #        verticalalignment='center',
184             transform=ax.transAxes,
185             bbox=dict(facecolor=None, edgecolor='g', alpha=1))
186    
187     ax.plot([0.1, 0.635], [0.3,0.3], 'b-')
188     ax.plot([0.105], [0.3], 'b<')
189     ax.plot([0.63], [0.3], 'b>')
190     ax.text(0.7, 0.35, 'WIND', color='b',
191             horizontalalignment='center',
192             #        verticalalignment='center',
193             transform=ax.transAxes,
194             bbox=dict(facecolor=None, edgecolor='b', alpha=1))
195     ax.set_ylim(0.,1.)
196     ax.set_xlim(0.,0.635)
197    
198     #######################################
199     # print ' ... Sf'
200     ax = fig.add_axes((.1,.25,.4,.15))
201     axs.append(ax)
202    
203     l1, = ax.plot(f, Sf, 'k-')
204     l1.set_label('Non-directional Spectrum')
205     l0 = ax.axvline(x=0.1, color='k', linestyle=':', linewidth=1.5)
206     l2 = ax.axvline(1/Tp, color='k', linestyle='-', label='ALL Wave Frequencies')
207     l3 = ax.axvline(1/Tps, color='g', linestyle='-', label='SWELL Waves')
208     l4 = ax.axvline(1/Tpw, color='b', linestyle='-', label='WIND Waves')
209     ax.set_axis_bgcolor(None)
210     ax.set_xlim(0., 0.635)
211     ax.set_ylabel('Sf (m2/Hz)')
212     ax.set_ylim(0, 3.0)
213     # ax.set_title('Frequency Spectrum')
214    
215     # legend
216     ls2 = l2.get_label()
217     ls3 = l3.get_label()
218     ls4 = l4.get_label()
219     leg = fig.legend((l2,l3,l4), (ls2,ls3,ls4), loc=(.520,.225))
220     ltext  = leg.get_texts()  # all the text.Text instance in the legend
221     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
222     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
223     frame.set_facecolor('0.80')      # set the frame face color to light gray
224     frame.set_alpha(0.5)             # set alpha low to see through
225     setp(ltext, fontsize='small')    # the legend text fontsize
226     setp(llines, linewidth=1.5)      # the legend linewidth
227    
228     #######################################
229     # print ' ... Stheta'
230     ax = fig.add_axes((.520,.4,.125,.45))
231     axs.append(ax)
232    
233     xlim = (0.,0.003)
234     l1, = ax.plot(Stheta, d, 'k-')
235     l2 = ax.axhline(Dp, color='k', linestyle='-')
236     # label ALL FREQ
237     ax.text(0.5, 0.95, 'ALL FREQs', horizontalalignment='center',
238             transform=ax.transAxes, bbox=dict(facecolor=None, edgecolor='k', alpha=0.5))
239     ax.set_yticklabels([])
240     ax.set_ylim(0., 360.)
241     ax.xaxis.tick_top()
242     ax.xaxis.set_label_position('top')
243     ax.set_xlim(xlim)
244     # ax.xaxis.set_major_locator(MaxNLocator(3))
245     # ax.xaxis.set_major_formatter(ScalarFormatter())
246     ax.set_xticks([0.,0.001,0.002])
247     ax.set_xticklabels(['0.0e-3','1.0','2.0'])
248    
249     #######################################
250     # print ' ... Stheta_swell'
251     ax = fig.add_axes((.67,.4,.125,.45))
252     axs.append(ax)
253    
254     l1, = ax.plot(Stheta_swell, d, 'g-')
255     l2 = ax.axhline(Dps, color='g', linestyle='-')
256     # label SWELL
257     ax.text(0.5, 0.95, 'SWELL', color='g', horizontalalignment='center',
258             transform=ax.transAxes, bbox=dict(facecolor=None, edgecolor='g', alpha=0.5))
259     ax.set_yticklabels([])
260     ax.set_ylim(0., 360.)
261     ax.xaxis.tick_top()
262     ax.xaxis.set_label_position('top')
263     ax.set_xlabel('Stheta (m2/deg)')
264     ax.set_xlim(xlim)
265     # ax.xaxis.set_major_locator(MaxNLocator(3))
266     # ax.xaxis.set_major_formatter(ScalarFormatter())
267     ax.set_xticks([0.,0.001,0.002])
268     ax.set_xticklabels(['0.0','1.0','2.0'])
269     ax.set_title('Jpier Wave Data as of ' + last_dt_str, fontsize=14)
270     # ax.set_title('Directional Spectrum')
271     ax.title.set_position((-0.8, 1.25))
272    
273     #######################################
274     # print ' ... Stheta_wind'
275     ax = fig.add_axes((.82,.4,.125,.45))
276     axs.append(ax)
277    
278     l1, = ax.plot(Stheta_wind, d, 'b-')
279     l2 = ax.axhline(Dpw, color='b', linestyle='-')
280     # label WIND
281     ax.text(0.5, 0.95, 'WIND', color='b', horizontalalignment='center',
282             transform=ax.transAxes, bbox=dict(facecolor=None, edgecolor='b', alpha=0.5))
283     ax.xaxis.tick_top()
284     ax.xaxis.set_label_position('top')
285     ax.set_xlim(xlim)
286     # ax.xaxis.set_major_locator(MaxNLocator(3))
287     # ax.xaxis.set_major_formatter(ScalarFormatter())
288     ax.set_xticks([0.,0.001,0.002])
289     ax.set_xticklabels(['0.0','1.0','2.0e-03'])
290    
291     ax.yaxis.tick_right()
292     ax.set_ylim(0., 360.)
293     ax.yaxis.set_label_position('right')
294     ax.set_ylabel('Direction (deg N)')
295    
296     #######################################
297     # print ' ... Hs, Hss, Hsw'
298     ax = fig.add_axes((.1,.05,.8,.15))
299     axs.append(ax)
300    
301     # use masked array to hide NaN's on plot
302     Hs = numpy.ma.masked_where(numpy.isnan(Hs), Hs)
303     Hss = numpy.ma.masked_where(numpy.isnan(Hss), Hss)
304     Hsw = numpy.ma.masked_where(numpy.isnan(Hsw), Hsw)
305    
306     # ax.plot returns a list of lines, so unpack tuple
307     l1, = ax.plot_date(dt, Hs, fmt='k-')
308     l1.set_label('Significant Wave Height (Hs)')
309    
310     l2, = ax.plot_date(dt, Hss, fmt='g-')
311     l2.set_label('Sig. Swell Wave Height (Hss)')
312    
313     l3, = ax.plot_date(dt, Hsw, fmt='b-')
314     l3.set_label('Sig. Wind Wave Height (Hsw)')
315    
316     ax.set_ylabel('WAVE\nHEIGHT(m)')
317     # ax.set_ylim(2.,10.)
318     # ax.set_xlim(dt[0], dt[-1]) # first to last regardless of what
319     ax.set_xlim(date2num(dt[-1])-1, date2num(dt[-1])) # last minus 30 days to last
320     ax.xaxis.set_major_locator( HourLocator(range(0,25,1)) )
321     ax.xaxis.set_minor_locator( MinuteLocator(range(0,61,30)) )
322     ax.xaxis.set_major_formatter( DateFormatter('%H') )
323     ax.set_xlabel('Jpier Wave Height -- Last 24 hours from ' + last_dt_str)
324    
325     # right-hand side scale
326     ax2 = twinx(ax)
327     ax2.yaxis.tick_right()
328     # convert (lhs) meters to (rhs) feet
329     feet = [procutil.meters2feet(val) for val in ax.get_ylim()]
330     ax2.set_ylim(feet)
331     ax2.set_ylabel('(feet)')
332    
333     # legend
334     ls1 = l1.get_label()
335     ls2 = l2.get_label()
336     ls3 = l3.get_label()
337     leg = ax.legend((l1,l2,l3), (ls1,ls2,ls3), loc='upper left')
338     ltext  = leg.get_texts()  # all the text.Text instance in the legend
339     llines = leg.get_lines()  # all the lines.Line2D instance in the legend
340     frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend
341     frame.set_facecolor('0.80')      # set the frame face color to light gray
342     frame.set_alpha(0.5)             # set alpha low to see through
343     setp(ltext, fontsize=8)          # the legend text fontsize
344     setp(llines, linewidth=1.5)      # the legend linewidth
345     leg.draw_frame(False)            # don't draw the legend frame
346    
347     # save figure
348     ofn = os.path.join(odir, 'jpier_dspec_'+fn_dt_str+'.png')
349     savefig(ofn)
350
351 # copy last latest
352 ofn2 = '/home/haines/rayleigh/img/jpier_dspec_last01days.png'
353 import shutil
354 shutil.copy(ofn, ofn2)
355
356 # copy last 24 to loop directory
357 import glob
358 gs = os.path.join(odir, '*.png')
359 all_pngs = glob.glob(gs)
360 all_pngs.sort()
361 j=1
362 for png in all_pngs[-24:]:
363     ofn = '/home/haines/rayleigh/loop/jpier_dspec_plot_%d.png' % (j,)
364     shutil.copy(png, ofn)
365     j=j+1
366
367 #
Note: See TracBrowser for help on using the browser.