read.py 3 KB
Newer Older
1
import pandas as pd
Antoine Berchet's avatar
Antoine Berchet committed
2
3
import pycif.utils.check as check
from pycif.utils import path
4
5
6
7
8
import xarray as xr
import datetime
import numpy as np


Espen Sollum's avatar
Espen Sollum committed
9
def read_fluxes(self, name, tracdir, tracfic, dates,
10
                interpol_flx=False, **kwargs):
Antoine Berchet's avatar
Antoine Berchet committed
11
    """Get fluxes from pre-computed fluxes and load them into a pycif
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
    variables

    Args:
        self: the model Plugin
        name: the name of the component
        tracdir, tracfic: flux directory and file format
        dates: list of dates to extract
        interpol_flx (bool): if True, interpolates fluxes at time t from
        values of surrounding available files

    """
    
    list_fic_flx = [dd.strftime(tracfic)
                    for dd in dates]
    
    # Reading fluxes for periods within the simulation window
    trcr_flx = []
    for dd, fic_flx in zip(dates, list_fic_flx):
        nc = xr.open_dataset(
            '{}/{}'.format(tracdir, fic_flx),
            decode_times=False)
        
        nlon = self.domain.nlon
        nlat = self.domain.nlat
        
        # Vector to map
        # Deals with polar boxes by sub-dividing them zonally
        # Also loops zonally for consistency with other call to gridded values
        flx = nc['flx_{}'.format(name.lower())].values
        flx0 = flx[:, 0]
        flx1 = flx[:, -1]
        
        flx = flx[:, 1:-1].reshape((-1, nlat - 2, nlon - 1))
        
        flx = np.append(flx, flx1[:, np.newaxis, np.newaxis]
                        * np.ones((1, 1, nlon - 1)), axis=1)
        flx = np.append(flx0[:, np.newaxis, np.newaxis]
                        * np.ones((1, 1, nlon - 1)), flx, axis=1)
        flx = np.append(flx, flx[:, :, np.newaxis, 0], axis=2)
        
        # Keeps only values for the corresponding month
        # Assumes monthly resolution
        if nc.dims['time'] == 12:
            month = dd.month
            flx = flx[month - 1]
        else:
            flx = flx[0]
        
        trcr_flx.append(flx)
    
    # Interpolating fluxes temporally between file values
    if interpol_flx:
        weights = []
        weights_inds = []
        for fic, flx, dd in zip(list_fic_flx, trcr_flx, dates):
            inds = [k for k, flxx in enumerate(trcr_flx)
                    if np.all(flx == flxx)]
            w0 = dd - dates[inds[0]]
            w1 = dates[min(inds[-1] + 1, len(dates) - 1)] - dd
            dt = w1 + w0
            w0 = w0.total_seconds() / float(dt.total_seconds())
            w1 = w1.total_seconds() / float(dt.total_seconds())
            weights.append((w0, w1))
            weights_inds.append(
                (inds[0], min(inds[-1] + 1, len(dates) - 1)))
        
        trcr_flx_interp = []
        for k, ((w0, w1), (i0, i1)) \
                in enumerate(zip(weights, weights_inds)):
            trcr_flx_interp.append(
                trcr_flx[i0] * w1 + trcr_flx[i1] * w0)
        trcr_flx = trcr_flx_interp
84

Espen Sollum's avatar
Espen Sollum committed
85
    xmod = xr.DataArray(trcr_flx,
86
                        coords={'time': dates},
Espen Sollum's avatar
Espen Sollum committed
87
                        dims=('time', 'lat', 'lon'))
88
89
    
    return xmod