File: test_python_CMIP6_CV_externalvariables.py

package info (click to toggle)
cmor 3.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 16,960 kB
  • sloc: ansic: 28,094; f90: 13,872; python: 12,423; sh: 3,738; makefile: 111
file content (234 lines) | stat: -rw-r--r-- 9,414 bytes parent folder | download | duplicates (2)
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
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
137
138
139
140
141
142
143
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
190
191
192
193
194
195
196
197
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
# If this example is not executed from the directory containing the
# CMOR code, please first complete the following steps:
#
#   1. In any directory, create 'Tables/', 'Test/' and 'CMIP6/' directories.
#
#   2. Download
#      https://github.com/PCMDI/cmor/blob/master/TestTables/CMIP6_Omon.json
#      and https://github.com/PCMDI/cmor/blob/master/TestTables/CMIP6_CV.json
#      to the 'Tables/' directory.
#
#   3. Download
#      https://github.com/PCMDI/cmor/blob/master/Test/<filename>.json
#      to the 'Test/' directory.
from __future__ import print_function
import cmor
import numpy
import unittest
import os
import sys
import tempfile
import importlib.util
import netCDF4
import base_CMIP6_CV

# ==============================
#  main thread
# ==============================
def run():
    unittest.main()


class TestCase(base_CMIP6_CV.BaseCVsTest):
    def testCMIP6(self):

        nlat = 10
        dlat = 180. / nlat
        nlon = 20
        dlon = 360. / nlon
        nlev = 5
        ntimes = 5

        lats = numpy.arange(90 - dlat / 2., -90, -dlat)
        blats = numpy.arange(90, -90 - dlat, -dlat)
        lons = numpy.arange(0 + dlon / 2., 360., dlon)
        blons = numpy.arange(0, 360. + dlon, dlon)

        # -------------------------------------------
        # Try to call cmor with a bad institution_ID
        # -------------------------------------------
        cmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE, logfile=self.tmpfile)
        cmor.dataset_json("Test/CMOR_input_example.json")

        # --------------------------------------------
        # load Omon table and create masscello variable
        # --------------------------------------------
        cmor.load_table("CMIP6_Omon.json")
        itime = cmor.axis(table_entry="time", units='months since 2010',
                          coord_vals=numpy.array([0, 1, 2, 3, 4.]),
                          cell_bounds=numpy.array([0, 1, 2, 3, 4, 5.]))
        ilat = cmor.axis(
            table_entry='latitude',
            coord_vals=lats,
            cell_bounds=blats,
            units='degrees_north')
        ilon = cmor.axis(
            table_entry='longitude',
            coord_vals=lons,
            cell_bounds=blons,
            units='degrees_east')
        ilev = cmor.axis(table_entry='depth_coord', length=5,
                         cell_bounds=numpy.arange(0, 12000, 2000), coord_vals=numpy.arange(0, 10000, 2000), units="m")

        ivar = cmor.variable(
            table_entry="masscello", axis_ids=[
                itime, ilev, ilat, ilon, ], units='kg/m2')

        data = numpy.random.random((ntimes, nlev, nlat, nlon)) * 100.

        cmor.write(ivar, data)
        self.delete_files += [cmor.close(ivar, True)]
        cmor.close()

        f = netCDF4.Dataset(cmor.get_final_filename(), "r")
        self.assertTrue("external_variables" in f.__dict__)
        a = f.__dict__["external_variables"]
        self.assertEqual("areacello volcello", a)
        f.close()

    @unittest.skipIf(importlib.util.find_spec("cdms2") is None, "cdms2 not installed")
    def testCMIP6_CDMS2(self):
        import cdms2

        nlat = 10
        dlat = 180. / nlat
        nlon = 20
        dlon = 360. / nlon
        nlev = 5
        ntimes = 5

        lats = numpy.arange(90 - dlat / 2., -90, -dlat)
        blats = numpy.arange(90, -90 - dlat, -dlat)
        lons = numpy.arange(0 + dlon / 2., 360., dlon)
        blons = numpy.arange(0, 360. + dlon, dlon)

        # -------------------------------------------
        # Try to call cmor with a bad institution_ID
        # -------------------------------------------
        cmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE, logfile=self.tmpfile)
        cmor.dataset_json("Test/CMOR_input_example.json")

        # --------------------------------------------
        # load Omon table and create masscello variable
        # --------------------------------------------
        cmor.load_table("CMIP6_Omon.json")
        itime = cmor.axis(table_entry="time", units='months since 2010',
                          coord_vals=numpy.array([0, 1, 2, 3, 4.]),
                          cell_bounds=numpy.array([0, 1, 2, 3, 4, 5.]))
        ilat = cmor.axis(
            table_entry='latitude',
            coord_vals=lats,
            cell_bounds=blats,
            units='degrees_north')
        ilon = cmor.axis(
            table_entry='longitude',
            coord_vals=lons,
            cell_bounds=blons,
            units='degrees_east')
        ilev = cmor.axis(table_entry='depth_coord', length=5,
                         cell_bounds=numpy.arange(0, 12000, 2000), coord_vals=numpy.arange(0, 10000, 2000), units="m")

        ivar = cmor.variable(
            table_entry="masscello", axis_ids=[
                itime, ilev, ilat, ilon, ], units='kg/m2')

        data = numpy.random.random((ntimes, nlev, nlat, nlon)) * 100.

        cmor.write(ivar, data)
        self.delete_files += [cmor.close(ivar, True)]
        cmor.close()

        f = cdms2.open(cmor.get_final_filename(), "r")
        a = f.getglobal("external_variables")
        self.assertEqual("areacello volcello", a)
        f.close()

    def testCMIP6_ExternaVariablesError(self):

        print("CMIP6 External Error")
        cmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE, logfile=self.tmpfile)
        error_flag = cmor.dataset_json('Test/CMOR_input_example.json')
        table_id = cmor.load_table('CMIP6_6hrLev.json')
        time = cmor.axis(table_entry='time1', units='days since 2000-01-01',
                        coord_vals=numpy.array(range(1)),
                        cell_bounds=numpy.array(range(2)))
        latitude = cmor.axis(table_entry='latitude', units='degrees_north',
                            coord_vals=numpy.array(range(5)),
                            cell_bounds=numpy.array(range(6)))
        longitude = cmor.axis(table_entry='longitude', units='degrees_east',
                            coord_vals=numpy.array(range(5)),
                            cell_bounds=numpy.array(range(6)))
        plev3 = cmor.axis(table_entry='plev3', units='Pa',
                        coord_vals=numpy.array([85000., 50000., 25000.]))
        axis_ids = [longitude, latitude, plev3, time]
        ua_var_id = cmor.variable(table_entry='ua', axis_ids=axis_ids,
                                units='m s-1')
        ta_var_id = cmor.variable(table_entry='ta', axis_ids=axis_ids,
                                units='K')
        data = numpy.random.random(75)
        reshaped_data = data.reshape((5, 5, 3, 1))

        # This doesn't:
        cmor.write(ta_var_id, reshaped_data)
        cmor.write(ua_var_id, reshaped_data)
        fname_ta = cmor.close(ta_var_id, file_name=True)
        fname_ua = cmor.close(ua_var_id, file_name=True)
        self.delete_files += [fname_ta, fname_ua]
        cmor.close()

        f = netCDF4.Dataset(fname_ta, "r")
        self.assertTrue("external_variables" in f.__dict__)
        a = f.__dict__["external_variables"]
        self.assertEqual("areacella", a)
        f.close()
        f = netCDF4.Dataset(fname_ua, "r")
        self.assertTrue("external_variables" not in f.__dict__)
        f.close()

    @unittest.skipIf(importlib.util.find_spec("cdms2") is None, "cdms2 not installed")
    def testCMIP6_ExternaVariablesError_CDMS2(self):
        import cdms2

        print("CMIP6 External Error")
        cmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE, logfile=self.tmpfile)
        error_flag = cmor.dataset_json('Test/CMOR_input_example.json')
        table_id = cmor.load_table('CMIP6_6hrLev.json')
        time = cmor.axis(table_entry='time1', units='days since 2000-01-01',
                        coord_vals=numpy.array(range(1)),
                        cell_bounds=numpy.array(range(2)))
        latitude = cmor.axis(table_entry='latitude', units='degrees_north',
                            coord_vals=numpy.array(range(5)),
                            cell_bounds=numpy.array(range(6)))
        longitude = cmor.axis(table_entry='longitude', units='degrees_east',
                            coord_vals=numpy.array(range(5)),
                            cell_bounds=numpy.array(range(6)))
        plev3 = cmor.axis(table_entry='plev3', units='Pa',
                        coord_vals=numpy.array([85000., 50000., 25000.]))
        axis_ids = [longitude, latitude, plev3, time]
        ua_var_id = cmor.variable(table_entry='ua', axis_ids=axis_ids,
                                units='m s-1')
        ta_var_id = cmor.variable(table_entry='ta', axis_ids=axis_ids,
                                units='K')
        data = numpy.random.random(75)
        reshaped_data = data.reshape((5, 5, 3, 1))

        # This doesn't:
        cmor.write(ta_var_id, reshaped_data)
        cmor.write(ua_var_id, reshaped_data)
        fname_ta = cmor.close(ta_var_id, file_name=True)
        fname_ua = cmor.close(ua_var_id, file_name=True)
        self.delete_files += [fname_ta, fname_ua]
        cmor.close()

        f = cdms2.open(fname_ta, "r")
        a = f.getglobal("external_variables")
        self.assertEqual("areacella", a)
        f.close()
        f = cdms2.open(fname_ua, "r")
        a = f.getglobal("external_variables")
        self.assertEqual(None, a)
        f.close()


if __name__ == '__main__':
    run()