standardization.py 5.98 KB
Newer Older
BorjaEst's avatar
BorjaEst committed
1
2
3
"""Module in charge of dataset standardization when loading models."""

import logging
4
5
import unittest

BorjaEst's avatar
BorjaEst committed
6
import xarray as xr
7
8
import pandas as pd
import numpy as np
BorjaEst's avatar
BorjaEst committed
9
10
11
12
from o3skim import utils

logger = logging.getLogger('o3skim.standardization')

13
14

@utils.return_on_failure("Error when loading '{0}'".format('tco3_zm'),
15
16
                         default=xr.Dataset())
def standardize_tco3(dataset, variable, coordinates):
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    """Standardizes a tco3 dataset.
    
    :param dataset: Dataset to standardize.
    :type dataset: xarray.Dataset

    :param variable: Variable name for the tco3 on the original dataset.
    :type variable: str

    :param coordinates: Coordinates map for tco3 variable. 
    :type coordinates: {'lon':str, 'lat':str, 'time':str}

    :return: Standardized dataset.
    :rtype: xarray.Dataset 
    """
31
    array = dataset[variable]
32
    array.name = 'tco3_zm'
33
    array = squeeze(array)
34
    array = rename_coords_tco3(array, **coordinates)
35
36
    array = sort(array)
    return array.to_dataset()
37
38


BorjaEst's avatar
BorjaEst committed
39
40
41
42
def rename_coords_tco3(array, time, lat, lon):
    """Renames a tco3 array variable and coordinates"""
    logger.debug("Renaming '{0}' coordinates".format('tco3_zm'))
    return array.rename({time: 'time', lat: 'lat', lon: 'lon'})
43
44
45


@utils.return_on_failure("Error when loading '{0}'".format('vmro3_zm'),
46
                         default=xr.Dataset())
47
def standardize_vmro3(dataset, variable, coordinates):
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    """Standardizes a vmro3 dataset.

    :param dataset: Dataset to standardize.
    :type dataset: xarray.Dataset

    :param variable: Variable name for the vmro3 on the original dataset.
    :type variable: str

    :param coordinates: Coordinates map for vmro3 variable. 
    :type coordinates: {'lon':str, 'lat':str, 'plev':str, 'time':str}

    :return: Standardized dataset.
    :rtype: xarray.Dataset 
    """
62
    array = dataset[variable]
63
    array.name = 'vmro3_zm'
64
    array = squeeze(array)
65
    array = rename_coords_vmro3(array, **coordinates)
66
67
    array = sort(array)
    return array.to_dataset()
68
69


BorjaEst's avatar
BorjaEst committed
70
71
72
73
def rename_coords_vmro3(array, time, plev, lat, lon):
    """Renames a vmro3 array variable and coordinates"""
    logger.debug("Renaming '{0}' coordinates".format('vmro3_zm'))
    return array.rename({time: 'time', plev: 'plev', lat: 'lat', lon: 'lon'})
74
75


76
77
def squeeze(array):
    """Squeezes the 1-size dimensions on an array"""
78
    logger.debug("Squeezing coordinates in dataset")
79
    return array.squeeze(drop=True)
80
81


82
83
def sort(array):
    """Sorts an array by coordinates"""
84
    logger.debug("Sorting coordinates in dataset")
85
    return array.sortby(list(array.coords))
86
87


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class TestsTCO3(unittest.TestCase):

    data_s = np.mgrid[1:3:3j, 1:3:3j, 1:3:3j][0]
    data_r = np.mgrid[3:1:3j, 3:1:3j, 1:1:1j, 3:1:3j][0]
    varname = "tco3"
    coords = {'lon': 'long', 'lat': 'latd', 'time': 'time'}

    @staticmethod
    def non_standard_ds():
        return xr.Dataset(
            data_vars=dict(
                tco3=(["long", "latd", "high", "time"], TestsTCO3.data_r)
            ),
            coords=dict(
                long=[180, 0, -180],
                latd=[90, 0, -90],
                high=[1],
                time=pd.date_range("2000-01-03", periods=3, freq='-1d')
            ),
            attrs=dict(description="Non standardized dataset")
        )

    @staticmethod
    def standard_ds():
        return xr.Dataset(
            data_vars=dict(
                tco3_zm=(["lon", "lat", "time"], TestsTCO3.data_s)
            ),
            coords=dict(
                time=pd.date_range("2000-01-01", periods=3, freq='1d'),
                lat=[-90, 0, 90],
                lon=[-180, 0, 180]
            ),
            attrs=dict(description="Standardized dataset")
        )

    def test_standardize(self):
        standardized_tco3 = standardize_tco3(
            dataset=TestsTCO3.non_standard_ds(),
            variable=TestsTCO3.varname,
            coordinates=TestsTCO3.coords)
        xr.testing.assert_equal(TestsTCO3.standard_ds(), standardized_tco3)

    def test_fail_returns_empty_dataset(self):
        empty_dataset = standardize_tco3(
            dataset=TestsTCO3.non_standard_ds(),
            variable="badVariable",
            coordinates=TestsTCO3.coords)
        xr.testing.assert_equal(xr.Dataset(), empty_dataset)
137
138
139
140
141
142
143
144


class TestsVMRO3(unittest.TestCase):

    data_s = np.mgrid[1:3:3j, 1:3:3j, 1:4:4j, 1:3:3j][0]
    data_r = np.mgrid[3:1:3j, 3:1:3j, 4:1:4j, 3:1:3j][0]
    varname = "vmro3"
    coords = {'lon': 'longit', 'lat': 'latitu',
145
              'plev': 'level', 'time': 't'}
146
147
148
149
150

    @staticmethod
    def non_standard_ds():
        return xr.Dataset(
            data_vars=dict(
151
                vmro3=(["longit", "latitu", "level", "t"], TestsVMRO3.data_r)
152
153
154
155
156
            ),
            coords=dict(
                longit=[180, 0, -180],
                latitu=[90, 0, -90],
                level=[1000, 100, 10, 1],
157
                t=pd.date_range("2000-01-03", periods=3, freq='-1d')
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
            ),
            attrs=dict(description="Non standardized dataset")
        )

    @staticmethod
    def standard_ds():
        return xr.Dataset(
            data_vars=dict(
                vmro3_zm=(["lon", "lat", "plev", "time"], TestsVMRO3.data_s)
            ),
            coords=dict(
                time=pd.date_range("2000-01-01", periods=3, freq='1d'),
                plev=[1, 10, 100, 1000],
                lat=[-90, 0, 90],
                lon=[-180, 0, 180]
            ),
            attrs=dict(description="Standardized dataset")
        )

    def test_standardize(self):
        standardized_vmro3 = standardize_vmro3(
            dataset=TestsVMRO3.non_standard_ds(),
            variable=TestsVMRO3.varname,
            coordinates=TestsVMRO3.coords)
        xr.testing.assert_equal(TestsVMRO3.standard_ds(), standardized_vmro3)
183
184
185
186
187
188
189

    def test_fail_returns_empty_dataset(self):
        empty_dataset = standardize_vmro3(
            dataset=TestsVMRO3.non_standard_ds(),
            variable="badVariable",
            coordinates=TestsVMRO3.coords)
        xr.testing.assert_equal(xr.Dataset(), empty_dataset)