/
subset.py
71 lines (58 loc) · 2.96 KB
/
subset.py
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
import iris
import datetime
from dateutil.relativedelta import relativedelta
iris.FUTURE.netcdf_promote = True
iris.FUTURE.cell_datetime_objects=False
def time_value(date, cube):
"""function that takes a string of date (YYYY-MM-DD) and returns it in correct format, derived from the data"""
try:
time_units = cube.coord('time').units
except:
raise KeyboardInterrupt, 'cube has no coord time'
try:
year, month, day = date.split('-')
year, month, day = int(year), int(month), int(day)
val = time_units.date2num(datetime.datetime(year, month, day))
except:
raise KeyboardInterrupt, 'format of date needs to be: \"YYYY-MM-DD\"'
return val
def subset_nc(filename, startdate, enddate, level=None, level2=None, lat_min=20, lat_max=90, lon_min=180, lon_max=340):
"""A function to subnet the netCDF4 file (.nc) which can be adjusted to extract
only the bits you need when making your dataframe"""
try:
cubes = iris.load(filename)
if len(cubes) == 1:
subset = cubes[0]
else:
subset = cubes[1]
except:
raise KeyboardInterrupt, 'need path to v-wind netcdf4 file'
try:
s_val = time_value(startdate, subset)
except:
raise KeyboardInterrupt, 'startdate needs to be in format: YYYY-MM-DD'
try:
e_val = time_value(enddate, subset)
except:
raise KeyboardInterrupt, 'enddate needs to be in format: YYYY-MM-DD'
try:
if level != None and level2 != None:
subset = subset.extract(
iris.Constraint(latitude=lambda cell: lat_min <= cell <= lat_max,
longitude=lambda cell: lon_min <= cell <= lon_max,
pressure_level=lambda cell: level <= cell <= level2,
time=lambda cell: int(s_val) <= cell <= int(e_val)))
elif level != None and level2 == None:
subset = subset.extract(
iris.Constraint(latitude=lambda cell: lat_min <= cell <= lat_max,
longitude=lambda cell: lon_min <= cell <= lon_max,
pressure_level=lambda cell: level <= cell <= level,
time=lambda cell: int(s_val) <= cell <= int(e_val)))
else:
subset = subset.extract(
iris.Constraint(latitude=lambda cell: lat_min <= cell <= lat_max,
longitude=lambda cell: lon_min <= cell <= lon_max,
time=lambda cell: int(s_val) <= cell <= int(e_val)))
except:
raise KeyboardInterrupt, 'variables out of range of the data\'s dimensions OR try setting iris.FUTURE.cell_datetime_objects to False'
return subset