metradar 0.1.3__py3-none-any.whl → 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,310 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- '''
4
- @File : construct_aws_refvpr_mainprog.py
5
- @Time : 2023/08/19 20:58:59
6
- @Author : Wenjian Zhu
7
- @Version : 1.0
8
- @Email : kevin2075@163.com
9
- '''
10
-
11
- from retrieve_cmadaas import cmadaas_obs_by_time_range_and_id,cmadaas_get_radar_vol,cmadaas_sounding_by_time,cmadaas_get_radar_3dref
12
- import pandas as pd
13
- import geo_transforms_pyart as geotrans
14
- import math
15
- import numpy as np
16
- import os
17
- import configparser
18
- from make_mosaic_mp_archive import MAKE_RADAR_MOSAIC
19
- from multiprocessing import freeze_support
20
- from datetime import datetime,timedelta
21
- import xarray as xr
22
- import numpy.ma as MA
23
- import matplotlib.pyplot as plt
24
- from parse_pal import parse_pro
25
- from matplotlib.ticker import (MultipleLocator)
26
- from matplotlib import font_manager
27
- from comm_func import geopotential_to_height
28
- import warnings
29
- warnings.filterwarnings("ignore")
30
-
31
- # 一键生成VPR数据和自动站数据,并绘制图形
32
- #数据来源:天擎
33
-
34
-
35
- if __name__ == "__main__":
36
- freeze_support()
37
- start_time = '20230703190000'
38
- # end_time = '20230703200000'
39
- end_time = '20230704020000'
40
- time_range = "[%s,%s]"%(start_time, end_time)
41
-
42
- # 读取自动站雨量数据
43
- # A7606, A7607, A7055, A7617
44
- staid = 'A7607'
45
- outpath = '/Users/wenjianzhu/Downloads/testvpr'
46
- outpath_fmt = outpath + os.sep + 'fmt'
47
- outpath_tlogp = outpath + os.sep + 'tlogp'
48
- outpath_sta = './output/VPR'
49
- outpath_pic = './output/VPR'
50
- outpath_ref = './output/VPR'
51
- outname_sta= '%s.csv'%staid
52
- outname_ref = 'p3_vpr_%s_cams.nc'%staid
53
- # outpath_mosaic = outpath + os.sep + 'mosaic'
54
- outpath_mosaic = outpath + os.sep + 'cams'
55
- if not os.path.exists(outpath):
56
- os.makedirs(outpath)
57
- if not os.path.exists(outpath_fmt):
58
- os.makedirs(outpath_fmt)
59
- if not os.path.exists(outpath_tlogp):
60
- os.makedirs(outpath_tlogp)
61
-
62
- # #第一步,从天擎下载自动站数据
63
-
64
- # elements='Station_Name,Station_Id_C,Station_Id_d,lat,lon,Datetime,PRE,PRE_1h'
65
-
66
- # data_code = 'SURF_CHN_MUL_MIN'
67
-
68
- # # 读取数据
69
- # data = cmadaas_obs_by_time_range_and_id(time_range=time_range, data_code = data_code,elements=elements,sta_ids = staid)
70
- # if data is None:
71
- # print('required data is None, please check the site number!')
72
-
73
- # sta_lat = data['lat'][0]
74
- # sta_lon = data['lon'][0]
75
- # sta_name = data['Station_Name'][0]
76
-
77
- # # data.to_csv(outpath_sta + os.sep + outname_sta,index=False)
78
- # data2 = data.set_index('Datetime')
79
- # # data2['PRE_1h'][0]=0
80
-
81
-
82
- # diff_rain =[]
83
- # diff_rain.append(0)
84
-
85
-
86
- # # PRE_1h表示当前小时的累计雨量
87
- # # pre_5min表示当前5分钟的累计雨量
88
- # # pre_1min表示当前1分钟的累计雨量
89
- # # accsum表示从起始时刻到当前时刻的累计雨量
90
- # # 时间均为UTC时间
91
-
92
- # # diff()为求差,mode()为获取众数
93
- # # steps 为数据的时间间隔,单位为分钟
94
- # steps = int(data['Datetime'].diff().mode()[0].seconds/60)
95
- # difrain_name = 'pre_%dmin'%steps
96
- # for nn in np.arange(0,data2.shape[0]-1):
97
-
98
- # if data2['PRE_1h'][nn+1] >= data2['PRE_1h'][nn]:
99
- # diff_rain.append(round(data2['PRE_1h'][nn+1]-data2['PRE_1h'][nn],2))
100
- # else:
101
- # diff_rain.append(round(data2['PRE_1h'][nn+1],2))
102
- # newpd = pd.DataFrame(diff_rain,columns=[difrain_name],index=data2.index)
103
- # # 如果间隔是1分钟,那么还需要求出5分钟的雨量
104
- # if steps == 1:
105
- # newpd['pre_5min'] = newpd[difrain_name].rolling(5).sum()
106
- # newpd['pre_5min'] = newpd['pre_5min'].round(2)
107
- # else:
108
- # pass
109
- # newindex = [tt for tt in newpd.index if tt.minute%5==0]
110
- # newpd['accsum'] = newpd[difrain_name].cumsum()
111
- # newpd['accsum'] = newpd['accsum'].round(2)
112
- # newpd['PRE_1h'] = data2['PRE_1h']
113
- # newpd['PRE'] = data2['PRE']
114
- # newpd['lat'] = data2['lat']
115
- # newpd['lon'] = data2['lon']
116
- # newpd['staname']=data2['Station_Name']
117
- # newpd.to_csv(outpath_sta + os.sep + outname_sta,index=True)
118
-
119
- # # 第二步,从离自动站最近的探空站中获取探空数据,提取零度层高度和-20度层高度
120
- # # 读取探空站信息,获取经纬度、站号等信息
121
- # # tlogpinfo = pd.read_csv('../common/stationinfo_new/china_tlogp_stations_m3.txt',delimiter=r"\s+",skiprows=3,names=['stanum','lon','lat','alt','num2'])
122
-
123
- # # tmpdata['stanum'].values[0] int
124
- # # staid_tlogp = str(tmpdata['stanum'].values[0])
125
- # tlogpdata = cmadaas_sounding_by_time(times='20230704000000')
126
- # allstas = np.unique(tlogpdata['Station_Id_C'])
127
- # alllons=[]
128
- # alllats=[]
129
- # #获取所有站点的经纬度信息
130
- # for ts in allstas:
131
- # tmpd = tlogpdata[tlogpdata['Station_Id_C']==ts]
132
- # curlat = tmpd['Lat'].values[0]
133
- # curlon = tmpd['Lon'].values[0]
134
- # alllons.append(curlon)
135
- # alllats.append(curlat)
136
-
137
- # x,y= geotrans.geographic_to_cartesian_aeqd(lon=alllons,lat=alllats,lon_0=sta_lon,lat_0=sta_lat)
138
- # dis = [math.sqrt(pow(x[k],2) + pow(y[k],2))/1000 for k in range(len(x))]
139
- # flag = np.array(dis) <= min(dis)+0.1
140
- # tmpts = allstas[flag]
141
- # tmpdata = tlogpdata[tlogpdata['Station_Id_C']==tmpts[0]]
142
- # tmpdata = tmpdata.sort_values(by='PRS_HWC',ascending=False)
143
- # tmpdata.dropna(subset=['PRS_HWC'],inplace=True)
144
- # tmpdata.to_csv(outpath_tlogp + os.sep + 'tlogp_%s.csv'%tmpts[0],index=False)
145
- #查找离零度层和-20度层最近的高度
146
- # 读取探空数据
147
- tmpdata = pd.read_csv(outpath_tlogp + os.sep + 'tlogp_57328.csv')
148
- flag = np.array(abs(tmpdata['TEM'])) <= abs(tmpdata['TEM']).min()+0.01
149
- z0 = tmpdata['GPH'][flag].values[0]
150
- flag = np.array(abs(tmpdata['TEM']+20)) <= abs(tmpdata['TEM']+20).min()+0.01
151
- z20 = tmpdata['GPH'][flag].values[0]
152
-
153
- z0 = geopotential_to_height(z0*9.80665)
154
- z20 = geopotential_to_height(z20*9.80665)
155
-
156
- # 第三步,从本地文件读取cams三维拼图数据
157
-
158
- # 根据自动站数据和三维拼图数据构建VPR并绘制图形
159
-
160
- # 从三维拼图数据中获取格点的时间序列
161
- data = pd.read_csv(outpath_sta+os.sep+outname_sta,index_col=0)
162
- sta_lat = data['lat'][0]
163
- sta_lon = data['lon'][0]
164
- sta_name = data['staname'][0]
165
- startt = datetime.strptime(start_time,'%Y%m%d%H%M%S')
166
- endt = datetime.strptime(end_time,'%Y%m%d%H%M%S')
167
- curt = startt
168
- allref=[]
169
- grd_height = None
170
- file_times=[]
171
- while curt <= endt:
172
-
173
- curname = 'Z_RADR_I_CHINA_' + curt.strftime('%Y%m%d%H%M00') + '_O_DOR_MOC_CAP_FMT_rewrite.nc'
174
- curmosaic_path = outpath_mosaic
175
- if not os.path.exists(curmosaic_path + os.sep + curname):
176
- print('file not exist: %s'%(curmosaic_path + os.sep + curname))
177
- curt += timedelta(minutes=6)
178
- continue
179
- ref = xr.open_dataset(outpath_mosaic + os.sep + curname)
180
-
181
- grd_height = ref.z.values
182
- ref2 = ref.interp(lat=sta_lat,lon=sta_lon)['ref_3d'].values
183
- # 对ref2进行线性插值
184
- tmpdf = pd.DataFrame(ref2,columns=['ref_raw'])
185
- tmpdf['ref_new'] = tmpdf['ref_raw'].interpolate(method='slinear')
186
- ref2 = tmpdf['ref_new'].values
187
- allref.append(ref2)
188
- file_times.append(curt)
189
- curt += timedelta(minutes=6)
190
- ref.close()
191
-
192
- print(curname + ' added!')
193
- allref = np.array(allref)
194
- # allref = allref.reshape(allref.shape[0],allref.shape[2])
195
-
196
- alldata = MA.masked_array(allref, mask=allref==-9999)
197
-
198
- xrdata = xr.Dataset({
199
- 'dbz':(['z', 'time'], alldata.T, {'long name':'time-height dBZ'})},
200
- coords={'z':grd_height, 'time':file_times},
201
- attrs={'lat':sta_lat, 'lon':sta_lon})
202
-
203
- xrdata.to_netcdf(outpath_ref + os.sep + outname_ref)
204
- print('ref data success!')
205
-
206
- # 画图
207
-
208
- oridf = pd.read_csv(outpath_sta+os.sep+outname_sta)#,index_col=0
209
-
210
- oridf['Datetime'] = pd.to_datetime(oridf['Datetime'], format="%Y-%m-%d %H:%M:%S")
211
- oridf = oridf.set_index('Datetime')
212
- newindex = [tt for tt in oridf.index if tt.minute%5==0]
213
- df = oridf.loc[newindex]
214
- # df.set_index('staname',inplace=True)
215
- df.reset_index(inplace=True)
216
-
217
- #将缺失的时间进行插值处理
218
- helper = pd.DataFrame({'Datetime': pd.date_range(start=df['Datetime'].min(), end=df['Datetime'].max(),freq='300s')})
219
- newdf = pd.merge(df, helper, on='Datetime', how='outer').sort_values('Datetime')
220
- newdf['accsum'] = newdf['accsum'].interpolate(method='linear')
221
-
222
- # ref_colorfile='gr2_colors/default_BR_PUP1.pal'
223
- ref_colorfile = 'gr2_colors/BR_WDTB_Bright.pal'
224
- outdic= parse_pro(ref_colorfile)
225
- cmap=outdic['cmap']
226
- norm=outdic['norm']
227
- units=outdic['units']
228
- # from pyart.graph import common
229
- # cmapname = 'pyart_NWSRef'
230
- # cmap = common.parse_cmap(cmapname, 'reflectivity')
231
-
232
- data = xr.open_dataset(outpath_ref + os.sep + outname_ref)
233
-
234
- data = data.rolling(z=2, time=2, min_periods=1, center=True).mean()
235
-
236
- font_path = 'simsun.ttc'
237
- font_manager.fontManager.addfont(font_path)
238
- prop = font_manager.FontProperties(fname=font_path)
239
-
240
- plt.rcParams["font.size"] = 12
241
- plt.rcParams["font.sans-serif"] = prop.get_name()
242
- fig = plt.figure(figsize=(10,6))
243
- ax1 = fig.add_axes([0.1,0.18,0.8,0.3])#位置[左,下,右,上]
244
- ax3 = fig.add_axes([0.1,0.64,0.8,0.3])#位置[左,下,右,上]
245
- ax2 = ax3.twinx()
246
- ax1.minorticks_on()
247
-
248
-
249
- cb_ax = fig.add_axes([0.25, 0.08, 0.5, 0.03])
250
-
251
- # data.dbz.plot(ax=ax1,cmap=cmap,norm=norm,)
252
- grid_y,grid_x=np.meshgrid(np.arange(0,data.dbz.shape[1]),data.z.values,)
253
- pcm = ax1.pcolormesh(grid_y,grid_x,data.dbz,cmap=cmap,norm=norm)
254
-
255
- z0h = ax1.plot(np.arange(0,data.dbz.shape[1]),np.ones(data.dbz.shape[1])*z0,'y--',linewidth=2,label='0度层高度')
256
- z20h=ax1.plot(np.arange(0,data.dbz.shape[1]),np.ones(data.dbz.shape[1])*z20,'r--',linewidth=2,label='-20度层高度')
257
-
258
-
259
- ax1.legend(loc='upper right')
260
-
261
- ax1.tick_params(axis='x',which='minor',length=3,width=0.8,)
262
- ax1.tick_params(axis='x',which='major',length=5,width=1,)
263
- cb = plt.colorbar(mappable=pcm,cax=cb_ax,extend='both',ticks=np.arange(-10,85,5),orientation='horizontal')
264
- cb.set_label('反射率因子 dBZ',fontsize=12)
265
- ah1=ax2.plot(newdf['accsum'].values,'r',linewidth=2,label='累计雨量')
266
- ah2=ax3.bar(np.arange(0,newdf.shape[0]),newdf['pre_5min'],label='5分钟雨量')
267
- ax2.legend(loc='upper right')
268
- ax3.legend(loc='upper left')
269
- ax3.minorticks_on()
270
- ax3.tick_params(axis='x',which='minor',length=3,width=0.8,)
271
- ax3.tick_params(axis='x',which='major',length=5,width=1,)
272
- ax3.xaxis.set_minor_locator(MultipleLocator(1))
273
- ax1.set_xlim([0,data.dbz.shape[1]+1])
274
- ax2.set_xlim([0,newdf.shape[0]])
275
- ax1.grid('y')
276
- ax2.grid('y')
277
-
278
- ax1.set_ylabel('距离地面的高度(米)')
279
- ax1.set_title('单点回波强度时间-高度图(%.2f°N,%.2f°E)'%(data.lat,data.lon),fontsize=12)
280
- ax2.set_ylabel('累计雨量(毫米)',color='r')
281
- ax3.set_ylabel('5分钟雨量(毫米)',color=[59/255,117/255,175/255])
282
-
283
- tmpdate = pd.to_datetime(data.time)+ timedelta(hours=8)
284
- dates1 = [date.strftime('%H:%M') for date in tmpdate]
285
- dates1[0] = tmpdate.min().strftime('%H:%M \n%Y-%m-%d')
286
-
287
- datestr = dates1[::5]
288
- tmpd = tmpdate[::5]
289
- datestr[-1] = tmpd.max().strftime('%H:%M \n%Y-%m-%d')
290
-
291
- ax1.set_xticks(np.arange(0,data.time.shape[0],5))
292
- ax1.set_xticklabels(datestr)
293
-
294
- ax1.set_ylim([0,20000])
295
- ax1.set_yticks(np.arange(0,20000,2500))
296
-
297
- tmpdate = pd.to_datetime(newdf['Datetime'])+ timedelta(hours=8)
298
- dates2 = [date.strftime('%H:%M') for date in tmpdate]
299
- dates2[0] = tmpdate.min().strftime('%H:%M \n%Y-%m-%d')
300
- dates2[-1] = tmpdate.max().strftime('%H:%M \n%Y-%m-%d')
301
-
302
- ax2.set_xticks(np.arange(0,newdf.shape[0],6))
303
-
304
- ax2.set_xticklabels(dates2[::6])
305
- ax3.set_xlabel('时间(时:分,北京时)')
306
- ax2.set_title('5分钟雨量(柱)、自动站累积雨量(红实线), 站号:%s,%s(%.2f°N,%.2f°E)'%(staid,sta_name,sta_lat,sta_lon),fontsize=12)
307
- # plt.figtext(0.73,0.02,'国家气象中心-天气预报技术研发室制作',fontsize=10)
308
- plt.savefig(outpath_pic + os.sep + outname_ref.replace('.nc','.svg'))#,dpi=600
309
- print(outpath_pic + os.sep + outname_ref.replace('.nc','.svg') + ' saved!')
310
- plt.show()