read.py 2.68 KB
Newer Older
Isabelle Pison's avatar
Isabelle Pison committed
1
2
3
4
5
6
7
8
9
10
11
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
84
85
86
87
88
89
90
91
import datetime
import os

import numpy as np
import xarray as xr
from netCDF4 import Dataset

from pycif.utils.netcdf import readnc


def read(
    self,
    name,
    tracdir,
    tracfile,
    varnames,
    dates,
    comp_type=None,
    **kwargs
):
    """Get BCs from raw files and load them into a pyCIF
    variables

    Args:
        self: the BC Plugin
        name: the name of the component
        tracdir, tracfile: raw data directory and file format
        dates: list of dates to extract
        comp_type: type of boundary conditions to generate

    """
    print('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ')
    if type(tracfile) == str:
         tracfile = [dd.strftime(tracfile) for dd in dates]
    else:
      if len(tracfile) != len(dates) :
        raise Exception(
            "Try read CAMS files from a list of dates and a "
            "list of files, but not of same length:\n{}\n{}".format(
                tracfile, dates
            )
        )
      list_files = tracfile[:]
    
    print('LLLLLLLLLLLLLL',list_files)
    
    # Reading fields for periods within the simulation window
    trcr_conc = []
    times = []
    for dd, dd_file in zip(dates, list_files):
        file_conc = dd.strftime(dd_file)
        dir_conc = dd.strftime(tracdir)

        if not os.path.isfile("{}/{}".format(dir_conc, file_conc)) and getattr(
            self, "closest_year", False
        ):
            info(
                "Warning: could not find correct year for CAMS; "
                "using closest available one"
            )
            list_dates = [
                datetime.datetime.strptime(os.path.basename(f), tracfile)
                for f in glob.glob("{}/z_cams_l_nilu_*nc".format(dir_conc))
            ]
            delta_dates = np.abs(dd - np.array(list_dates))
            file_conc = list_dates[np.argmin(delta_dates)].strftime(tracfile)

        nc = xr.open_dataset(
            "{}/{}".format(dir_conc, file_conc), decode_times=False
        )
        #print('DDDDDDDDDDD',dd,nc['time'])
        # Convert number of hours since first day of the month to datetime
        times.extend(
            [datetime.datetime(dd.year, dd.month, 1) + datetime.timedelta(hours=t)
             for t in nc['time'].values]
        ) 
        #print('TTTTTTTTTT',times)
        trcr_conc.append(nc[varnames]['time' == dates].values)

        
    # Putting in DataArray for the right period = combien d'heures??? Juste dates???
    # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    print('TTTTTTTTT',np.array(trcr_conc).shape)
    print('ddddddddddd',dates,times[0])
    xmod = xr.DataArray(
        np.array(trcr_conc),
        coords={"time": dates},
        dims=("time", "lev", "lat", "lon"),
    )

    return xmod