forked from pbuckner/XplaneNoaaWeather
/
gfs.py
168 lines (138 loc) · 5.85 KB
/
gfs.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
"""
NOAA weather daemon server
---
X-plane NOAA GFS weather plugin.
Copyright (C) 2012-2015 Joan Perez i Cauhe
---
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or any later version.
"""
import sys
import subprocess
try:
from weathersource import GribWeatherSource
from c import c
except ImportError:
from .weathersource import GribWeatherSource
from .c import c
class GFS(GribWeatherSource):
"""NOAA GFS weather source"""
base_url = 'https://nomads.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/gfs.'
download = False
download_wait = 0
def __init__(self, conf):
self.variable_list = conf.gfs_variable_list
super(GFS, self).__init__(conf)
@classmethod
def get_download_url(cls, datecycle, cycle, forecast):
"""Returns the GRIB download url add .idx or .grib to the end"""
filename = 'gfs.t%02dz.pgrb2full.0p50.f0%02d' % (cycle, forecast)
url = '%s%s/%02d/atmos/%s' % (cls.base_url, datecycle, cycle, filename)
return url
@classmethod
def get_cache_filename(cls, datecycle, cycle, forecast):
"""Returns the proper filename for the cache"""
return '%s_gfs.t%02dz.pgrb2full.0p50.f0%02d' % (datecycle, cycle, forecast)
def parse_grib_data(self, filepath, lat, lon):
"""Executes wgrib2 and parses its output"""
args = ['-s',
'-lon',
'%f' % (lon),
'%f' % (lat),
filepath
]
kwargs = {'stdout': subprocess.PIPE}
if self.conf.spinfo:
kwargs.update({'startupinfo': self.conf.spinfo, 'shell': True})
print("Calling subprocess with {}, {}".format([self.conf.wgrib2bin] + args, kwargs))
p = subprocess.Popen([self.conf.wgrib2bin] + args, **kwargs)
print("result of grib data subprocess is p={}".format(p))
it = iter(p.stdout)
data = {}
clouds = {}
pressure = False
tropo = {}
for line in it:
if sys.version_info.major == 2:
r = line[:-1].split(':')
else:
r = line.decode('utf-8')[:-1].split(':')
# Level, variable, value
level, variable, value = [r[4].split(' '), r[3], r[7].split(',')[2].split('=')[1]]
if len(level) > 1:
if level[1] == 'cloud':
# cloud layer
clouds.setdefault(level[0], {})
if len(level) > 3 and variable == 'PRES':
clouds[level[0]][level[2]] = value
else:
# level coverage/temperature
clouds[level[0]][variable] = value
elif level[1] == 'mb':
# wind levels
data.setdefault(level[0], {})
data[level[0]][variable] = value
elif level[0] == 'mean':
if variable == 'PRMSL':
pressure = c.pa2inhg(float(value))
elif level[0] == 'tropopause':
tropo[variable] = value
windlevels = []
cloudlevels = []
# Let data ready to push on datarefs.
# Convert wind levels
if sys.version_info.major == 2:
wind_levels = data.iteritems()
else:
wind_levels = iter(data.items())
for level, wind in wind_levels:
if 'UGRD' in wind and 'VGRD' in wind:
hdg, vel = c.c2p(float(wind['UGRD']), float(wind['VGRD']))
alt = int(c.mb2alt(float(level)))
# Optional varialbes
temp, dev, rh, dew = False, False, False, False
# Temperature
if 'TMP' in wind:
temp = float(wind['TMP'])
dev = c.isaDev(alt, temp)
# Relative Humidity
if 'RH' in wind:
rh = float(wind['RH'])
if temp and rh:
dew = c.dewpoint(temp, rh)
windlevels.append([alt, hdg, c.ms2knots(vel), {'temp': temp,
'dev': dev,
'rh': rh,
'dew': dew,
'gust': 0}])
# get tropopause info from F386 wind level if not already available
if not tropo and float(level) == 200 and temp:
tropo = {'PRES': level, 'TMP': wind['TMP']}
# Convert cloud level
for level in clouds:
level = clouds[level]
if 'top' in level and 'bottom' in level:
top, bottom = float(level['top']), float(level['bottom'])
# print "XPGFS: top: %.0fmbar %.0fm, bottom: %.0fmbar %.0fm %d%%" % (top * 0.01, c.mb2alt(top * 0.01), bottom * 0.01, c.mb2alt(bottom * 0.01), cover)
cover = float(level.get(next((k for k in level.keys() if k in ('LCDC', 'MCDC', 'HCDC')), None)) or 0)
if cover:
cloudlevels.append([c.mb2alt(bottom * 0.01) * 0.3048, c.mb2alt(top * 0.01) * 0.3048, cover])
windlevels.sort()
cloudlevels.sort()
# tropo
if all(k in tropo.keys() for k in ('PRES', 'TMP')):
alt = int(c.mb2alt(float(tropo['PRES'])*0.01))
temp = float(tropo['TMP'])
dev = c.isaDev(alt, temp)
tropo ={'alt': float(alt), 'temp': temp, 'dev': dev}
else:
tropo = {}
data = {
'winds': windlevels,
'clouds': cloudlevels,
'pressure': pressure,
'tropo': tropo
}
return data