toy_ASFC.py 32.5 KB
Newer Older
sbiri's avatar
sbiri committed
1 2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
3 4 5 6 7
"""
example of running AirSeaFluxCode with
1. R/V data (data_all.csv) or
2. one day era5 hourly data (era5_r360x180.nc)
compute fluxes
sbiri's avatar
sbiri committed
8 9
output NetCDF4 or csv
and statistics in "outS".txt
10 11 12 13 14 15 16 17 18 19 20 21 22 23

@author: sbiri
"""
#%% import packages
import matplotlib.pyplot as plt
import netCDF4 as nc
import numpy as np
import pandas as pd
from AirSeaFluxCode import AirSeaFluxCode
import time
from tabulate import tabulate
#%%
def reject_outliers(data, m=2):
    x = np.copy(data)
24
    x = np.where(np.abs(x-np.nanmean(x)) < m*np.nanstd(x), x, np.nan)
25 26 27
    return x


sbiri's avatar
sbiri committed
28
def toy_ASFC(inF, outF, outS, gustIn, cskinIn, tolIn, meth, qmIn, LIn, stdIn):
29
    """
30 31
    Example routine of how to run AirSeaFluxCode with the test data given
    and save output either as .csv or NetCDF
32 33 34 35 36 37 38

    Parameters
    ----------
    inF : str
        input filename either data_all.csv or era5_r360x180.nc
    outF : str
        output filename
sbiri's avatar
sbiri committed
39 40
    outS : str
        output statistics filename
41 42 43 44 45
    gustIn : float
        gustiness option e.g. [1, 1.2, 800]
    cskinIn : int
        cool skin option input 0 or 1
    tolIn : float
46
        tolerance input option e.g. ['all', 0.01, 0.01, 1e-05, 1e-3, 0.1, 0.1]
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    meth : str
        parametrisation method option

    Returns
    -------
    res : float
        AirSeaFluxCode output
    lon : float
        longitude from input netCDF file
    lat : float
        latitude from input netCDF file

    """
    if (inF == "data_all.csv"):
        #%% load data_all
        inDt = pd.read_csv("data_all.csv")
        date = np.asarray(inDt["Date"])
        lon = np.asarray(inDt["Longitude"])
        lat = np.asarray(inDt["Latitude"])
        spd = np.asarray(inDt["Wind speed"])
sbiri's avatar
sbiri committed
67
        spd = spd+np.random.normal(0, stdIn[0], spd.shape)
68
        t = np.asarray(inDt["Air temperature"])
sbiri's avatar
sbiri committed
69
        t = t+np.random.normal(0, stdIn[1], t.shape)
70
        sst = np.asarray(inDt["SST"])
sbiri's avatar
sbiri committed
71
        sst = sst+np.random.normal(0, stdIn[2], sst.shape)
72
        rh = np.asarray(inDt["RH"])
sbiri's avatar
sbiri committed
73
        rh = rh+np.random.normal(0, stdIn[3], rh.shape)
74 75 76 77 78 79 80
        p = np.asarray(inDt["P"])
        sw = np.asarray(inDt["Rs"])
        hu = np.asarray(inDt["zu"])
        ht = np.asarray(inDt["zt"])
        hin = np.array([hu, ht, ht])
        del hu, ht, inDt
        #%% run AirSeaFluxCode
81
        res = AirSeaFluxCode(spd, t, sst, lat=lat, hum=['rh', rh], P=p,
82
                             hin=hin, Rs=sw, tol=tolIn, gust=gustIn,
sbiri's avatar
sbiri committed
83
                             cskin=cskinIn, meth=meth, qmeth=qmIn, L=LIn, n=30)
sbiri's avatar
sbiri committed
84
        flg = res["flag"]
85 86 87 88 89 90 91 92

    elif (inF == 'era5_r360x180.nc'):
        #%% load era5_r360x180.nc
        fid = nc.Dataset(inF)
        lon = np.array(fid.variables["lon"])
        lat = np.array(fid.variables["lat"])
        tim = np.array(fid.variables["time"])
        lsm = np.array(fid.variables["lsm"])
93
        icon = np.array(fid.variables["siconc"])
sbiri's avatar
sbiri committed
94
        lsm = np.where(lsm > 0, np.nan, 1) # reverse 0 on land 1 over ocean
sbiri's avatar
sbiri committed
95
        icon = np.where(icon == 0, 1, np.nan) # keep only ice-free regions
96
        msk = lsm*icon
97
        T = np.array(fid.variables["t2m"])*msk
sbiri's avatar
sbiri committed
98
        T = T+np.random.normal(0, stdIn[1], T.shape)
99
        Td = np.array(fid.variables["d2m"])*msk
sbiri's avatar
sbiri committed
100
        Td = Td+np.random.normal(0, stdIn[3], T.shape)
sbiri's avatar
sbiri committed
101
        sst = np.array(fid.variables["sst"])
102
        sst = np.where(sst < -100, np.nan, sst)*msk
sbiri's avatar
sbiri committed
103
        sst = sst+np.random.normal(0, stdIn[2], sst.shape)
104 105 106 107 108 109 110
        p = np.array(fid.variables["msl"])*msk/100 # to set hPa
        lw = np.array(fid.variables["strd"])*msk/60/60
        sw = np.array(fid.variables["ssrd"])*msk/60/60
        u = np.array(fid.variables["u10"])
        v = np.array(fid.variables["v10"])
        fid.close()
        spd = np.sqrt(np.power(u, 2)+np.power(v, 2))*msk
sbiri's avatar
sbiri committed
111
        spd = spd+np.random.normal(0, stdIn[0], spd.shape)
112
        del u, v, fid
113 114 115
        hin = np.array([10, 2, 2])
        latIn = np.tile(lat, (len(lon), 1)).T.reshape(len(lon)*len(lat))
        date = np.copy(tim)
116

117
        #%% run AirSeaFluxCode
118 119
        res = np.zeros((len(tim),len(lon)*len(lat), 39))
        flg = np.empty((len(tim),len(lon)*len(lat)), dtype="object")
120 121
        # reshape input and run code
        for x in range(len(tim)):
sbiri's avatar
sbiri committed
122
            a = AirSeaFluxCode(spd.reshape(len(tim), len(lon)*len(lat))[x, :],
123 124 125 126 127 128 129 130
                               T.reshape(len(tim), len(lon)*len(lat))[x, :],
                               sst.reshape(len(tim), len(lon)*len(lat))[x, :],
                               lat=latIn,
                               hum=['Td', Td.reshape(len(tim), len(lon)*len(lat))[x, :]],
                               P=p.reshape(len(tim), len(lon)*len(lat))[x, :],
                               hin=hin,
                               Rs=sw.reshape(len(tim), len(lon)*len(lat))[x, :],
                               Rl=lw.reshape(len(tim), len(lon)*len(lat))[x, :],
sbiri's avatar
sbiri committed
131
                               gust=gustIn, cskin=cskinIn, tol=tolIn,
sbiri's avatar
sbiri committed
132 133 134 135 136
                               meth=meth, qmeth=qmIn, n=30, L=LIn)
            temp = a.loc[:,"tau":"rh"]
            temp = temp.to_numpy()
            flg[x, :] = a["flag"]
            res[x, :, :] = temp
137 138 139 140 141
            del a, temp
            n = np.shape(res)
            res = np.asarray([res[:, :, i]*msk.reshape(n[0], n[1])
                              for i in range(39)])
            res = np.moveaxis(res, 0, -1)
sbiri's avatar
sbiri committed
142
        flg = np.where(np.isnan(msk.reshape(len(tim), len(lon)*len(lat))),
sbiri's avatar
sbiri committed
143
                        'm', flg)
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
    if (outF[-3:] == '.nc'):
        if (inF == 'era5_r360x180.nc'):
            #%% save NetCDF4
            fid = nc.Dataset(outF,'w', format='NETCDF4')
            fid.createDimension('lon', len(lon))
            fid.createDimension('lat', len(lat))
            fid.createDimension('time', None)
            longitude = fid.createVariable('lon', 'f4', 'lon')
            latitude = fid.createVariable('lat', 'f4', 'lat')
            Date = fid.createVariable('Date', 'i4', 'time')
            tau = fid.createVariable('tau', 'f4', ('time','lat','lon'))
            sensible = fid.createVariable('shf', 'f4', ('time','lat','lon'))
            latent = fid.createVariable('lhf', 'f4', ('time','lat','lon'))
            monob = fid.createVariable('MO', 'f4', ('time','lat','lon'))
            cd = fid.createVariable('cd', 'f4', ('time','lat','lon'))
            cdn = fid.createVariable('cdn', 'f4', ('time','lat','lon'))
            ct = fid.createVariable('ct', 'f4', ('time','lat','lon'))
            ctn = fid.createVariable('ctn', 'f4', ('time','lat','lon'))
            cq = fid.createVariable('cq', 'f4', ('time','lat','lon'))
            cqn = fid.createVariable('cqn', 'f4', ('time','lat','lon'))
            tsrv = fid.createVariable('tsrv', 'f4', ('time','lat','lon'))
            tsr = fid.createVariable('tsr', 'f4', ('time','lat','lon'))
            qsr = fid.createVariable('qsr', 'f4', ('time','lat','lon'))
            usr = fid.createVariable('usr', 'f4', ('time','lat','lon'))
            psim = fid.createVariable('psim', 'f4', ('time','lat','lon'))
            psit = fid.createVariable('psit', 'f4', ('time','lat','lon'))
            psiq = fid.createVariable('psiq', 'f4', ('time','lat','lon'))
            u10n = fid.createVariable('u10n', 'f4', ('time','lat','lon'))
            t10n = fid.createVariable('t10n', 'f4', ('time','lat','lon'))
            tv10n = fid.createVariable('tv10n', 'f4', ('time','lat','lon'))
            q10n = fid.createVariable('q10n', 'f4', ('time','lat','lon'))
            zo = fid.createVariable('zo', 'f4', ('time','lat','lon'))
            zot = fid.createVariable('zot', 'f4', ('time','lat','lon'))
            zoq = fid.createVariable('zoq', 'f4', ('time','lat','lon'))
            urefs = fid.createVariable('uref', 'f4', ('time','lat','lon'))
            trefs = fid.createVariable('tref', 'f4', ('time','lat','lon'))
            qrefs = fid.createVariable('qref', 'f4', ('time','lat','lon'))
            itera = fid.createVariable('iter', 'i4', ('time','lat','lon'))
            dter = fid.createVariable('dter', 'f4', ('time','lat','lon'))
            dqer = fid.createVariable('dqer', 'f4', ('time','lat','lon'))
            dtwl = fid.createVariable('dtwl', 'f4', ('time','lat','lon'))
            qair = fid.createVariable('qair', 'f4', ('time','lat','lon'))
            qsea = fid.createVariable('qsea', 'f4', ('time','lat','lon'))
            Rl = fid.createVariable('Rl', 'f4', ('time','lat','lon'))
            Rs = fid.createVariable('Rs', 'f4', ('time','lat','lon'))
            Rnl = fid.createVariable('Rnl', 'f4', ('time','lat','lon'))
190 191 192
            ug = fid.createVariable('ug', 'f4', ('time','lat','lon'))
            Rib = fid.createVariable('Rib', 'f4', ('time','lat','lon'))
            rh = fid.createVariable('rh', 'f4', ('time','lat','lon'))
sbiri's avatar
sbiri committed
193
            flag = fid.createVariable('flag', 'U1', ('time','lat','lon'))
194 195 196 197

            longitude[:] = lon
            latitude[:] = lat
            Date[:] = tim
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
            tau[:] = res[:, :, 0].reshape((len(tim), len(lat), len(lon)))*msk
            sensible[:] = res[:, :, 1].reshape((len(tim), len(lat), len(lon)))*msk
            latent[:] = res[:, :, 2].reshape((len(tim), len(lat), len(lon)))*msk
            monob[:] = res[:, :, 3].reshape((len(tim), len(lat), len(lon)))*msk
            cd[:] = res[:, :, 4].reshape((len(tim), len(lat), len(lon)))*msk
            cdn[:] = res[:, :, 5].reshape((len(tim), len(lat), len(lon)))*msk
            ct[:] = res[:, :, 6].reshape((len(tim), len(lat), len(lon)))*msk
            ctn[:] = res[:, :, 7].reshape((len(tim), len(lat), len(lon)))*msk
            cq[:] = res[:, :, 8].reshape((len(tim), len(lat), len(lon)))*msk
            cqn[:] = res[:, :, 9].reshape((len(tim), len(lat), len(lon)))*msk
            tsrv[:] = res[:, :, 10].reshape((len(tim), len(lat), len(lon)))*msk
            tsr[:] = res[:, :, 11].reshape((len(tim), len(lat), len(lon)))*msk
            qsr[:] = res[:, :, 12].reshape((len(tim), len(lat), len(lon)))*msk
            usr[:] = res[:, :, 13].reshape((len(tim), len(lat), len(lon)))*msk
            psim[:] = res[:, :, 14].reshape((len(tim), len(lat), len(lon)))*msk
            psit[:] = res[:, :, 15].reshape((len(tim), len(lat), len(lon)))*msk
            psiq[:] = res[:, :, 16].reshape((len(tim), len(lat), len(lon)))*msk
            u10n[:] = res[:, :, 17].reshape((len(tim), len(lat), len(lon)))*msk
            t10n[:] = res[:, :, 18].reshape((len(tim), len(lat), len(lon)))*msk
            tv10n[:] = res[:, :, 19].reshape((len(tim), len(lat), len(lon)))*msk
            q10n[:] = res[:, :, 20].reshape((len(tim), len(lat), len(lon)))*msk
            zo[:] = res[:, :, 21].reshape((len(tim), len(lat), len(lon)))*msk
            zot[:] = res[:, :, 22].reshape((len(tim), len(lat), len(lon)))*msk
            zoq[:] = res[:, :, 23].reshape((len(tim), len(lat), len(lon)))*msk
            urefs[:] = res[:, :, 24].reshape((len(tim), len(lat), len(lon)))*msk
            trefs[:] = res[:, :, 25].reshape((len(tim), len(lat), len(lon)))*msk
            qrefs[:] = res[:, :, 26].reshape((len(tim), len(lat), len(lon)))*msk
            itera[:] = res[:, :, 27].reshape((len(tim), len(lat), len(lon)))*msk
            dter[:] = res[:, :, 28].reshape((len(tim), len(lat), len(lon)))*msk
            dqer[:] = res[:, :, 29].reshape((len(tim), len(lat), len(lon)))*msk
            dtwl[:] = res[:, :, 30].reshape((len(tim), len(lat), len(lon)))*msk
            qair[:] = res[:, :, 31].reshape((len(tim), len(lat), len(lon)))*msk
            qsea[:] = res[:, :, 32].reshape((len(tim), len(lat), len(lon)))*msk
            Rl[:] = res[:, :, 33].reshape((len(tim), len(lat), len(lon)))*msk
            Rs[:] = res[:, :, 34].reshape((len(tim), len(lat), len(lon)))*msk
            Rnl[:] = res[:, :, 35].reshape((len(tim), len(lat), len(lon)))*msk
            ug[:] = res[:, :, 36].reshape((len(tim), len(lat), len(lon)))*msk
            Rib[:] = res[:, :, 37].reshape((len(tim), len(lat), len(lon)))*msk
            rh[:] = res[:, :, 38].reshape((len(tim), len(lat), len(lon)))*msk
            flag[:] = flg.reshape((len(tim), len(lat), len(lon)))

239 240 241 242
            longitude.long_name = 'Longitude'
            longitude.units = 'degrees East'
            latitude.long_name = 'Latitude'
            latitude.units = 'degrees North'
sbiri's avatar
sbiri committed
243 244
            Date.long_name = "gregorian"
            Date.units = "hours since 1900-01-01 00:00:00.0"
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
            tau.long_name = 'Wind stress'
            tau.units = 'N/m^2'
            sensible.long_name = 'Sensible heat fluxe'
            sensible.units = 'W/m^2'
            latent.long_name = 'Latent heat flux'
            latent.units = 'W/m^2'
            monob.long_name = 'Monin-Obukhov length'
            monob.units = 'm'
            cd.long_name = 'Drag coefficient'
            cd.units = ''
            cdn.long_name = 'Neutral Drag coefficient'
            cdn.units = ''
            ct.long_name = 'Heat exchange coefficient'
            ct.units = ''
            ctn.long_name = 'Neutral Heat exchange coefficient'
            ctn.units = ''
            cq.long_name = 'Moisture exchange coefficient'
            cq.units = ''
            cqn.long_name = 'Neutral Moisture exchange coefficient'
            cqn.units = ''
            tsrv.long_name = 'star virtual temperature'
            tsrv.units = 'degrees Celsius'
            tsr.long_name = 'star temperature'
            tsr.units = 'degrees Celsius'
            qsr.long_name = 'star specific humidity'
            qsr.units = 'gr/kgr'
            usr.long_name = 'friction velocity'
            usr.units = 'm/s'
            psim.long_name = 'Momentum stability function'
            psit.long_name = 'Heat stability function'
sbiri's avatar
sbiri committed
275
            psiq.long_name = 'moisture stability function'
276 277 278 279 280 281 282
            u10n.long_name = '10m neutral wind speed'
            u10n.units = 'm/s'
            t10n.long_name = '10m neutral temperature'
            t10n.units = 'degrees Celsius'
            tv10n.long_name = '10m neutral virtual temperature'
            tv10n.units = 'degrees Celsius'
            q10n.long_name = '10m neutral specific humidity'
283
            q10n.units = 'kgr/kgr'
284 285 286 287 288 289 290 291 292 293 294
            zo.long_name = 'momentum roughness length'
            zo.units = 'm'
            zot.long_name = 'temperature roughness length'
            zot.units = 'm'
            zoq.long_name = 'moisture roughness length'
            zoq.units = 'm'
            urefs.long_name = 'wind speed at ref height'
            urefs.units = 'm/s'
            trefs.long_name = 'temperature at ref height'
            trefs.units = 'degrees Celsius'
            qrefs.long_name = 'specific humidity at ref height'
295
            qrefs.units = 'kgr/kgr'
296
            qair.long_name = 'specific humidity of air'
297
            qair.units = 'kgr/kgr'
298
            qsea.long_name = 'specific humidity over water'
299
            qsea.units = 'kgr/kgr'
300
            itera.long_name = 'number of iterations'
301 302 303 304 305 306 307 308 309 310 311 312 313 314
            Rl.long_name = 'downward longwave radiation'
            Rl.units = 'W/m^2'
            Rs.long_name = 'downward shortwave radiation'
            Rs.units = 'W/m^2'
            Rnl.long_name = 'downward net longwave radiation'
            Rnl.units = 'W/m^2'
            ug.long_name = 'gust wind speed'
            ug.units = 'm/s'
            Rib.long_name = 'bulk Richardson number'
            rh.long_name = 'relative humidity'
            rh.units = '%'
            flag.long_name = ('flag "n" normal, "u": u10n < 0, "q": q10n < 0,'
                              '"l": zol<0.01, "m": missing, "i": points that'
                              'have not converged')
315 316 317 318 319 320
            fid.close()
            #%% delete variables
            del longitude, latitude, Date, tau, sensible, latent, monob, cd, cdn
            del ct, ctn, cq, cqn, tsrv, tsr, qsr, usr, psim, psit, psiq, u10n, t10n
            del tv10n, q10n, zo, zot, zoq, urefs, trefs, qrefs, itera, dter, dqer
            del qair, qsea, Rl, Rs, Rnl, dtwl
321
            del tim, T, Td, p, lw, sw, lsm, spd, hin, latIn, icon, msk
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
        else:
            #%% save NetCDF4
            fid = nc.Dataset(outF,'w', format='NETCDF4')
            fid.createDimension('lon', len(lon))
            fid.createDimension('lat', len(lat))
            fid.createDimension('time', None)
            longitude = fid.createVariable('lon', 'f4', 'lon')
            latitude = fid.createVariable('lat', 'f4', 'lat')
            Date = fid.createVariable('Date', 'i4', 'time')
            tau = fid.createVariable('tau', 'f4', 'time')
            sensible = fid.createVariable('shf', 'f4', 'time')
            latent = fid.createVariable('lhf', 'f4', 'time')
            monob = fid.createVariable('MO', 'f4', 'time')
            cd = fid.createVariable('cd', 'f4', 'time')
            cdn = fid.createVariable('cdn', 'f4', 'time')
            ct = fid.createVariable('ct', 'f4', 'time')
            ctn = fid.createVariable('ctn', 'f4', 'time')
            cq = fid.createVariable('cq', 'f4', 'time')
            cqn = fid.createVariable('cqn', 'f4', 'time')
            tsrv = fid.createVariable('tsrv', 'f4', 'time')
            tsr = fid.createVariable('tsr', 'f4', 'time')
            qsr = fid.createVariable('qsr', 'f4', 'time')
            usr = fid.createVariable('usr', 'f4', 'time')
            psim = fid.createVariable('psim', 'f4', 'time')
            psit = fid.createVariable('psit', 'f4', 'time')
            psiq = fid.createVariable('psiq', 'f4', 'time')
            u10n = fid.createVariable('u10n', 'f4', 'time')
            t10n = fid.createVariable('t10n', 'f4', 'time')
            tv10n = fid.createVariable('tv10n', 'f4', 'time')
            q10n = fid.createVariable('q10n', 'f4', 'time')
            zo = fid.createVariable('zo', 'f4', 'time')
            zot = fid.createVariable('zot', 'f4', 'time')
            zoq = fid.createVariable('zoq', 'f4', 'time')
            urefs = fid.createVariable('uref', 'f4', 'time')
            trefs = fid.createVariable('tref', 'f4', 'time')
            qrefs = fid.createVariable('qref', 'f4', 'time')
            itera = fid.createVariable('iter', 'i4', 'time')
            dter = fid.createVariable('dter', 'f4', 'time')
            dqer = fid.createVariable('dqer', 'f4', 'time')
361
            dtwl = fid.createVariable('dtwl', 'f4', 'time')
362 363 364 365 366
            qair = fid.createVariable('qair', 'f4', 'time')
            qsea = fid.createVariable('qsea', 'f4', 'time')
            Rl = fid.createVariable('Rl', 'f4', 'time')
            Rs = fid.createVariable('Rs', 'f4', 'time')
            Rnl = fid.createVariable('Rnl', 'f4', 'time')
367 368 369
            ug = fid.createVariable('ug', 'f4', 'time')
            Rib = fid.createVariable('Rib', 'f4', 'time')
            rh = fid.createVariable('rh', 'f4', 'time')
sbiri's avatar
sbiri committed
370
            flag = fid.createVariable('flag', 'U1', 'time')
371 372 373 374

            longitude[:] = lon
            latitude[:] = lat
            Date[:] = date
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
            tau[:] = res["tau"]
            sensible[:] = res["shf"]
            latent[:] = res["lhf"]
            monob[:] = res["L"]
            cd[:] = res["cd"]
            cdn[:] = res["cdn"]
            ct[:] = res["ct"]
            ctn[:] = res["ctn"]
            cq[:] = res["cq"]
            cqn[:] = res["cqn"]
            tsrv[:] = res["tsrv"]
            tsr[:] = res["tsr"]
            qsr[:] = res["qsr"]
            usr[:] = res["usr"]
            psim[:] = res["psim"]
            psit[:] = res["psit"]
            psiq[:] = res["psiq"]
            u10n[:] = res["u10n"]
            t10n[:] = res["t10n"]
            tv10n[:] = res["tv10n"]
            q10n[:] = res["q10n"]
            zo[:] = res["zo"]
            zot[:] = res["zot"]
            zoq[:] = res["zoq"]
            urefs[:] = res["uref"]
            trefs[:] = res["tref"]
            qrefs[:] = res["qref"]
            itera[:] = res["iteration"]
            dter[:] = res["dter"]
            dqer[:] = res["dqer"]
            dtwl[:] = res["dtwl"]
            qair[:] = res["qair"]
            qsea[:] = res["qsea"]
            Rl[:] = res["Rl"]
            Rs[:] = res["Rs"]
            Rnl[:] = res["Rnl"]
            ug[:] = res["ug"]
            Rib[:] = res["Rib"]
            rh[:] = res["rh"]
            flag[:] = res["flag"]

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
            longitude.long_name = 'Longitude'
            longitude.units = 'degrees East'
            latitude.long_name = 'Latitude'
            latitude.units = 'degrees North'
            Date.long_name = "calendar date"
            Date.units = "YYYYMMDD UTC"
            tau.long_name = 'Wind stress'
            tau.units = 'N/m^2'
            sensible.long_name = 'Sensible heat fluxe'
            sensible.units = 'W/m^2'
            latent.long_name = 'Latent heat flux'
            latent.units = 'W/m^2'
            monob.long_name = 'Monin-Obukhov length'
            monob.units = 'm'
            cd.long_name = 'Drag coefficient'
            cd.units = ''
            cdn.long_name = 'Neutral Drag coefficient'
            cdn.units = ''
            ct.long_name = 'Heat exchange coefficient'
            ct.units = ''
            ctn.long_name = 'Neutral Heat exchange coefficient'
            ctn.units = ''
            cq.long_name = 'Moisture exchange coefficient'
            cq.units = ''
            cqn.long_name = 'Neutral Moisture exchange coefficient'
            cqn.units = ''
            tsrv.long_name = 'star virtual temperature'
            tsrv.units = 'degrees Celsius'
            tsr.long_name = 'star temperature'
            tsr.units = 'degrees Celsius'
            qsr.long_name = 'star specific humidity'
            qsr.units = 'gr/kgr'
            usr.long_name = 'friction velocity'
            usr.units = 'm/s'
            psim.long_name = 'Momentum stability function'
            psit.long_name = 'Heat stability function'
            u10n.long_name = '10m neutral wind speed'
            u10n.units = 'm/s'
            t10n.long_name = '10m neutral temperature'
            t10n.units = 'degrees Celsius'
            tv10n.long_name = '10m neutral virtual temperature'
            tv10n.units = 'degrees Celsius'
            q10n.long_name = '10m neutral specific humidity'
459
            q10n.units = 'kgr/kgr'
460 461 462 463 464 465 466 467 468 469 470
            zo.long_name = 'momentum roughness length'
            zo.units = 'm'
            zot.long_name = 'temperature roughness length'
            zot.units = 'm'
            zoq.long_name = 'moisture roughness length'
            zoq.units = 'm'
            urefs.long_name = 'wind speed at ref height'
            urefs.units = 'm/s'
            trefs.long_name = 'temperature at ref height'
            trefs.units = 'degrees Celsius'
            qrefs.long_name = 'specific humidity at ref height'
471
            qrefs.units = 'kgr/kgr'
472
            qair.long_name = 'specific humidity of air'
473
            qair.units = 'kgr/kgr'
474
            qsea.long_name = 'specific humidity over water'
475
            qsea.units = 'kgr/kgr'
476
            itera.long_name = 'number of iterations'
477 478 479 480 481 482 483 484 485 486 487 488 489 490
            Rl.long_name = 'downward longwave radiation'
            Rl.units = 'W/m^2'
            Rs.long_name = 'downward shortwave radiation'
            Rs.units = 'W/m^2'
            Rnl.long_name = 'downward net longwave radiation'
            Rnl.units = 'W/m^2'
            ug.long_name = 'gust wind speed'
            ug.units = 'm/s'
            Rib.long_name = 'bulk Richardson number'
            rh.long_name = 'relative humidity'
            rh.units = '%'
            flag.long_name = ('flag "n" normal, "u": u10n < 0, "q": q10n < 0,'
                              '"l": zol<0.01, "m": missing, "i": points that'
                              'have not converged')
491 492 493 494 495
            fid.close()
            #%% delete variables
            del longitude, latitude, Date, tau, sensible, latent, monob, cd, cdn
            del ct, ctn, cq, cqn, tsrv, tsr, qsr, usr, psim, psit, psiq, u10n, t10n
            del tv10n, q10n, zo, zot, zoq, urefs, trefs, qrefs, itera, dter, dqer
496 497
            del qair, qsea, Rl, Rs, Rnl, ug, rh, Rib
            del t, date, p, sw, spd, hin, sst
498 499
    else:
        #%% save as .csv
500 501 502 503
        res.insert(loc=0, column='date', value=date)
        res.insert(loc=1, column='lon', value=lon)
        res.insert(loc=2, column='lat', value=lat)
        res.to_csv(outF)
504 505 506 507 508 509 510
    return res, lon, lat
#%% run function
start_time = time.perf_counter()
#------------------------------------------------------------------------------
inF = input("Give input file name (data_all.csv or era5_r360x180.nc): \n")
meth = input("Give prefered method: \n")
while meth not in ["S80", "S88", "LP82", "YT96", "UA", "LY04", "C30", "C35",
sbiri's avatar
sbiri committed
511
                   "ecmwf","Beljaars"]:
512 513 514 515 516 517
    print("method unknown")
    meth = input("Give prefered method: \n")
else:
    meth = meth #[meth]
ext = meth+"_"
#------------------------------------------------------------------------------
sbiri's avatar
sbiri committed
518 519 520 521 522 523 524 525 526 527 528
qmIn = input("Give prefered method for specific humidity: \n")
if (qmIn == ''):
    qmIn = 'Buck2' # default
while qmIn not in ["HylandWexler", "Hardy", "Preining", "Wexler",
                   "GoffGratch", "WMO", "MagnusTetens", "Buck", "Buck2",
                   "WMO2018", "Sonntag", "Bolton", "IAPWS", "MurphyKoop"]:
    print("method unknown")
    meth = input("Give prefered method: \n")
else:
    qmIn = qmIn
#------------------------------------------------------------------------------
sbiri's avatar
sbiri committed
529 530 531 532
gustIn = input("Give gustiness option (to switch it off enter 0;"
               " to set your own input use the form [1, B, zi]"
               " i.e. [1, 1, 800] or "
               "to use default press enter): \n")
533 534 535 536 537 538 539 540 541 542 543 544 545 546
if (gustIn == ''):
    gustIn = None
    ext = ext+'gust_'
else:
    gustIn = np.asarray(eval(gustIn), dtype=float)
    if ((np.all(gustIn) == 0)):
        ext = ext+'nogust_'
    else:
        ext = ext+'gust_'
#------------------------------------------------------------------------------
cskinIn = input("Give cool skin option (to use default press enter): \n")
if (cskinIn == ''):
    cskinIn = None
    if ((cskinIn == None) and (meth == "S80" or meth == "S88" or meth == "LP82"
sbiri's avatar
sbiri committed
547 548
                               or meth == "YT96" or meth == "UA"
                               or meth == "LY04")):
549 550
        cskinIn = 0
        ext = ext+'noskin_'
sbiri's avatar
sbiri committed
551 552
    elif ((cskinIn == None) and (meth == "C30" or meth == "C35"
                                 or meth == "ecmwf" or meth == "Beljaars")):
553 554 555 556 557 558 559 560 561 562 563
        cskinIn = 1
        ext = ext+'skin_'
else:
    cskinIn = int(cskinIn)
    if (cskinIn == 0):
        ext = ext+'noskin_'
    elif (cskinIn == 1):
        ext = ext+'skin_'
#------------------------------------------------------------------------------
tolIn = input("Give tolerance option (to use default press enter): \n")
if (tolIn == ''):
sbiri's avatar
sbiri committed
564
    tolIn = ['all', 0.01, 0.01, 1e-05, 1e-3, 0.1, 0.1]
565 566 567 568
else:
    tolIn = eval(tolIn)
ext = ext+'tol'+tolIn[0]
#------------------------------------------------------------------------------
sbiri's avatar
sbiri committed
569
LIn = input("Give prefered method for L (tsrv or Rb): \n")
sbiri's avatar
sbiri committed
570
if (LIn == ''):
sbiri's avatar
sbiri committed
571 572 573
    LIn = 'tsrv' # default
elif LIn not in ["tsrv", "Rb"]:
    LIn = 'tsrv' # default
sbiri's avatar
sbiri committed
574 575 576 577 578 579 580 581 582 583
else:
    LIn = LIn
#------------------------------------------------------------------------------
stdIn = input("Give noise std for spd, T, SST and Td/rh \n (e.g. [0.01, 0, 0, 0]"
              " adds noise only to spd): \n")
if (stdIn == ''):
    stdIn = [0, 0, 0, 0] # no noise added
else:
    stdIn = eval(stdIn)
#------------------------------------------------------------------------------
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
outF = input("Give path and output file name: \n")
if ((outF == '') and (inF == "data_all.csv")):
    outF = "out_"+inF[:-4]+"_"+ext+".csv"
elif ((outF == '') and (inF == "era5_r360x180.nc")):
    outF = "out_"+inF[:-3]+"_"+ext+".nc"
elif ((outF[-4:] == '.csv') and (inF == 'era5_r360x180.nc')):
    outF = outF[:-4]+".nc"
elif ((outF[-3:] != '.nc') and (outF[-4:] != '.csv')):
    if (inF == "data_all.csv"):
        outF = outF+".csv"
    else:
        outF = outF+".nc"
else:
    outF = outF
#------------------------------------------------------------------------------
sbiri's avatar
sbiri committed
599 600 601 602 603 604 605 606 607
outS = input("Give path and statistics file name: \n")
if ((outS == '') and (inF == "data_all.csv")):
    outS = "RV_"+ext+"_stats.txt"
elif ((outS == '') and (inF == "era5_r360x180.nc")):
    outS = "era5_"+ext+"_stats.txt"
elif (outS[-4:] != '.txt'):
    outF = outS+".txt"

#------------------------------------------------------------------------------
608 609
print("\n run_ASFC.py, started for method "+meth)

sbiri's avatar
sbiri committed
610 611
res, lon, lat = toy_ASFC(inF, outF, outS, gustIn, cskinIn, tolIn, meth, qmIn,
                         LIn, stdIn)
612 613 614 615
print("run_ASFC.py took ", np.round((time.perf_counter()-start_time)/60, 2),
      "minutes to run")

#%% generate flux plots
sbiri's avatar
sbiri committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
# if (inF == 'era5_r360x180.nc'):
#     cm = plt.cm.get_cmap('RdYlBu')
#     ttl = ["tau (Nm$^{-2}$)", "shf (Wm$^{-2}$)", "lhf (Wm$^{-2}$)"]
#     for i in range(3):
#         plt.figure()
#         plt.contourf(lon, lat,
#                      np.nanmean(res[:, :, i], axis=0).reshape(len(lat),
#                                                               len(lon)),
#                      100, cmap=cm)
#         plt.colorbar()
#         plt.tight_layout()
#         plt.xlabel("Longitude")
#         plt.ylabel("Latitude")
#         plt.title(meth+', '+ttl[i])
#         plt.savefig('./'+ttl[i][:3]+'_'+ext+'.png', dpi=300, bbox_inches='tight')
# elif (inF == "data_all.csv"):
#     ttl = ["tau (Nm$^{-2}$)", "shf (Wm$^{-2}$)", "lhf (Wm$^{-2}$)"]
#     for i in range(3):
#         plt.figure()
#         plt.plot(res[ttl[i][:3]],'.c', markersize=1)
#         plt.title(meth)
#         plt.xlabel("points")
#         plt.ylabel(ttl[i])
#         plt.savefig('./'+ttl[i][:3]+'_'+ext+'.png', dpi=300, bbox_inches='tight')
640

sbiri's avatar
sbiri committed
641
#%% generate txt file with statistics
642 643 644 645
if ((cskinIn == None) and (meth == "S80" or meth == "S88" or meth == "LP82"
                           or meth == "YT96" or meth == "UA" or
                           meth == "LY04")):
   cskinIn = 0
sbiri's avatar
sbiri committed
646
elif ((cskinIn == None) and (meth == "C30" or meth == "C35"
647 648
                             or meth == "ecmwf" or meth == "Beljaars")):
   cskinIn = 1
sbiri's avatar
sbiri committed
649
if (np.all(gustIn == None) and (meth == "C30" or meth == "C35")):
650 651 652 653 654 655 656 657
    gustIn = [1, 1.2, 600]
elif (np.all(gustIn == None) and (meth == "UA" or meth == "ecmwf")):
    gustIn = [1, 1, 1000]
elif np.all(gustIn == None):
    gustIn = [1, 1.2, 800]
elif ((np.size(gustIn) < 3) and (gustIn == 0)):
    gust = [0, 0, 0]
if (tolIn == None):
sbiri's avatar
sbiri committed
658
    tolIn = ['all', 0.01, 0.01, 1e-05, 1e-3, 0.1, 0.1]
659

sbiri's avatar
sbiri committed
660 661

print("Input summary", file=open('./'+outS, 'a'))
662
print('input file name: {}, \n method: {}, \n gustiness: {}, \n cskin: {},'
sbiri's avatar
sbiri committed
663 664 665
      ' \n tolerance: {}, \n qmethod: {}, \n L: {}'.format(inF, meth, gustIn,
                                                           cskinIn, tolIn,
                                                           qmIn, LIn),
sbiri's avatar
sbiri committed
666
      file=open('./'+outS, 'a'))
667 668 669 670 671
ttl = np.asarray(["tau  ", "shf  ", "lhf  ", "L    ", "cd   ", "cdn  ",
                  "ct   ", "ctn  ", "cq   ", "cqn  ", "tsrv ", "tsr  ",
                  "qsr  ", "usr  ", "psim ", "psit ", "psiq ", "u10n ",
                  "t10n ", "tv10n", "q10n ", "zo   ", "zot  ", "zoq  ",
                  "urefs", "trefs", "qrefs", "itera", "dter ", "dqer ",
672 673
                  "dtwl ", "qair ", "qsea ", "Rl   ", "Rs   ", "Rnl  ",
                  "ug   ", "Rib  ", "rh   "])
674 675 676 677 678 679 680 681 682 683 684 685 686 687
header = ["var", "mean", "median", "min", "max", "5%", "95%"]
n = np.shape(res)
stats = np.copy(ttl)
if (inF == 'era5_r360x180.nc'):
    stats = np.c_[stats, np.nanmean(res.reshape(n[0]*n[1], n[2]), axis=0)]
    stats = np.c_[stats, np.nanmedian(res.reshape(n[0]*n[1], n[2]), axis=0)]
    stats = np.c_[stats, np.nanmin(res.reshape(n[0]*n[1], n[2]), axis=0)]
    stats = np.c_[stats, np.nanmax(res.reshape(n[0]*n[1], n[2]), axis=0)]
    stats = np.c_[stats, np.nanpercentile(res.reshape(n[0]*n[1], n[2]), 5,
                                          axis=0)]
    stats = np.c_[stats, np.nanpercentile(res.reshape(n[0]*n[1], n[2]), 95,
                                          axis=0)]
    print(tabulate(stats, headers=header, tablefmt="github", numalign="left",
                   floatfmt=("s", "2.2e", "2.2e", "2.2e", "2.2e", "2.2e",
sbiri's avatar
sbiri committed
688 689
                             "2.2e")), file=open('./'+outS, 'a'))
    print('-'*79+'\n', file=open('./'+outS, 'a'))
690
elif (inF == "data_all.csv"):
691 692 693 694 695 696 697
    a = res.loc[:,"tau":"rh"].to_numpy(dtype="float64").T
    stats = np.c_[stats, np.nanmean(a, axis=1)]
    stats = np.c_[stats, np.nanmedian(a, axis=1)]
    stats = np.c_[stats, np.nanmin(a, axis=1)]
    stats = np.c_[stats, np.nanmax(a, axis=1)]
    stats = np.c_[stats, np.nanpercentile(a, 5, axis=1)]
    stats = np.c_[stats, np.nanpercentile(a, 95, axis=1)]
698 699
    print(tabulate(stats, headers=header, tablefmt="github", numalign="left",
                   floatfmt=("s", "2.2e", "2.2e", "2.2e", "2.2e", "2.2e",
sbiri's avatar
sbiri committed
700 701 702
                               "2.2e")),
          file=open('./'+outS, 'a'))
    print('-'*79+'\n', file=open('./'+outS, 'a'))
703
    del a
704 705 706 707 708 709

print('input file name: {}, \n method: {}, \n gustiness: {}, \n cskin: {},'
      ' \n tolerance: {}, \n output is written in: {}'.format(inF, meth,
                                                              gustIn, cskinIn,
                                                              tolIn, outF),
      file=open('./readme.txt', 'w'))