/
tavgMap.py
executable file
·380 lines (320 loc) · 10.4 KB
/
tavgMap.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/python
import matplotlib as mpl
mpl.use('Agg')
import os, sys, shapefile, glob
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import LineCollection
from mpl_toolkits.basemap import Basemap
import matplotlib.font_manager as font_manager
from PIL import Image
from pyproj import Proj, transform
def divlookup(dfile, division, year, month):
'''
Function divlookup: pulls division data from CMB data (i.e., text file)
'''
cmd = 'grep '+division+'02'+year+' '+dfile
#print cmd
dval = os.popen(cmd)
dval = float(dval.read().split()[month])
return dval
def gmtColormap(fileName):
import colorsys
import numpy as N
try:
f = open(fileName)
except:
print "file ",fileName, "not found"
return None
lines = f.readlines()
f.close()
x = []
r = []
g = []
b = []
colorModel = "RGB"
for l in lines:
ls = l.split()
if l[0] == "#":
if ls[-1] == "HSV":
colorModel = "HSV"
continue
else:
continue
if ls[0] == "B" or ls[0] == "F" or ls[0] == "N":
pass
else:
x.append(float(ls[0]))
r.append(float(ls[1]))
g.append(float(ls[2]))
b.append(float(ls[3]))
xtemp = float(ls[4])
rtemp = float(ls[5])
gtemp = float(ls[6])
btemp = float(ls[7])
x.append(xtemp)
r.append(rtemp)
g.append(gtemp)
b.append(btemp)
nTable = len(r)
x = N.array( x , N.float32)
r = N.array( r , N.float32)
g = N.array( g , N.float32)
b = N.array( b , N.float32)
if colorModel == "HSV":
for i in range(r.shape[0]):
rr,gg,bb = colorsys.hsv_to_rgb(r[i]/360.,g[i],b[i])
r[i] = rr ; g[i] = gg ; b[i] = bb
if colorModel == "HSV":
for i in range(r.shape[0]):
rr,gg,bb = colorsys.hsv_to_rgb(r[i]/360.,g[i],b[i])
r[i] = rr ; g[i] = gg ; b[i] = bb
if colorModel == "RGB":
r = r/255.
g = g/255.
b = b/255.
xNorm = (x - x[0])/(x[-1] - x[0])
red = []
blue = []
green = []
for i in range(len(x)):
red.append([xNorm[i],r[i],r[i]])
green.append([xNorm[i],g[i],g[i]])
blue.append([xNorm[i],b[i],b[i]])
colorDict = {"red":red, "green":green, "blue":blue}
return (colorDict)
def int2str(mm):
if(mm == '00'): ms = 'No Data'
if(mm == '01'): ms = 'January'
if(mm == '02'): ms = 'February'
if(mm == '03'): ms = 'March'
if(mm == '04'): ms = 'April'
if(mm == '05'): ms = 'May'
if(mm == '06'): ms = 'June'
if(mm == '07'): ms = 'July'
if(mm == '08'): ms = 'August'
if(mm == '09'): ms = 'September'
if(mm == '10'): ms = 'October'
if(mm == '11'): ms = 'November'
if(mm == '12'): ms = 'December'
return ms
fdate = sys.argv[1] #(expects format like: 201301)
yyyy = fdate[0:4]
mm = fdate[4:]
ms = int2str(mm)
labeldate = ms+' '+yyyy
if(ms == 'No Data'):
labeldate = ms
yyyy = '0000'
imgsize = sys.argv[2] #(expects 620, 1000, DIY, HD, or HDSD)
dfile = glob.glob('./Data/*tmp*')
dfile = dfile[0]
path = './Fonts/Trebuchet_MS.ttf'
propr = font_manager.FontProperties(fname=path)
path = './Fonts/Trebuchet_MS_Bold.ttf'
propb = font_manager.FontProperties(fname=path)
if(imgsize == '620'):
figxsize = 8.62
figysize = 5.56
figdpi = 72
lllon, lllat, urlon, urlat = [-119.8939, 21.6678, -62.3094, 49.1895]
logo_image = './noaa_logo_42.png'
logo_x = 566
logo_y = 4
framestat = 'False'
base_img = './CONUS_620_BaseLayer.png'
line_img = './CONUS_620_stateLines.png'
bgcol = '#F5F5F5'
cmask = "./Custom_mask.png"
if(imgsize == '1000'):
figxsize = 13.89
figysize = 8.89
figdpi = 72
lllon, lllat, urlon, urlat = [-119.8939, 21.6678, -62.3094, 49.1895]
logo_image = './noaa_logo_42.png'
logo_x = 946
logo_y = 4
framestat = 'False'
base_img = './CONUS_1000_BaseLayer.png'
line_img = './CONUS_1000_stateLines.png'
bgcol = '#F5F5F5'
cmask = "./Custom_mask.png"
if(imgsize == 'DIY'):
figxsize = 13.655
figysize = 8.745
figdpi = 300
lllon, lllat, urlon, urlat = [-119.8939, 21.6678, -62.3094, 49.1895]
logo_image = './noaa_logo_42.png'
logo_x = 946
logo_y = 4
framestat = 'False'
base_img = './CONUS_DIY_BaseLayer.png'
line_img = './CONUS_DIY_stateLines.png'
bgcol = '#F5F5F5'
cmask = "./Custom_mask.png"
if(imgsize == 'HD'):
figxsize = 21.33
figysize = 10.25
figdpi = 72
lllon, lllat, urlon, urlat = [-126.95182, 19.66787, -52.88712, 46.33016]
logo_image = './noaa_logo_100.png'
logo_x = 1421
logo_y = 35
framestat = 'True'
base_img = './CONUS_HD_BaseLayer.png'
line_img = './CONUS_HD_stateLines.png'
framestat = 'False'
bgcol = '#F5F5F5'
cmask = "./Custom_HD_mask.png"
if(imgsize == 'HDSD'):
figxsize = 16
figysize = 9.75
figdpi = 72
lllon, lllat, urlon, urlat = [-120.8000, 19.5105, -57.9105, 48.9905]
logo_image = './noaa_logo_100.png'
logo_x = 1037
logo_y = 35
framestat = 'True'
base_img = './CONUS_HDSD_BaseLayer.png'
line_img = './CONUS_HDSD_stateLines.png'
framestat = 'False'
bgcol = '#F5F5F5'
cmask = "./Custom_HDSD_mask.png"
if(imgsize == 'GEO'):
figxsize = 13.655
figysize = 8.745
figdpi = 300
lllon, lllat, urlon, urlat = [-179.9853516, 14.9853516, -59.9853516, 74.9853516]
framestat = 'False'
base_img = './trans.tif'
bgcol = 'none'
fig = plt.figure(figsize=(figxsize,figysize))
# create an axes instance, leaving room for colorbar at bottom.
ax1 = fig.add_axes([0.0,0.0,1.0,1.0], frameon=framestat)#, axisbg=bgcol)
ax1.spines['left'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['top'].set_visible(False)
#Set up the base map for everything except the geotif
if(imgsize != 'GEO'):
# Create Map and Projection Coordinates
kwargs = {'epsg' : '5070',
'resolution' : 'i',
'llcrnrlon' : lllon,
'llcrnrlat' : lllat,
'urcrnrlon' : urlon,
'urcrnrlat' : urlat,
'lon_0' : -96.,
'lat_0' : 23.,
'lat_1' : 29.5,
'lat_2' : 45.5,
'area_thresh' : 15000,
'ax' : ax1,
'fix_aspect' : False
}
#Set up the base map for the geotif
if(imgsize == 'GEO'):
# Create Map and Projection Coordinates
kwargs = {'epsg' : '4326',
'resolution' : 'i',
'llcrnrlon' : lllon,
'llcrnrlat' : lllat,
'urcrnrlon' : urlon,
'urcrnrlat' : urlat,
'lon_0' : -119.9853516,
'lat_0' : 44.9853516,
'area_thresh' : 15000,
'ax' : ax1,
'fix_aspect' : False
}
#Set up the Basemap
m =Basemap(**kwargs)
#Add the BaseLayer image 1st pass
outline_im = Image.open(base_img)
m.imshow(outline_im, origin='upper', aspect='auto')
cdict1 = gmtColormap('./CPT/temperature_0-100.cpt')
valmax = 100.
valmin = 0.
cwidth = valmax - valmin #used to determine where a given data value lies in the span of the color ramp (0-100=100, 20-80=60 and so on)
cmap_temp = LinearSegmentedColormap('cmap_temp', cdict1)
if(mm != '00'):
#Now read in the Climate Division Shapes and fill the basemap
r = shapefile.Reader(r"./Shapefiles/GIS_OFFICIAL_CLIM_DIVISIONS")
shapes = r.shapes()
records = r.records()
for record, shape in zip(records,shapes):
lons,lats = zip(*shape.points)
data = np.array(m(lons, lats)).T
if len(shape.parts) == 1:
segs = [data,]
else:
segs = []
for i in range(1,len(shape.parts)):
index = shape.parts[i-1]
index2 = shape.parts[i]
segs.append(data[index:index2])
segs.append(data[index2:])
lines = LineCollection(segs,antialiaseds=(1,))
#Now obtain the data in a given poly and assign a color to the value
div = str(record[5])
#print record
dval = divlookup(dfile,div,yyyy,int(mm))
#if(dval > valmax): dval = valmax - 0.1
lines.set_facecolors(cmap_temp([dval/cwidth]))
lines.set_edgecolors(cmap_temp([dval/cwidth]))
lines.set_linewidth(0.25)
ax1.add_collection(lines)
if(imgsize == 'GEO'):
inProj = Proj(init='epsg:3338')
outProj = Proj(init='epsg:4326')
#Now read in the Alaska Climate Division Shapes and fill the basemap
s = shapefile.Reader(r"./Shapefiles/AK_divisions_NAD83")
shapes = s.shapes()
records = s.records()
for record, shape in zip(records,shapes):
lons,lats = zip(*shape.points)
lons,lats = transform(inProj,outProj,lons,lats)
data = np.array(m(lons, lats)).T
if len(shape.parts) == 1:
segs = [data,]
else:
segs = []
for i in range(1,len(shape.parts)):
index = shape.parts[i-1]
index2 = shape.parts[i]
segs.append(data[index:index2])
segs.append(data[index2:])
lines = LineCollection(segs,antialiaseds=(1,))
#Now obtain the data in a given poly and assign a color to the value
div = str(record[0])
if(len(div) < 2): div = '0'+div
div = '50'+div
dval = divlookup(dfile,div,yyyy,int(mm))
lines.set_facecolors(cmap_temp([dval/cwidth]))
lines.set_edgecolors(cmap_temp([dval/cwidth]))
lines.set_linewidth(0.25)
ax1.add_collection(lines)
if(imgsize != 'GEO'):
#Add the custom mask
omask_im = Image.open(cmask)
m.imshow(omask_im, origin='upper', alpha=1., zorder=10, aspect='auto', interpolation='nearest')
#Add the Line image
outline_im = Image.open(line_img)
m.imshow(outline_im, origin='upper', alpha=0.75, zorder=10, aspect='auto')
#Add the NOAA logo (except for DIY)
if(imgsize == '620' or imgsize == '1000' or imgsize == 'HD' or imgsize == 'HDSD'):
logo_im = Image.open(logo_image)
height = logo_im.size[1]
# We need a float array between 0-1, rather than
# a uint8 array between 0-255 for the logo
logo_im = np.array(logo_im).astype(np.float) / 255
fig.figimage(logo_im, logo_x, logo_y, zorder=10)
outpng = "temporary_map.png"
outtif = "temporary_map.tif"
if(imgsize == '620' or imgsize == '1000' or imgsize == 'DIY'):
plt.savefig(outpng,dpi=figdpi, orientation='landscape', bbox_inches='tight', pad_inches=0.00)
if(imgsize == 'HD' or imgsize =='HDSD'):
plt.savefig(outpng, dpi=figdpi, orientation='landscape')#, bbox_inches='tight', pad_inches=0.01)
if(imgsize == 'GEO'):
plt.savefig(outtif, dpi=figdpi, orientation='landscape', transparent='true', bbox_inches='tight', pad_inches=0.00)