data_util.py 9.41 KB
Newer Older
tpys's avatar
tpys committed
1
2
3
4
5
6
import os

import numpy as np
import pandas as pd
import xarray as xr

tpys's avatar
tpys committed
7
__all__ = ["save_like"]
tpys's avatar
tpys committed
8
9
10
11

pl_names = ['z', 't', 'u', 'v', 'r']
sfc_names = ['t2m', 'u10', 'v10', 'msl', 'tp']
levels = [50, 100, 150, 200, 250, 300, 400, 500, 600, 700, 850, 925, 1000]
tpys's avatar
tpys committed
12
13
degree = 0.25

14

tpys's avatar
tpys committed
15
16
17
18
19
def weighted_rmse(out, tgt):
    wlat = np.cos(np.deg2rad(tgt.lat))
    wlat /= wlat.mean()
    error = ((out - tgt) ** 2 * wlat)
    return np.sqrt(error.mean(('lat', 'lon')))
tpys's avatar
tpys committed
20
21
22
23
24
25
26


def split_variable(ds, name):
    if name in sfc_names:
        v = ds.sel(level=[name])
        v = v.assign_coords(level=[0])
        v = v.rename({"level": "level0"})
tpys's avatar
tpys committed
27
        v = v.transpose('member', 'level0', 'time', 'dtime', 'lat', 'lon')
tpys's avatar
tpys committed
28
29
30
31
32
33
34
35
    elif name in pl_names:
        level = [f'{name}{l}' for l in levels]
        v = ds.sel(level=level)
        v = v.assign_coords(level=levels)
        v = v.transpose('member', 'level', 'time', 'dtime', 'lat', 'lon')
    return v


tpys's avatar
tpys committed
36
def save_like(output, input, step, save_dir="", input_type="hres", freq=6, split=False):
tpys's avatar
tpys committed
37
38
    if save_dir:
        os.makedirs(save_dir, exist_ok=True)
39
        step = (step+1) * freq
tpys's avatar
tpys committed
40
        init_time = pd.to_datetime(input.time.values[-1])
tpys's avatar
tpys committed
41

tpys's avatar
tpys committed
42
        if input_type.upper() == "HRES":
43
            step = (step+2) * freq
tpys's avatar
tpys committed
44
            init_time = pd.to_datetime(input.time.values[0])
tpys's avatar
tpys committed
45

tpys's avatar
tpys committed
46
        ds = xr.DataArray(
47
48
            output[None],
            dims=['time', 'step', 'level', 'lat', 'lon'],
tpys's avatar
tpys committed
49
50
            coords=dict(
                time=[init_time],
51
                step=[step],
tpys's avatar
tpys committed
52
53
54
55
                level=input.level,
                lat=input.lat.values,
                lon=input.lon.values,
            )
tpys's avatar
tpys committed
56
57
        ).astype(np.float32)

tpys's avatar
tpys committed
58
59
60
61
62
63
64
        if split:
            def rename(name):
                if name == "tp":
                    return "TP06"
                elif name == "r":
                    return "RH"
                return name.upper()
tpys's avatar
tpys committed
65

tpys's avatar
tpys committed
66
67
68
69
70
71
            new_ds = []
            for k in pl_names + sfc_names:
                v = split_variable(ds, k)
                v.name = rename(k)
                new_ds.append(v)
            ds = xr.merge(new_ds, compat="no_conflicts")
tpys's avatar
tpys committed
72

73
74
        save_name = os.path.join(save_dir, f'{step:03d}.nc')
        # print(f'Save to {save_name} ...')
tpys's avatar
tpys committed
75
        ds.to_netcdf(save_name)
tpys's avatar
tpys committed
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
def make_era5_input(init_time, data_dir, save_dir):   
    ds = []
    init_time =  pd.to_datetime(init_time)
    hist_time = init_time - pd.Timedelta(hours=6)
    print(f"init_time: {init_time}")
    level = []

    for name in pl_names + sfc_names:
        data_name = os.path.join(data_dir, name, f'{init_time.year}')
        v = xr.open_zarr(data_name)
        v = v.sel(time=[hist_time, init_time])
        v = v.rename({name: 'data'})
        v.attrs = {}                
        ds.append(v)

        if name in pl_names:
            level.extend([f'{name.lower()}{l}' for l in levels])

        if name in sfc_names:
            level.append(name.lower())
        
    ds = xr.concat(ds, 'level')
    ds = ds.assign_coords(level=level)  

    os.makedirs(save_dir, exist_ok=True)
    save_name = os.path.join(save_dir, init_time.strftime("input.%Y%m%d.t%H.nc"))
    print(f"save to {save_name} ...")
    ds = ds.astype(np.float32)
    ds.to_netcdf(save_name)    


tpys's avatar
tpys committed
109
110
111
def make_hres_input(init_time, data_dir, save_dir):
    lat = np.linspace(-90, 90, int(180/degree)+1, dtype=np.float32)
    lon = np.arange(0, 360, degree, dtype=np.float32)
tpys's avatar
tpys committed
112
113
114

    input = []
    level = []
tpys's avatar
tpys committed
115

tpys's avatar
tpys committed
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
    for name in pl_names + sfc_names:
        src_name = '{}_{}'.format(name, init_time.strftime("%Y%m%d%H.nc"))
        src_file = os.path.join(data_dir, src_name)

        if not os.path.exists(src_file):
            return

        try:
            v = xr.open_dataset(src_file)
            v = v.sel(time=init_time, drop=True).data
        except:
            print(f"open {src_file} failed")
            return

        # is there nan in raw data ?
        if np.isnan(v).sum() > 0:
            print(f"{src_name} has nan value")
            return

        # interpolate to 0.25 deg
        v = v.interp(lat=lat, lon=lon, kwargs={"fill_value": "extrapolate"})

        # make sure on nan
        if np.isnan(v).sum() > 0:
            print(f"{src_name} has nan value")
            return

        # reverse pressure level
        try:
            if name in pl_names:
                v = xr.concat([v.sel(level=l) for l in levels], 'level')
                level.extend([f'{name}{l}' for l in levels])
        except:
            print("missing pressure level")
            return

        if name in sfc_names:
            level.append(name)

        # temperature in kelvin
        if name == "t":
            v = v + 273.15

        # FuXi take two step as input
        if name == "tp":
            v = v.clip(min=0, max=1000)
            zero = v * 0
            zero = zero.assign_coords(dtime=[0])
            v = xr.concat([zero, v], "dtime")

        print(f'{src_name}: {v.min().values:.2f} ~ {v.max().values:.2f}')

        v.attrs = {}
        v = v.rename({'dtime': 'time'})
        v = v.squeeze('member').drop('member')
        input.append(v)

    # concat and reshape
    input = xr.concat(input, "level")
    input = input.transpose("time", "level", "lat", "lon")
    valid_time = init_time + pd.Timedelta(hours=6)  # utc time
    v = v.assign_coords(time=[init_time, valid_time])

    # reverse latitude
    input = input.reindex(lat=input.lat[::-1])
    input = input.assign_coords(level=level)
    input.name = 'data'

    # save to nc
    print(input)
    save_name = os.path.join(save_dir, init_time.strftime("%Y%m%d-%H.nc"))
    input = input.astype(np.float32)
    input.to_netcdf(save_name)


tpys's avatar
tpys committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def make_gfs_input(init_time, data_dir, save_dir):
    pl_names = ['Z', 'T', 'U', 'V', 'R']
    sfc_names = ['t2m', 'u10', 'v10', 'msl', 'tp']

    lon = np.arange(0, 360, degree, dtype=np.float32)
    lat = np.arange(90, -90, -degree, dtype=np.float32)

    input = []
    level = []
    for name in pl_names + sfc_names:
        src_name = '{}_{}'.format(name, init_time.strftime("%Y%m%d.nc"))
        src_file = os.path.join(data_dir, src_name)

        if not os.path.exists(src_file):
            print(src_file)
206
            return
tpys's avatar
tpys committed
207
208
209
210
211

        try:
            v = xr.open_dataset(src_file)[name]
        except:
            print(f"open {src_file} failed")
212
            return
tpys's avatar
tpys committed
213
214
215

        if np.isnan(v).sum() > 0:
            print(f"{src_name} has nan value")
216
            return
tpys's avatar
tpys committed
217
218

        if v.shape[-2:] != (721, 1440):
219
220
            v = v.interp(lat=lat, lon=lon, kwargs={
                         "fill_value": "extrapolate"})
tpys's avatar
tpys committed
221
222
            if np.isnan(v).sum() > 0:
                print(f"{src_name} has nan value")
223
                return
tpys's avatar
tpys committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240

        if name in pl_names:
            level.extend([f'{name.lower()}{l}' for l in levels])

        if name in sfc_names:
            level.append(name.lower())

        if name == "Z":
            v = v * 9.8

        if name == "tp":
            v = v.clip(min=0, max=1000)

        v = v.squeeze('step').drop('step')
        v.attrs = {}
        v.name = 'data'

241
242
        vmin = v.min().values
        vmax = v.max().values
tpys's avatar
tpys committed
243
244
245

        if vmax > 1e10:
            v = v.where(v < 1e10, 0)
246
            vmax = v.max().values
tpys's avatar
tpys committed
247
248
249
250
251

        assert vmax < 1e10
        print(f'{src_name}: {v.shape}, {vmin:.2f} ~ {vmax:.2f}')
        input.append(v)

252
    input = xr.concat(input, "level")  # T
tpys's avatar
tpys committed
253
    input = input.rename({"latitude": "lat", "longitude": "lon"})
254
255
    times = [pd.to_datetime(str(t), format='%Y%m%d%H')
             for t in input.time.values]
tpys's avatar
tpys committed
256
257
258
259
260
261
262
263
264
    input = input.assign_coords(level=level)
    input = input.assign_coords(time=times)

    # TODO, we only need two time step input with dims: 2 x 70 x 721 x 1440
    save_name = os.path.join(save_dir, init_time.strftime("%Y%m%d.nc"))
    input = input.astype(np.float32)
    input.to_netcdf(save_name)


tpys's avatar
tpys committed
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
def visualize(save_name, vars=[], titles=[], vmin=None, vmax=None):
    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(len(vars), 1, figsize=(8, 6), subplot_kw={
                           "projection": ccrs.PlateCarree()})

    def plot(ax, v, title):
        v.plot(
            ax=ax,
            x='lon',
            y='lat',
            vmin=vmin,
            vmax=vmax,
            transform=ccrs.PlateCarree(),
            add_colorbar=False
        )
        # ax.coastlines()
        ax.set_title(title)
        gl = ax.gridlines(draw_labels=True, linewidth=0.5)
        gl.top_labels = False
        gl.right_labels = False

    for i, v in enumerate(vars):
        if len(vars) == 1:
            plot(ax, v, titles[i])
        else:
            plot(ax[i], v, titles[i])

    plt.savefig(save_name, bbox_inches='tight',
                pad_inches=0.1, transparent='true', dpi=200)
    plt.close()


def test_make_input():
    init_time = pd.to_datetime("20230731-12")  # must utc
    data_dir = "data/HRES"
    save_dir = "data/HRES/input"
    os.makedirs(save_dir, exist_ok=True)
tpys's avatar
tpys committed
303
    make_hres_input(init_time, data_dir, save_dir)
tpys's avatar
tpys committed
304
305
306
307
308
309
310
311


def test_visualize():
    ds = xr.open_dataarray('data/HRES/output/072.nc')
    tp = ds.sel(level='tp')
    visualize('tp.jpg', [tp], ['tp'], vmin=0, vmax=20)


312
313
314
315
316
317
318
319
320
321
322
def test_rmse(output_name, target_name):
    output = xr.open_dataarray(output_name)
    output = output.isel(time=0).sel(step=120)
    target = xr.open_dataarray(target_name)

    for level in ["z500", "t850", "t2m", "u10", "v10", "msl", "tp"]:
        out = output.sel(level=level)
        tgt = target.sel(level=level)
        rmse = weighted_rmse(out, tgt).load()
        print(f"{level.upper()} 120h rmse: {rmse:.3f}")