-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_cr1000_gps.py
225 lines (190 loc) · 8.91 KB
/
plot_cr1000_gps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env /opt/env/haines/dataproc/bin/python
# Last modified: Time-stamp: <2014-02-21 10:15:14 haines>
"""plot_cr1000_gps"""
import os
# import sys, glob, re
import datetime, time, dateutil, dateutil.tz
import pycdf
import numpy
# sys.path.append('/opt/env/haines/dataproc/raw2proc')
# del(sys)
os.environ["MPLCONFIGDIR"]="/home/haines/.matplotlib/"
from pylab import figure, twinx, savefig, setp, getp, cm, colorbar, colors
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, DateFormatter, date2num, num2date
import procutil
def watch_circle(pi, si, yyyy_mm, plot_type='latest'):
"""
"""
print 'plot_cr1000_gps ...'
img_dir = '/home/haines/rayleigh/img'
prev_month, this_month, next_month = procutil.find_months(yyyy_mm)
yyyy_mm_str = this_month.strftime('%Y_%m')
fn = '_'.join([pi['id'], si['id'], prev_month.strftime('%Y_%m')+'.nc'])
ncFile1= os.path.join(si['proc_dir'], fn)
fn = '_'.join([pi['id'], si['id'], this_month.strftime('%Y_%m')+'.nc'])
ncFile2= os.path.join(si['proc_dir'], fn)
# ncFile1='/seacoos/data/nccoos/level1/meet/wq/meet_wq_'+prev_month.strftime('%Y_%m')+'.nc'
# ncFile2='/seacoos/data/nccoos/level1/meet/wq/meet_wq_'+this_month.strftime('%Y_%m')+'.nc'
have_ncFile1 = os.path.exists(ncFile1)
have_ncFile2 = os.path.exists(ncFile2)
print ' ... loading data for graph from ...'
print ' ... ... ' + ncFile1 + ' ... ' + str(have_ncFile1)
print ' ... ... ' + ncFile2 + ' ... ' + str(have_ncFile2)
# open netcdf data
if have_ncFile1 and have_ncFile2:
nc = pycdf.CDFMF((ncFile1, ncFile2))
elif not have_ncFile1 and have_ncFile2:
nc = pycdf.CDFMF((ncFile2,))
elif have_ncFile1 and not have_ncFile2:
nc = pycdf.CDFMF((ncFile1,))
else:
print ' ... both files do not exist -- NO DATA LOADED'
return
# ncvars = nc.variables()
# print ncvars
es = nc.var('time')[:]
units = nc.var('time').units
dt = [procutil.es2dt(e) for e in es]
# set timezone info to UTC (since data from level1 should be in UTC!!)
dt = [e.replace(tzinfo=dateutil.tz.tzutc()) for e in dt]
# return new datetime based on computer local
dt_local = [e.astimezone(dateutil.tz.tzlocal()) for e in dt]
dn = date2num(dt)
# last dt in data for labels
dtu = dt[-1]
dtl = dt_local[-1]
diff = abs(dtu - dtl)
if diff.days>0:
last_dt_str = dtu.strftime("%H:%M %Z on %b %d, %Y") + ' (' + dtl.strftime("%H:%M %Z, %b %d") + ')'
else:
last_dt_str = dtu.strftime("%H:%M %Z") + ' (' + dtl.strftime("%H:%M %Z") + ')' \
+ dtl.strftime(" on %b %d, %Y")
#######################################
# Build Plot
#######################################
fig = figure(figsize=(6, 5))
fig.subplots_adjust(left=0.20, bottom=0.10, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
ax = fig.add_subplot(1,1,1)
axs = [ax]
# GPS longitude on x, latitude on y
gps_lon = nc.var('gps_lon')[:]
gps_lat = nc.var('gps_lat')[:]
# gps_lon[-1:] returns last value as type numpy.array
# gps_lon[-1] returns the value as type float
(x, y) = (gps_lon[-1:], gps_lat[-1:])
# print (x, y)
# ax.plot returns a list of lines, so unpack tuple
l1, = ax.plot(x, y, 'r*', ms=8)
# anchor position platform lat and lon from config -- needs to be numpy.array([]) for ax.plot
(x, y) = (numpy.array([pi['lon']]), numpy.array([pi['lat']]))
# anchor posn platform lat and lon from netcdf file (should be the same as config)
# (x, y) = (nc.var('lon')[:], nc.var('lat')[:])
# print (x, y)
l2, = ax.plot(x, y, 'ks', ms=8, mfc='none')
# 1km watch circle, approx 111 km in 1 deg latitude 1 km is 1/111 of a deg
if 0:
wc = Circle((x,y), 1./111, alpha=0.2)
wc.set_label('1 km Watch Circle')
p = PatchCollection([wc], alpha=0.2)
ax.add_collection(p)
leg1 = ax.legend([wc], '1 km Watch Circle', loc='lower left')
ax.set_xlabel('Longitude (deg)')
ax.set_ylabel('Latitude (deg)')
ax.axis('equal')
# keep tick formatting from defaulting scienitific with offsets
from matplotlib.ticker import FormatStrFormatter
ax.xaxis.set_major_formatter(FormatStrFormatter('%g'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
# limit number of ticks on x-axis to 5 to allow for the squeeze
locator = ax.xaxis.get_major_locator()
locator._nbins=5
ax.xaxis.set_major_locator(locator)
# legend
leg = ax.legend((l2,l1), ('Anchor Position', 'Current Buoy GPS') , loc='upper left')
ltext = leg.get_texts() # all the text.Text instance in the legend
llines = leg.get_lines() # all the lines.Line2D instance in the legend
frame = leg.get_frame() # the patch.Rectangle instance surrounding the legend
frame.set_facecolor('0.80') # set the frame face color to light gray
frame.set_alpha(0.5) # set alpha low to see through
setp(ltext, fontsize='small') # the legend text fontsize
setp(llines, linewidth=1.5) # the legend linewidth
# leg.draw_frame(False) # don't draw the legend frame
#######################################
# YYYY_MM
#######################################
title_str = ' '.join([pi['id'].upper(), si['description']])
if plot_type=='latest' or plot_type=='monthly':
print ' ... : %s' % (yyyy_mm_str,)
ax.set_title(title_str+' -- ' + yyyy_mm_str)
dns = date2num(this_month)
dne = date2num(next_month-datetime.timedelta(seconds=1))
idx = (dn>=dns) & (dn<=dne)
c = ax.scatter(gps_lon[idx],gps_lat[idx],c=dn[idx],
cmap=cm.jet,vmin=dns,vmax=dne)
cbar = fig.colorbar(c, ticks=DayLocator(range(0,32,2)),format=DateFormatter('%m/%d'))
fn = '_'.join([pi['id'], si['id'], yyyy_mm_str+'.png'])
ofn = os.path.join(img_dir, pi['id'], fn) # /home/haines/rayleigh/img/meet
savefig(ofn)
# remove scatter instances and colorbar axis for next plot
c.remove()
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.20, bottom=0.10, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
#######################################
# Last 30 days
#######################################
if plot_type=='latest':
print ' ... Last 30 days'
ax.set_title(title_str+'\n Last 30 days from '+last_dt_str)
dns = date2num(dt[-1])-30
dne = date2num(dt[-1])
idx = (dn>=dns) & (dn<=dne)
c = ax.scatter(gps_lon[idx],gps_lat[idx],c=dn[idx],
cmap=cm.jet,vmin=dns,vmax=dne)
cbar = fig.colorbar(c, ticks=DayLocator(range(0,32,2)),format=DateFormatter('%m/%d'))
fn = '_'.join([pi['id'], si['id'], 'last30days.png'])
ofn = os.path.join(img_dir, fn) # /home/haines/rayleigh/img/
savefig(ofn)
# remove scatter instances and colorbar axis for next plot
c.remove()
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.20, bottom=0.10, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
#######################################
# Last 7 days
#######################################
if plot_type=='latest':
print ' ... Last 7 days'
ax.set_title(title_str+'\n Last 7 days from '+last_dt_str)
dns = date2num(dt[-1])-7
dne = date2num(dt[-1])
idx = (dn>=dns) & (dn<=dne)
c = ax.scatter(gps_lon[idx],gps_lat[idx],c=dn[idx],
cmap=cm.jet,vmin=dns,vmax=dne)
cbar = fig.colorbar(c, ticks=DayLocator(range(0,32,1)),format=DateFormatter('%m/%d'))
fn = '_'.join([pi['id'], si['id'], 'last07days.png'])
ofn = os.path.join(img_dir, fn) # /home/haines/rayleigh/img
savefig(ofn)
# remove scatter instances and colorbar axis for next plot
c.remove()
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.20, bottom=0.10, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
#######################################
# Last 1 day (24hrs)
#######################################
if plot_type=='latest':
print ' ... Last 1 days'
ax.set_title(title_str+'\n Last 24 hours from '+last_dt_str)
dns = date2num(dt[-1])-1
dne = date2num(dt[-1])
idx = (dn>=dns) & (dn<=dne)
c = ax.scatter(gps_lon[idx],gps_lat[idx],c=dn[idx],
cmap=cm.jet,vmin=dns,vmax=dne)
cbar = fig.colorbar(c, ticks=HourLocator(range(0,25,1)),format=DateFormatter('%H'))
fn = '_'.join([pi['id'], si['id'], 'last01days.png'])
ofn = os.path.join(img_dir, fn) # /home/haines/rayleigh/img
savefig(ofn)
# remove scatter instances and colorbar axis for next plot
c.remove()
fig.delaxes(fig.axes[1])
fig.subplots_adjust(left=0.20, bottom=0.10, right=0.9, top=0.9, wspace=0.1, hspace=0.1)