AirSeaFluxCode.py 17.3 KB
Newer Older
sbiri's avatar
sbiri committed
1 2
import numpy as np
import logging
sbiri's avatar
sbiri committed
3 4 5 6 7
from get_init import get_init
from hum_subs import (get_hum)
from util_subs import (kappa, CtoK, get_heights)
from flux_subs import (get_skin, get_gust, get_L, get_strs, psim_calc,
                       psit_calc, cdn_calc, cd_calc, ctcq_calc, ctcqn_calc)
sbiri's avatar
sbiri committed
8 9


sbiri's avatar
sbiri committed
10
def AirSeaFluxCode(spd, T, SST, lat=None, hum=None, P=None,
11 12 13
                   hin=18, hout=10, Rl=None, Rs=None, cskin=None,
                   gust=None, meth="S80", qmeth="Buck2", tol=None, n=10,
                   out=0, L=None):
sbiri's avatar
sbiri committed
14 15 16 17 18 19 20 21 22 23 24 25
    """ Calculates momentum and heat fluxes using different parameterizations

    Parameters
    ----------
        spd : float
            relative wind speed in m/s (is assumed as magnitude difference
            between wind and surface current vectors)
        T : float
            air temperature in K (will convert if < 200)
        SST : float
            sea surface temperature in K (will convert if < 200)
        lat : float
26 27 28
            latitude (deg), default 45deg
        hum : float
            humidity input switch 2x1 [x, values] default is relative humidity
29 30 31
            x='rh' : relative humidity in %
            x='q' : specific humidity (g/kg)
            x='Td' : dew point temperature (K)
sbiri's avatar
sbiri committed
32
        P : float
33
            air pressure (hPa), default 1013hPa
sbiri's avatar
sbiri committed
34
        hin : float
35
            sensor heights in m (array 3x1 or 3xn), default 18m
sbiri's avatar
sbiri committed
36 37 38 39 40 41
        hout : float
            output height, default is 10m
        Rl : float
            downward longwave radiation (W/m^2)
        Rs : float
            downward shortwave radiation (W/m^2)
sbiri's avatar
sbiri committed
42
        cskin : int
43 44
            0 switch cool skin adjustment off, else 1
            default is 1
45
        gust : int
46 47 48 49 50 51 52 53 54 55
            3x1 [x, beta, zi] x=1 to include the effect of gustiness, else 0
            beta gustiness parameter, beta=1 for UA, beta=1.2 for COARE
            zi PBL height (m) 600 for COARE, 1000 for UA and ERA5, 800 default
            default for COARE [1, 1.2, 600]
            default for UA, ERA5 [1, 1, 1000]
            default else [1, 1.2, 800]
        meth : str
            "S80","S88","LP82","YT96","UA","LY04","C30","C35","C40","ERA5"
        qmeth : str
            is the saturation evaporation method to use amongst
56 57
            "HylandWexler","Hardy","Preining","Wexler","GoffGratch","WMO",
            "MagnusTetens","Buck","Buck2","WMO2018","Sonntag","Bolton",
58 59 60 61 62 63 64 65 66
            "IAPWS","MurphyKoop"]
            default is Buck2
        tol : float
           4x1 or 7x1 [option, lim1-3 or lim1-6]
           option : 'flux' to set tolerance limits for fluxes only lim1-3
           option : 'ref' to set tolerance limits for height adjustment lim-1-3
           option : 'all' to set tolerance limits for both fluxes and height
                    adjustment lim1-6 ['all', 0.01, 0.01, 5e-05, 0.01, 1, 1]
           default is tol=['flux', 0.01, 1, 1]
sbiri's avatar
sbiri committed
67
        n : int
68 69 70 71
            number of iterations (defautl = 10)
        out : int
            set 0 to set points that have not converged to missing (default)
            set 1 to keep points
sbiri's avatar
sbiri committed
72 73
        L : int
           Monin-Obukhov length definition options
74 75
           "S80"  : default for S80, S88, LP82, YT96 and LY04
           "ERA5" : following ERA5 (IFS Documentation cy46r1), default for ERA5
sbiri's avatar
sbiri committed
76 77 78
    Returns
    -------
        res : array that contains
79
                       1. momentum flux (N/m^2)
sbiri's avatar
sbiri committed
80 81
                       2. sensible heat (W/m^2)
                       3. latent heat (W/m^2)
82
                       4. Monin-Obhukov length (m)
sbiri's avatar
sbiri committed
83 84 85 86 87 88 89 90 91 92 93
                       5. drag coefficient (cd)
                       6. neutral drag coefficient (cdn)
                       7. heat exhange coefficient (ct)
                       8. neutral heat exhange coefficient (ctn)
                       9. moisture exhange coefficient (cq)
                       10. neutral moisture exhange coefficient (cqn)
                       11. star virtual temperature (tsrv)
                       12. star temperature (tsr)
                       13. star humidity (qsr)
                       14. star velocity (usr)
                       15. momentum stability function (psim)
94 95 96 97 98 99 100 101 102
                       16. heat stability function (psit)
                       17. moisture stability function (psiq)
                       18. 10m neutral velocity (u10n)
                       19. 10m neutral temperature (t10n)
                       20. 10m neutral virtual temperature (tv10n)
                       21. 10m neutral specific humidity (q10n)
                       22. surface roughness length (zo)
                       23. heat roughness length (zot)
                       24. moisture roughness length (zoq)
103 104 105
                       25. velocity at reference height (uref)
                       26. temperature at reference height (tref)
                       27. specific humidity at reference height (qref)
106
                       28. number of iterations until convergence
107 108 109 110 111 112 113 114 115
                       29. cool-skin temperature depression (dter)
                       30. cool-skin humidity depression (dqer)
                       31. specific humidity of air (qair)
                       32. specific humidity at sea surface (qsea)
                       33. downward longwave radiation (Rl)
                       34. downward shortwave radiation (Rs)
                       35. downward net longwave radiation (Rnl)

    2020 / Author S. Biri
sbiri's avatar
sbiri committed
116 117 118
    """
    logging.basicConfig(filename='flux_calc.log',
                        format='%(asctime)s %(message)s',level=logging.INFO)
119 120
    logging.captureWarnings(True)
    #  check input values and set defaults where appropriate
121 122 123
    lat, P, Rl, Rs, cskin, gust, tol, L = get_init(spd, T, SST, lat, P, Rl, Rs,
                                                   cskin, gust, L, tol, meth,
                                                   qmeth)
124 125 126
    ref_ht, tlapse = 10, 0.0098        # reference height, lapse rate
    h_in = get_heights(hin, len(spd))  # heights of input measurements/fields
    h_out = get_heights(hout, 1)       # desired height of output variables
127
    logging.info('method %s, inputs: lat: %s | P: %s | Rl: %s |'
128
                 ' Rs: %s | gust: %s | cskin: %s | L : %s', meth,
129
                 np.nanmedian(lat), np.nanmedian(P), np.nanmedian(Rl),
130
                 np.nanmedian(Rs), gust, cskin, L)
131
    #  set up/calculate temperatures and specific humidities
132
    th = np.where(T < 200, (np.copy(T)+CtoK) *
sbiri's avatar
sbiri committed
133 134
                  np.power(1000/P,287.1/1004.67),
                  np.copy(T)*np.power(1000/P,287.1/1004.67))  # potential T
135 136 137
    Ta = np.where(T < 200, np.copy(T)+CtoK+tlapse*h_in[1],
                  np.copy(T)+tlapse*h_in[1])  # convert to Kelvin if needed
    sst = np.where(SST < 200, np.copy(SST)+CtoK, np.copy(SST))
138
    qair, qsea = get_hum(hum, T, sst, P, qmeth)
139 140
    logging.info('method %s and q method %s | qsea:%s, qair:%s', meth, qmeth,
                  np.nanmedian(qsea), np.nanmedian(qair))
sbiri's avatar
sbiri committed
141 142
    if (np.all(np.isnan(qsea)) or np.all(np.isnan(qair))):
        print("qsea and qair cannot be nan")
143
    # tlapse = gamma_moist(SST, T, qair/1000) lapse rate can be computed like this
sbiri's avatar
sbiri committed
144 145
    dt = Ta - sst
    dq = qair - qsea
146
    #  first guesses
sbiri's avatar
sbiri committed
147 148 149 150 151 152
    t10n, q10n = np.copy(Ta), np.copy(qair)
    tv10n = t10n*(1 + 0.61*q10n)
    #  Zeng et al. 1998
    tv=th*(1.+0.61*qair)   # virtual potential T
    dtv=dt*(1.+0.61*qair)+0.61*th*dq
    # ------------
153
    rho = P*100/(287.1*tv10n)
154
    lv = (2.501-0.00237*(sst-CtoK))*1e6
sbiri's avatar
sbiri committed
155 156
    cp = 1004.67*(1 + 0.00084*qsea)
    u10n = np.copy(spd)
sbiri's avatar
sbiri committed
157
    monob = -100*np.ones(spd.shape)
sbiri's avatar
sbiri committed
158
    cdn = cdn_calc(u10n, Ta, None, lat, meth)
159 160 161 162 163 164 165
    ctn, ct, cqn, cq = (np.zeros(spd.shape)*np.nan, np.zeros(spd.shape)*np.nan,
                        np.zeros(spd.shape)*np.nan, np.zeros(spd.shape)*np.nan)
    psim, psit, psiq = (np.zeros(spd.shape), np.zeros(spd.shape),
                        np.zeros(spd.shape))
    cd = cd_calc(cdn, h_in[0], ref_ht, psim)
    tsr, tsrv = np.zeros(spd.shape), np.zeros(spd.shape)
    qsr = np.zeros(spd.shape)
sbiri's avatar
sbiri committed
166
    # cskin parameters
167
    tkt = 0.001*np.ones(T.shape)
sbiri's avatar
sbiri committed
168
    Rnl = 0.97*(5.67e-8*np.power(sst-0.3*cskin+CtoK, 4)-Rl)
sbiri's avatar
sbiri committed
169
    dter = np.ones(T.shape)*0.3
170
    dqer = dter*0.622*lv*qsea/(287.1*np.power(sst, 2))
171
    # gustiness adjustment
172
    if (gust[0] == 1 and meth == "UA"):
173 174
        wind = np.where(dtv >= 0, np.where(spd > 0.1, spd, 0.1),
                        np.sqrt(np.power(np.copy(spd), 2)+np.power(0.5, 2)))
175
    elif (gust[0] == 1):
176
        wind = np.sqrt(np.power(np.copy(spd), 2)+np.power(0.5, 2))
177
    elif (gust[0] == 0):
178
        wind = np.copy(spd)
179
    # stars and roughness lengths
180 181 182 183
    usr = np.sqrt(cd*np.power(wind, 2))
    zo = 0.0001*np.ones(spd.shape)
    zot, zoq = 0.0001*np.ones(spd.shape), 0.0001*np.ones(spd.shape)
    monob = -100*np.ones(spd.shape)  # Monin-Obukhov length
sbiri's avatar
sbiri committed
184
    tsr = (dt+dter*cskin)*kappa/(np.log(h_in[1]/zot) -
185
                                 psit_calc(h_in[1]/monob, meth))
sbiri's avatar
sbiri committed
186
    qsr = (dq+dqer*cskin)*kappa/(np.log(h_in[2]/zoq) -
187
                                 psit_calc(h_in[2]/monob, meth))
188
    # set-up to feed into iteration loop
189 190
    it, ind = 0, np.where(spd > 0)
    ii, itera = True, np.zeros(spd.shape)*np.nan
191 192 193
    tau = 0.05*np.ones(spd.shape)
    sensible = 5*np.ones(spd.shape)
    latent = 65*np.ones(spd.shape)
194
    #  iteration loop
sbiri's avatar
sbiri committed
195 196 197 198
    while np.any(ii):
        it += 1
        if it > n:
            break
199 200 201 202 203 204 205
        if (tol[0] == 'flux'):
            old = np.array([np.copy(tau), np.copy(sensible), np.copy(latent)])
        elif (tol[0] == 'ref'):
            old = np.array([np.copy(u10n), np.copy(t10n), np.copy(q10n)])
        elif (tol[0] == 'all'):
            old = np.array([np.copy(u10n), np.copy(t10n), np.copy(q10n),
                            np.copy(tau), np.copy(sensible), np.copy(latent)])
sbiri's avatar
sbiri committed
206 207
        cdn[ind] = cdn_calc(u10n[ind], Ta[ind], None, lat[ind], meth)
        if (np.all(np.isnan(cdn))):
208
            break
sbiri's avatar
sbiri committed
209 210
            logging.info('break %s at iteration %s cdn<0', meth, it)
        zo[ind] = ref_ht/np.exp(kappa/np.sqrt(cdn[ind]))
211 212 213
        psim[ind] = psim_calc(h_in[0, ind]/monob[ind], meth)
        cd[ind] = cd_calc(cdn[ind], h_in[0, ind], ref_ht, psim[ind])
        ctn[ind], cqn[ind] = ctcqn_calc(h_in[1, ind]/monob[ind], cdn[ind],
sbiri's avatar
sbiri committed
214
                                        u10n[ind], zo[ind], Ta[ind], meth)
215 216 217 218
        zot[ind] = ref_ht/(np.exp(np.power(kappa, 2) /
                           (ctn[ind]*np.log(ref_ht/zo[ind]))))
        zoq[ind] = ref_ht/(np.exp(np.power(kappa, 2) /
                           (cqn[ind]*np.log(ref_ht/zo[ind]))))
219 220
        psit[ind] = psit_calc(h_in[1, ind]/monob[ind], meth)
        psiq[ind] = psit_calc(h_in[2, ind]/monob[ind], meth)
sbiri's avatar
sbiri committed
221
        ct[ind], cq[ind] = ctcq_calc(cdn[ind], cd[ind], ctn[ind], cqn[ind],
222 223
                                      h_in[1, ind], h_in[2, ind], ref_ht,
                                      psit[ind], psiq[ind])
sbiri's avatar
sbiri committed
224 225 226 227 228
        usr[ind], tsr[ind], qsr[ind] = get_strs(h_in[:, ind], monob[ind],
                                                wind[ind], zo[ind], zot[ind],
                                                zoq[ind], dt[ind], dq[ind],
                                                dter[ind], dqer[ind], ct[ind],
                                                cq[ind], cskin, meth)
sbiri's avatar
sbiri committed
229
        if (cskin == 1):
230 231 232 233 234 235 236 237 238 239
            dter[ind], dqer[ind], tkt[ind] = get_skin(sst[ind], qsea[ind],
                                                      rho[ind], Rl[ind],
                                                      Rs[ind], Rnl[ind],
                                                      cp[ind], lv[ind],
                                                      np.copy(tkt[ind]),
                                                      usr[ind], tsr[ind],
                                                      qsr[ind], lat[ind])
        else:
           dter[ind] = np.zeros(sst[ind].shape)
           dqer[ind] = np.zeros(sst[ind].shape)
240
           tkt[ind] = 0.001*np.ones(T[ind].shape)
sbiri's avatar
sbiri committed
241 242 243 244 245 246
        logging.info('method %s | dter = %s | dqer = %s | tkt = %s | Rnl = %s '
                     '| usr = %s | tsr = %s | qsr = %s', meth,
                     np.nanmedian(dter), np.nanmedian(dqer),
                     np.nanmedian(tkt), np.nanmedian(Rnl),
                     np.nanmedian(usr), np.nanmedian(tsr),
                     np.nanmedian(qsr))
247
        Rnl[ind] = 0.97*(5.67e-8*np.power(sst[ind]-CtoK -
sbiri's avatar
sbiri committed
248
                          dter[ind]*cskin+CtoK, 4)-Rl[ind])
249 250 251 252
        t10n[ind] = (Ta[ind] -
                     tsr[ind]/kappa*(np.log(h_in[1, ind]/ref_ht)-psit[ind]))
        q10n[ind] = (qair[ind] -
                     qsr[ind]/kappa*(np.log(h_in[2, ind]/ref_ht)-psiq[ind]))
sbiri's avatar
sbiri committed
253
        tv10n[ind] = t10n[ind]*(1+0.61*q10n[ind])
254 255 256 257
        tsrv[ind], monob[ind] = get_L(L, lat[ind], usr[ind], tsr[ind],
                                      qsr[ind], t10n[ind], tv10n[ind],
                                      qair[ind], h_in[:, ind], T[ind], Ta[ind],
                                      th[ind], tv[ind], sst[ind], dt[ind],
sbiri's avatar
sbiri committed
258 259
                                      dtv[ind], dq[ind], zo[ind], wind[ind],
                                      np.copy(monob[ind]), meth)
260 261 262
        psim[ind] = psim_calc(h_in[0, ind]/monob[ind], meth)
        psit[ind] = psit_calc(h_in[1, ind]/monob[ind], meth)
        psiq[ind] = psit_calc(h_in[2, ind]/monob[ind], meth)
263
        if (gust[0] == 1 and meth == "UA"):
sbiri's avatar
sbiri committed
264
            wind[ind] = np.where(dtv[ind] >= 0, np.where(spd[ind] > 0.1,
265 266 267 268 269 270 271
                                  spd[ind], 0.1),
                                  np.sqrt(np.power(np.copy(spd[ind]), 2) +
                                  np.power(get_gust(gust[1], tv[ind], usr[ind],
                                  tsrv[ind], gust[2], lat[ind]), 2)))
                                  # Zeng et al. 1998 (20)
        elif (gust[0] == 1 and (meth == "C30" or meth == "C35" or
                                meth == "C40")):
sbiri's avatar
sbiri committed
272
            wind[ind] = np.sqrt(np.power(np.copy(spd[ind]), 2) +
273 274 275
                                np.power(get_gust(gust[1], Ta[ind], usr[ind],
                                tsrv[ind], gust[2], lat[ind]), 2))
        elif (gust[0] == 1):
276
            wind[ind] = np.sqrt(np.power(np.copy(spd[ind]), 2) +
277 278 279
                                np.power(get_gust(gust[1], Ta[ind], usr[ind],
                                tsrv[ind], gust[2], lat[ind]), 2))
        elif (gust[0] == 0):
280
            wind[ind] = np.copy(spd[ind])
281 282
        u10n[ind] = wind[ind]-usr[ind]/kappa*(np.log(h_in[0, ind]/10) -
                                              psim[ind])
sbiri's avatar
sbiri committed
283
        u10n = np.where(u10n < 0, np.nan, u10n)
sbiri's avatar
sbiri committed
284
        itera[ind] = np.ones(1)*it
285 286 287 288 289 290 291 292 293 294 295 296 297
        sensible = -rho*cp*usr*tsr
        latent = -rho*lv*usr*qsr
        if (gust[0] == 1):
            tau = rho*np.power(usr, 2)*(spd/wind)
        elif (gust[0] == 0):
            tau = rho*np.power(usr, 2)
        if (tol[0] == 'flux'):
            new = np.array([np.copy(tau), np.copy(sensible), np.copy(latent)])
        elif (tol[0] == 'ref'):
            new = np.array([np.copy(u10n), np.copy(t10n), np.copy(q10n)])
        elif (tol[0] == 'all'):
            new = np.array([np.copy(u10n), np.copy(t10n), np.copy(q10n),
                            np.copy(tau), np.copy(sensible), np.copy(latent)])
298
        d = np.abs(new-old)
299 300
        if (tol[0] == 'flux'):
            ind = np.where((d[0, :] > tol[1])+(d[1, :] > tol[2]) +
301
                            (d[2, :] > tol[3]))
302 303
        elif (tol[0] == 'ref'):
            ind = np.where((d[0, :] > tol[1])+(d[1, :] > tol[2]) +
304
                            (d[2, :] > tol[3]))
305 306
        elif (tol[0] == 'all'):
            ind = np.where((d[0, :] > tol[1])+(d[1, :] > tol[2]) +
307 308
                            (d[2, :] > tol[3])+(d[3, :] > tol[4]) +
                            (d[4, :] > tol[5])+(d[5, :] > tol[6]))
309 310
        if (ind[0].size == 0):
            ii = False
sbiri's avatar
sbiri committed
311
        else:
312
            ii = True
313
    itera[ind] = -1
314
    # itera = np.where(itera > n, -1, itera)
315
    logging.info('method %s | # of iterations:%s', meth, it)
sbiri's avatar
sbiri committed
316
    logging.info('method %s | # of points that did not converge :%s', meth,
317
                  ind[0].size)
sbiri's avatar
sbiri committed
318
    # calculate output parameters
319
    rho = (0.34838*P)/(tv10n)
sbiri's avatar
sbiri committed
320
    t10n = t10n-(273.16+tlapse*ref_ht)
321 322 323
    zo = ref_ht/np.exp(kappa/cdn**0.5)
    zot = ref_ht/(np.exp(kappa**2/(ctn*np.log(ref_ht/zo))))
    zoq = ref_ht/(np.exp(kappa**2/(cqn*np.log(ref_ht/zo))))
324 325 326 327 328 329 330
    uref = (spd-usr/kappa*(np.log(h_in[0]/h_out[0])-psim +
            psim_calc(h_out[0]/monob, meth)))
    tref = (Ta-tsr/kappa*(np.log(h_in[1]/h_out[1])-psit +
            psit_calc(h_out[0]/monob, meth)))
    tref = tref-(273.16+tlapse*h_out[1])
    qref = (qair-qsr/kappa*(np.log(h_in[2]/h_out[2]) -
            psit+psit_calc(h_out[2]/monob, meth)))
331
    res = np.zeros((35, len(spd)))
sbiri's avatar
sbiri committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    res[0][:] = tau
    res[1][:] = sensible
    res[2][:] = latent
    res[3][:] = monob
    res[4][:] = cd
    res[5][:] = cdn
    res[6][:] = ct
    res[7][:] = ctn
    res[8][:] = cq
    res[9][:] = cqn
    res[10][:] = tsrv
    res[11][:] = tsr
    res[12][:] = qsr
    res[13][:] = usr
    res[14][:] = psim
    res[15][:] = psit
348 349 350 351 352 353 354 355
    res[16][:] = psiq
    res[17][:] = u10n
    res[18][:] = t10n
    res[19][:] = tv10n
    res[20][:] = q10n
    res[21][:] = zo
    res[22][:] = zot
    res[23][:] = zoq
356 357 358
    res[24][:] = uref
    res[25][:] = tref
    res[26][:] = qref
359
    res[27][:] = itera
360 361 362 363 364 365 366 367
    res[28][:] = dter
    res[29][:] = dqer
    res[30][:] = qair
    res[31][:] = qsea
    res[32][:] = Rl
    res[33][:] = Rs
    res[34][:] = Rnl

368 369 370 371 372
    if (out == 0):
        res[:, ind] = np.nan
    # set missing values where data have non acceptable values
    res = np.where(spd < 0, np.nan, res)

373
    return res