splitnc 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- splitnc/__init__.py +1 -0
- splitnc/esm1p6.py +158 -0
- splitnc/splitnc.py +580 -0
- splitnc-0.1.dist-info/METADATA +144 -0
- splitnc-0.1.dist-info/RECORD +9 -0
- splitnc-0.1.dist-info/WHEEL +5 -0
- splitnc-0.1.dist-info/entry_points.txt +2 -0
- splitnc-0.1.dist-info/licenses/LICENSE +201 -0
- splitnc-0.1.dist-info/top_level.txt +1 -0
splitnc/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .splitnc import *
|
splitnc/esm1p6.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _build_model():
|
|
6
|
+
# Model is always access-esm1p6
|
|
7
|
+
return "access-esm1p6"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _build_component(ds):
|
|
11
|
+
# Component: either CICE5 or UM7.3
|
|
12
|
+
source = ds.attrs["source"]
|
|
13
|
+
if "Los Alamos Sea Ice Model (CICE) Version 5" in source:
|
|
14
|
+
return "cice5"
|
|
15
|
+
elif "Data from Met Office Unified Model" in source and \
|
|
16
|
+
ds.attrs['um_version'] == "7.3":
|
|
17
|
+
return "um7p3"
|
|
18
|
+
else:
|
|
19
|
+
raise ValueError(f"Unknown source, {source}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _build_dimensions(ds, field_name):
|
|
23
|
+
# Dimensions: Don't count time when seeing if field is 2d or 3d
|
|
24
|
+
ndims = len([d for d in ds[field_name].dims if d!='time'])
|
|
25
|
+
if ndims == 2:
|
|
26
|
+
return "2d"
|
|
27
|
+
elif ndims == 3:
|
|
28
|
+
return "3d"
|
|
29
|
+
else:
|
|
30
|
+
raise ValueError(f"Unexpected number for dimensions, {ndims}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _build_frequency(ds, field_name, input_filepath):
|
|
34
|
+
# Frequency: use fx if no time dim
|
|
35
|
+
if 'time' not in ds[field_name].dims:
|
|
36
|
+
return "fx"
|
|
37
|
+
|
|
38
|
+
# Attempt to parse from expected filenames
|
|
39
|
+
filename = input_filepath.name
|
|
40
|
+
|
|
41
|
+
# Define the expected ice filenames
|
|
42
|
+
# e.g. iceh-2hourly-mean_0272.nc, iceh-1yearly-mean_0272.nc
|
|
43
|
+
ice_regex = r"iceh-(?P<num>\d+)(?P<unit>yearly|monthly|daily|hourly)-"
|
|
44
|
+
ice_unit_mapping = {
|
|
45
|
+
"yearly": "yr",
|
|
46
|
+
"monthly": "mon",
|
|
47
|
+
"daily": "day",
|
|
48
|
+
"hourly": "hr"
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if match:=re.match(ice_regex, filename):
|
|
52
|
+
# Extract the frequency number and units for ice files
|
|
53
|
+
return f"{match['num']}{ice_unit_mapping[match['unit']]}"
|
|
54
|
+
elif "_mon.nc" in filename:
|
|
55
|
+
# Match the monthly pattern for atmosphere files
|
|
56
|
+
return "1mon"
|
|
57
|
+
elif "_dai.nc" in filename:
|
|
58
|
+
# Match the daily pattern for atmosphere files
|
|
59
|
+
return "1day"
|
|
60
|
+
elif match:=re.match(r".+_(\d+hr).nc", filename):
|
|
61
|
+
# Get the frequency from the atmosphere regex match for Xhr
|
|
62
|
+
return match[1]
|
|
63
|
+
elif "aiihca.pc" in filename:
|
|
64
|
+
# Match another pattern for hourly atmosphere files
|
|
65
|
+
return "1hr"
|
|
66
|
+
|
|
67
|
+
# No sub-hourly frequency data expected
|
|
68
|
+
raise ValueError("Unable to deduce frequency from filename")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _build_cell_method(ds, field_name):
|
|
72
|
+
attrs = ds[field_name].attrs
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
if attrs['time_rep'] == "instantaneous":
|
|
76
|
+
# ice files sometimes have time_rep = instantaneous but not
|
|
77
|
+
# cell_methods = time: point
|
|
78
|
+
return ".snap"
|
|
79
|
+
except KeyError:
|
|
80
|
+
# Continue if 'time_rep' not in attrs
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
# Time cell_method: Should be able to deduce from the cell_method
|
|
84
|
+
cell_method_regx = r"time: (\w+)"
|
|
85
|
+
try:
|
|
86
|
+
if m:= re.search(cell_method_regx, attrs["cell_methods"]):
|
|
87
|
+
method = m[1]
|
|
88
|
+
if method == "point":
|
|
89
|
+
method = "snap"
|
|
90
|
+
|
|
91
|
+
# Since this element is optional add the . here
|
|
92
|
+
return "." + method
|
|
93
|
+
except KeyError:
|
|
94
|
+
# Continue if 'cell_methods' not in attrs
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
# If there's time but no time_bnds and no time cell_method then assume snap
|
|
98
|
+
# This case is intended to catch instantaneous atmospheric fields from um2nc
|
|
99
|
+
if "time" in ds and "bounds" not in ds["time"].attrs:
|
|
100
|
+
return ".snap"
|
|
101
|
+
|
|
102
|
+
# Otherwise omit this element from the filename
|
|
103
|
+
return ""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _build_datestamp(ds, field_name, file_freq):
|
|
107
|
+
if 'time' not in ds[field_name].dims:
|
|
108
|
+
# No datetime for fixed files
|
|
109
|
+
return ""
|
|
110
|
+
|
|
111
|
+
# Truncate average time val by output file frequency
|
|
112
|
+
# datetimes do not correctly zero-pad so need to use %4Y
|
|
113
|
+
if re.match(r'\d+(yr|dec)', file_freq):
|
|
114
|
+
fmt = '%4Y'
|
|
115
|
+
elif re.match(r'\d+mon', file_freq):
|
|
116
|
+
fmt = '%4Y-%m'
|
|
117
|
+
elif re.match(r'\d+day', file_freq):
|
|
118
|
+
fmt = '%4Y-%m-%d'
|
|
119
|
+
else:
|
|
120
|
+
fmt = '%4Y-%m-%dT%H:%M:%S'
|
|
121
|
+
|
|
122
|
+
# Get the appropriately truncated datetime for the average time
|
|
123
|
+
try:
|
|
124
|
+
# Try the time bounds
|
|
125
|
+
time_arr = ds[ds['time'].attrs["bounds"]]
|
|
126
|
+
logging.debug("Using time bounds to calculate filename timestamp")
|
|
127
|
+
except KeyError:
|
|
128
|
+
# If there are no time bounds just use time
|
|
129
|
+
logging.debug("Unable to find time bounds, using time to calculate filename timestamp")
|
|
130
|
+
time_arr = ds['time']
|
|
131
|
+
|
|
132
|
+
# Calculate the middle point
|
|
133
|
+
first, last = time_arr.min(), time_arr.max()
|
|
134
|
+
datestamp_dt = (first + (last - first) / 2).dt
|
|
135
|
+
|
|
136
|
+
return "." + datestamp_dt.strftime(fmt).data.flatten()[0]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def build_esm1p6_filename(ds, field_name, input_filepath, esm1p6_filename=False, file_freq="1yr"):
|
|
140
|
+
template = "{model}.{component}.{dimensions}.{field}.{freq}{time_cell_method}{datestamp}.nc"
|
|
141
|
+
|
|
142
|
+
# Model is always access-esm1p6
|
|
143
|
+
try:
|
|
144
|
+
d = {
|
|
145
|
+
"model": _build_model(),
|
|
146
|
+
"component": _build_component(ds),
|
|
147
|
+
"dimensions": _build_dimensions(ds, field_name),
|
|
148
|
+
"field": field_name,
|
|
149
|
+
"freq": _build_frequency(ds, field_name, input_filepath),
|
|
150
|
+
"time_cell_method": _build_cell_method(ds, field_name),
|
|
151
|
+
"datestamp": _build_datestamp(ds, field_name, file_freq),
|
|
152
|
+
}
|
|
153
|
+
except ValueError as e:
|
|
154
|
+
# Reraise the exception with some extra information
|
|
155
|
+
e.args = (*e.args, f"While building output filename for field {field_name} and {input_filepath}")
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
return template.format(**d)
|
splitnc/splitnc.py
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from collections import Counter
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from glob import glob
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from platform import python_version
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import xarray as xr
|
|
12
|
+
|
|
13
|
+
from splitnc.esm1p6 import build_esm1p6_filename
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def determine_field_vars(ds):
|
|
17
|
+
"""
|
|
18
|
+
Attempt to determine which variables in the xarray dataset are fields
|
|
19
|
+
|
|
20
|
+
If a variable is not depended on by any other variables it is likely to be a
|
|
21
|
+
field. E.g.
|
|
22
|
+
F(x, y, z), x, y, z
|
|
23
|
+
F depends on x, y, and z so x, y, and z are not fields
|
|
24
|
+
Nothing depends on F, so F is likely to be a field
|
|
25
|
+
|
|
26
|
+
Need to check dimensions, bounds, and coordinates
|
|
27
|
+
"""
|
|
28
|
+
reference_counts = Counter()
|
|
29
|
+
|
|
30
|
+
for varname in ds.variables:
|
|
31
|
+
# Any dims that are not variables will be ignored
|
|
32
|
+
reference_counts.update(ds[varname].dims)
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
reference_counts.update(ds[varname].encoding["coordinates"].split())
|
|
36
|
+
except KeyError:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
reference_counts.update([ds[varname].attrs["bounds"]])
|
|
41
|
+
except KeyError:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
return sorted(
|
|
45
|
+
[varname for varname in ds.variables if reference_counts[varname] == 0]
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_dependent_vars(ds, varname, curr_vars=None):
|
|
50
|
+
"""
|
|
51
|
+
Get a list of variables that the given variable depends on.
|
|
52
|
+
|
|
53
|
+
Check dimensions, bounds, and coordinates
|
|
54
|
+
|
|
55
|
+
Recurse on each NEW dependent to get other dependents.
|
|
56
|
+
|
|
57
|
+
By only recursing on new dependents infinite recursion in the case of
|
|
58
|
+
circular dependencies is avoided.
|
|
59
|
+
"""
|
|
60
|
+
logging.debug(f"Determining dependent variables for {varname}")
|
|
61
|
+
if curr_vars is None:
|
|
62
|
+
curr_vars = set()
|
|
63
|
+
|
|
64
|
+
# Get any dims that are also variables
|
|
65
|
+
new_vars = {d for d in ds[varname].dims if d in ds.variables}
|
|
66
|
+
|
|
67
|
+
# Get any coords
|
|
68
|
+
if (
|
|
69
|
+
"coordinates" in ds[varname].encoding
|
|
70
|
+
and ds[varname].encoding["coordinates"] is not None
|
|
71
|
+
):
|
|
72
|
+
new_vars.update(ds[varname].encoding["coordinates"].split())
|
|
73
|
+
|
|
74
|
+
# Add bounds if the variable has them
|
|
75
|
+
if "bounds" in ds[varname].attrs:
|
|
76
|
+
bounds = ds[varname].attrs["bounds"]
|
|
77
|
+
new_vars.update([bounds])
|
|
78
|
+
|
|
79
|
+
# Get the set of vars that are actually new (to avoid infinite recursion)
|
|
80
|
+
diff_vars = new_vars.difference(curr_vars)
|
|
81
|
+
|
|
82
|
+
all_vars = curr_vars | new_vars
|
|
83
|
+
|
|
84
|
+
# Recurse on each new var
|
|
85
|
+
additional_vars = set()
|
|
86
|
+
for new_v in diff_vars:
|
|
87
|
+
additional_vars |= get_dependent_vars(ds, new_v, all_vars)
|
|
88
|
+
|
|
89
|
+
return diff_vars | additional_vars
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def get_vars_in_order(ds, varname):
|
|
93
|
+
"""
|
|
94
|
+
Get the variables in order
|
|
95
|
+
|
|
96
|
+
- Start with the field for this dataset,
|
|
97
|
+
- Followed by the dimensions of the field
|
|
98
|
+
- each dim followed by their bounds if they exist
|
|
99
|
+
- Finish with anything remaining in alphabetical order
|
|
100
|
+
"""
|
|
101
|
+
# Order the variables
|
|
102
|
+
vars_to_order = list(ds.variables)
|
|
103
|
+
|
|
104
|
+
# Start with the field
|
|
105
|
+
vars_in_order = [varname]
|
|
106
|
+
vars_to_order.remove(varname)
|
|
107
|
+
|
|
108
|
+
# Then the field's dimension and their bnds in order
|
|
109
|
+
for dim_name in ds[varname].dims:
|
|
110
|
+
if dim_name not in vars_to_order:
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
vars_in_order.append(dim_name)
|
|
114
|
+
vars_to_order.remove(dim_name)
|
|
115
|
+
if "bounds" in ds[dim_name].attrs:
|
|
116
|
+
dim_bnd_name = ds[dim_name].attrs["bounds"]
|
|
117
|
+
if dim_bnd_name in vars_to_order:
|
|
118
|
+
vars_in_order.append(dim_bnd_name)
|
|
119
|
+
vars_to_order.remove(dim_bnd_name)
|
|
120
|
+
|
|
121
|
+
# Then the remaining variables in alphabetical order
|
|
122
|
+
vars_in_order += sorted(vars_to_order)
|
|
123
|
+
|
|
124
|
+
return vars_in_order
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def rename_variable(ds, oldname, newname):
|
|
128
|
+
"""
|
|
129
|
+
Rename a variable, xarray handles most of the rename.
|
|
130
|
+
|
|
131
|
+
If the variable has a bounds variable, also rename the matching portion of
|
|
132
|
+
the bound's name. I.e. latitude -> lat therefore latitude_bnds -> lat_bnds
|
|
133
|
+
"""
|
|
134
|
+
logging.debug(f"Renaming {oldname} to {newname}")
|
|
135
|
+
ds_new = ds.rename({oldname: newname})
|
|
136
|
+
|
|
137
|
+
for v in ds.variables:
|
|
138
|
+
# Update cell_methods
|
|
139
|
+
try:
|
|
140
|
+
old_cell_methods = ds_new[v].attrs['cell_methods']
|
|
141
|
+
if old_cell_methods and oldname in old_cell_methods:
|
|
142
|
+
new_cell_methods = old_cell_methods.replace(oldname, newname)
|
|
143
|
+
logging.debug(f"Renaming {oldname} to {newname} in {v}'s cell_methods - {old_cell_methods} to {new_cell_methods}")
|
|
144
|
+
ds_new[v].attrs['cell_methods'] = new_cell_methods
|
|
145
|
+
except KeyError:
|
|
146
|
+
# Do nothing if there's no cell_methods
|
|
147
|
+
pass
|
|
148
|
+
|
|
149
|
+
# Update coordinates
|
|
150
|
+
try:
|
|
151
|
+
old_coords = ds_new[v].encoding['coordinates']
|
|
152
|
+
if old_coords and oldname in old_coords:
|
|
153
|
+
new_coords = old_coords.replace(oldname, newname)
|
|
154
|
+
logging.debug(f"Renaming {oldname} to {newname} in {v}'s coordinates - {old_coords} to {new_coords}")
|
|
155
|
+
ds_new[v].encoding['coordinates'] = new_coords
|
|
156
|
+
except KeyError:
|
|
157
|
+
# Do nothing if there's no coords
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
# Update bounds
|
|
161
|
+
try:
|
|
162
|
+
old_bnd_name = ds_new[newname].attrs["bounds"]
|
|
163
|
+
new_bnd_name = old_bnd_name.replace(oldname, newname)
|
|
164
|
+
|
|
165
|
+
logging.debug(f"Renaming {old_bnd_name} to {new_bnd_name}")
|
|
166
|
+
ds_new = rename_variable(ds_new, old_bnd_name, new_bnd_name)
|
|
167
|
+
|
|
168
|
+
# Update the attr on the original variable
|
|
169
|
+
logging.debug(f'Updating "bounds" attr on {newname} to {new_bnd_name}')
|
|
170
|
+
ds_new[newname].attrs["bounds"] = new_bnd_name
|
|
171
|
+
except KeyError:
|
|
172
|
+
# This variable doesn't have bounds
|
|
173
|
+
pass
|
|
174
|
+
|
|
175
|
+
return ds_new
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def match_regex_list(regex_list, string_list):
|
|
179
|
+
"""
|
|
180
|
+
Return strings in the given list that match the supplied regex
|
|
181
|
+
"""
|
|
182
|
+
compiled_regex = [re.compile(regex) for regex in regex_list]
|
|
183
|
+
return [s for s in string_list if any(r.fullmatch(s) for r in compiled_regex)]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def build_rename_dict(ds, rename_regex):
|
|
187
|
+
"""
|
|
188
|
+
Use the supplied regex to build a dictionary of {"oldname": "newname"} to
|
|
189
|
+
pass to xarray's rename.
|
|
190
|
+
|
|
191
|
+
"newname" should be supplied as a named capture group in the regex.
|
|
192
|
+
|
|
193
|
+
E.g. to rename "time_0", "time_1" or "height_0" to "time" or "height", one
|
|
194
|
+
could use the regex "(?P<newname>.+)_\\d+".
|
|
195
|
+
"""
|
|
196
|
+
logging.debug("Building rename dict")
|
|
197
|
+
rename_dict = {}
|
|
198
|
+
for coord in ds.coords:
|
|
199
|
+
m = re.fullmatch(rename_regex, str(coord))
|
|
200
|
+
|
|
201
|
+
if m:
|
|
202
|
+
try:
|
|
203
|
+
newname = m["newname"]
|
|
204
|
+
except IndexError as e:
|
|
205
|
+
logging.error(
|
|
206
|
+
f"{coord} matched regex for renaming, {rename_regex}, "
|
|
207
|
+
'but no "newname" capture group found'
|
|
208
|
+
)
|
|
209
|
+
raise e
|
|
210
|
+
|
|
211
|
+
logging.debug(f"{coord} will be renamed to {newname}")
|
|
212
|
+
|
|
213
|
+
rename_dict[coord] = newname
|
|
214
|
+
|
|
215
|
+
return rename_dict
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def build_history():
|
|
219
|
+
time_stamp = datetime.now(timezone.utc).isoformat(timespec='seconds')
|
|
220
|
+
python_exe = f"python{python_version()}"
|
|
221
|
+
|
|
222
|
+
# The list of files given on the commandline is not needed in the history
|
|
223
|
+
args = " ".join(sys.argv)
|
|
224
|
+
|
|
225
|
+
return f"{time_stamp} : splitnc (https://github.com/ACCESS-NRI/esm1.6-scripts) : {python_exe} {args}"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def update_history_attr(ds, new_history):
|
|
229
|
+
if "history" in ds.attrs:
|
|
230
|
+
old_history = ds.attrs["history"] + "\n"
|
|
231
|
+
else:
|
|
232
|
+
old_history = ""
|
|
233
|
+
|
|
234
|
+
ds.attrs["history"] = old_history + new_history
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def fix_cell_methods(ds, varname):
|
|
238
|
+
"""
|
|
239
|
+
Fix missing cell_methods for instantaneous variables from um2nc.
|
|
240
|
+
|
|
241
|
+
If variable has 'time' but no time 'bounds' and there are no other 'time'
|
|
242
|
+
cell_methods then add 'time: point' to the cell_methods.
|
|
243
|
+
"""
|
|
244
|
+
if "time" in ds and "bounds" not in ds["time"].attrs:
|
|
245
|
+
try:
|
|
246
|
+
cell_methods = ds[varname].attrs["cell_methods"]
|
|
247
|
+
except KeyError:
|
|
248
|
+
cell_methods = ""
|
|
249
|
+
|
|
250
|
+
if "time" not in cell_methods:
|
|
251
|
+
new_cell_methods = f"{cell_methods} time: point".strip()
|
|
252
|
+
logging.debug(f"Updating cell_methods for {varname} to {new_cell_methods}")
|
|
253
|
+
ds[varname].attrs["cell_methods"] = new_cell_methods
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def build_filename(ds, field_name, input_filepath, esm1p6_filename=False, file_freq="1yr"):
|
|
257
|
+
"""
|
|
258
|
+
Build the filename used for the output.
|
|
259
|
+
|
|
260
|
+
If esm1p6_filename=False then <field_name>_<orginal_file_name> will be used.
|
|
261
|
+
|
|
262
|
+
Otherwise a filename that follows the ESM1.6 naming scheme will be used:
|
|
263
|
+
{model}.{component}.{dimensions}.{field}.{freq}.{time_cell_method}.{datestamp}.nc
|
|
264
|
+
More info here: https://access-om3-configs.access-hive.org.au/configurations/Ocean_diagnostics/
|
|
265
|
+
Elements of this schema will be deduced from the Dataset, the original filename,
|
|
266
|
+
and the given output file frequency.
|
|
267
|
+
"""
|
|
268
|
+
if esm1p6_filename:
|
|
269
|
+
return build_esm1p6_filename(ds, field_name, input_filepath,
|
|
270
|
+
esm1p6_filename=esm1p6_filename, file_freq=file_freq)
|
|
271
|
+
else:
|
|
272
|
+
return f"{field_name}_{input_filepath.name}"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def process_file(filepath, **kwargs):
|
|
276
|
+
# Define default kwargs and update them with kwargs
|
|
277
|
+
kwargs = {
|
|
278
|
+
"excluded_vars": [],
|
|
279
|
+
"shared_vars": [],
|
|
280
|
+
"field_vars": None,
|
|
281
|
+
"rename_regex": None,
|
|
282
|
+
"update_history": True,
|
|
283
|
+
"fix_cell_methods": False,
|
|
284
|
+
"output_dir": False,
|
|
285
|
+
"use_esm1p6_filenames": False,
|
|
286
|
+
"file_freq": "1yr",
|
|
287
|
+
"overwrite": False,
|
|
288
|
+
} | kwargs
|
|
289
|
+
|
|
290
|
+
logging.debug(f"Processing {filepath}")
|
|
291
|
+
filepath = Path(filepath)
|
|
292
|
+
|
|
293
|
+
# Use cftime to suppress warnings
|
|
294
|
+
decoder = xr.coders.CFDatetimeCoder(time_unit='us')
|
|
295
|
+
with xr.open_dataset(filepath, decode_times=decoder) as ds:
|
|
296
|
+
# Resolve any regex in the excluded_vars list
|
|
297
|
+
if excluded_vars:=kwargs["excluded_vars"]:
|
|
298
|
+
excluded_vars = match_regex_list(excluded_vars, ds.variables)
|
|
299
|
+
logging.debug(f"List of defined excluded variables is: {excluded_vars}")
|
|
300
|
+
|
|
301
|
+
# Resolve any regex in the shared_vars list
|
|
302
|
+
if shared_vars:=kwargs["shared_vars"]:
|
|
303
|
+
shared_vars = match_regex_list(shared_vars, ds.variables)
|
|
304
|
+
|
|
305
|
+
# shared_vars should not be in excluded vars
|
|
306
|
+
shared_vars = [v for v in shared_vars if v not in excluded_vars]
|
|
307
|
+
logging.debug(f"List of defined shared variables is: {shared_vars}")
|
|
308
|
+
|
|
309
|
+
# Determine the field vars
|
|
310
|
+
if field_vars:=kwargs["field_vars"]:
|
|
311
|
+
# There may be regex to process
|
|
312
|
+
field_vars = match_regex_list(field_vars, ds.variables)
|
|
313
|
+
else:
|
|
314
|
+
logging.debug("Automatically determining field variables")
|
|
315
|
+
field_vars = determine_field_vars(ds)
|
|
316
|
+
|
|
317
|
+
# Shared and excluded vars shouldn't be field_vars
|
|
318
|
+
logging.debug("Removing shared variables from list of field variables")
|
|
319
|
+
field_vars = [v for v in field_vars if v not in shared_vars and v not in excluded_vars]
|
|
320
|
+
logging.debug(f"List of field vars is: {field_vars}")
|
|
321
|
+
|
|
322
|
+
# Build the mapping dict for renaming, e.g. {"time_0: "time"}
|
|
323
|
+
if rename_regex:=kwargs["rename_regex"]:
|
|
324
|
+
rename_dict = build_rename_dict(ds, rename_regex)
|
|
325
|
+
else:
|
|
326
|
+
rename_dict = {}
|
|
327
|
+
logging.debug(f"Rename dict is {rename_dict}")
|
|
328
|
+
|
|
329
|
+
for v in field_vars:
|
|
330
|
+
# Get the list of vars to keep for this field
|
|
331
|
+
logging.debug(f"Determining dependent variables for field variable {v}")
|
|
332
|
+
dependent_vars = get_dependent_vars(ds, v)
|
|
333
|
+
full_var_list = [v] + list(dependent_vars) + shared_vars
|
|
334
|
+
|
|
335
|
+
# Drop any vars not in the list
|
|
336
|
+
drop_vars_list = [v for v in ds.variables if v not in full_var_list]
|
|
337
|
+
ds_v = ds.drop_vars(drop_vars_list)
|
|
338
|
+
|
|
339
|
+
# Rename anything in the rename dict
|
|
340
|
+
if rename_dict:
|
|
341
|
+
for old_name, new_name in rename_dict.items():
|
|
342
|
+
if (
|
|
343
|
+
old_name in ds_v.variables
|
|
344
|
+
or old_name in ds_v.dims
|
|
345
|
+
or old_name in ds_v.coords
|
|
346
|
+
):
|
|
347
|
+
ds_v = rename_variable(ds_v, old_name, new_name)
|
|
348
|
+
|
|
349
|
+
# Coordinates shouldn't have _FillValues
|
|
350
|
+
for coord in list(ds_v.coords):
|
|
351
|
+
if coord in ds_v.variables:
|
|
352
|
+
logging.debug(f'Setting "_FillValue" to None for {coord}')
|
|
353
|
+
ds_v[coord].encoding["_FillValue"] = None
|
|
354
|
+
|
|
355
|
+
# Bounds shouldn't have coordinates or _FillValues
|
|
356
|
+
bnds_set = {
|
|
357
|
+
ds_v[bnd_v].attrs["bounds"]
|
|
358
|
+
for bnd_v in ds_v.variables
|
|
359
|
+
if "bounds" in ds_v[bnd_v].attrs
|
|
360
|
+
}
|
|
361
|
+
logging.debug(f"Bounds variables are {bnds_set}")
|
|
362
|
+
for bnd in bnds_set:
|
|
363
|
+
logging.debug(
|
|
364
|
+
f'Setting "coordinates" and "_FillValue" to None for {bnd}'
|
|
365
|
+
)
|
|
366
|
+
ds_v[bnd].encoding["coordinates"] = None
|
|
367
|
+
ds_v[bnd].encoding["_FillValue"] = None
|
|
368
|
+
|
|
369
|
+
# Order the variables
|
|
370
|
+
vars_in_order = get_vars_in_order(ds_v, v)
|
|
371
|
+
logging.debug(f"Ordering variable as {vars_in_order}")
|
|
372
|
+
ds_v = ds_v[vars_in_order]
|
|
373
|
+
|
|
374
|
+
# Update the history attribute
|
|
375
|
+
if kwargs["update_history"]:
|
|
376
|
+
new_history = build_history()
|
|
377
|
+
logging.debug(f"Updating history attribute with: {new_history}")
|
|
378
|
+
update_history_attr(ds_v, new_history)
|
|
379
|
+
|
|
380
|
+
# Fix cell_methods
|
|
381
|
+
if kwargs["fix_cell_methods"]:
|
|
382
|
+
fix_cell_methods(ds_v, v)
|
|
383
|
+
|
|
384
|
+
if output_dir:=kwargs["output_dir"]:
|
|
385
|
+
output_dir = Path(output_dir)
|
|
386
|
+
else:
|
|
387
|
+
output_dir = filepath.parent
|
|
388
|
+
|
|
389
|
+
# Build the output filepath
|
|
390
|
+
filename = build_filename(
|
|
391
|
+
ds=ds_v,
|
|
392
|
+
field_name=v,
|
|
393
|
+
input_filepath=filepath,
|
|
394
|
+
esm1p6_filename=kwargs["use_esm1p6_filenames"],
|
|
395
|
+
file_freq=kwargs["file_freq"],
|
|
396
|
+
)
|
|
397
|
+
output_filepath = output_dir / filename
|
|
398
|
+
logging.debug(f"Output filepath is {output_filepath}")
|
|
399
|
+
|
|
400
|
+
# Write to file
|
|
401
|
+
if not kwargs["overwrite"] and output_filepath.exists():
|
|
402
|
+
logging.error(f"Output file already exists - {output_filepath}")
|
|
403
|
+
logging.error("Use --overwrite to overwrite existing files")
|
|
404
|
+
|
|
405
|
+
raise FileExistsError(f"{output_filepath} already exists")
|
|
406
|
+
|
|
407
|
+
logging.debug("Creating parent directory and writing to output file")
|
|
408
|
+
output_filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
409
|
+
ds_v.to_netcdf(output_filepath)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
#### Main
|
|
413
|
+
def arg_parse(cmdline_args=None):
|
|
414
|
+
# If -c/--command-line-file is being used then all other args are ignored
|
|
415
|
+
# This affects which are "required" (or nargs for filepaths)
|
|
416
|
+
args = sys.argv if cmdline_args is None else cmdline_args
|
|
417
|
+
cmd_file_arg_present = "-c" in args or "--command-line-file" in args
|
|
418
|
+
|
|
419
|
+
parser = argparse.ArgumentParser(
|
|
420
|
+
prog="splitnc",
|
|
421
|
+
description="Splits a multi-field netCDF file into separate one-field files",
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
# Create a custom type for comma separated strings as lists
|
|
425
|
+
def comma_separated_string_type(s):
|
|
426
|
+
return s.split(",")
|
|
427
|
+
|
|
428
|
+
# Open the named file and parse it as a command line split it around the
|
|
429
|
+
# whitespaces (including newlines)
|
|
430
|
+
def command_line_file(filepath):
|
|
431
|
+
with open(filepath, "r") as f:
|
|
432
|
+
file_str = f.read()
|
|
433
|
+
|
|
434
|
+
return file_str.split()
|
|
435
|
+
|
|
436
|
+
# Filepath wildcards won't be expanded if supplied via a command line file
|
|
437
|
+
# I.e. *.nc won't be expanded by the shell to [file1.nc, file2.nc]
|
|
438
|
+
def globbable_string_list(string_list):
|
|
439
|
+
return glob(string_list)
|
|
440
|
+
|
|
441
|
+
# Let filepaths be optional (i.e. nargs=* instead of +) so that it isn't
|
|
442
|
+
# required and --cmd-line-file can be used on it's own
|
|
443
|
+
parser.add_argument(
|
|
444
|
+
"filepaths",
|
|
445
|
+
nargs="*" if cmd_file_arg_present else "+",
|
|
446
|
+
default=[],
|
|
447
|
+
type=globbable_string_list,
|
|
448
|
+
help="One or more filepaths to process",
|
|
449
|
+
)
|
|
450
|
+
parser.add_argument(
|
|
451
|
+
"--field-vars",
|
|
452
|
+
type=comma_separated_string_type,
|
|
453
|
+
default=[],
|
|
454
|
+
metavar="FIELD_VAR1,FIELD_VAR2,...",
|
|
455
|
+
help="Specify the names of the field variables to split into separate "
|
|
456
|
+
"files - dimensions, bounds, and coordinates of these fields will "
|
|
457
|
+
"be included in each file. Disables automatic field variable "
|
|
458
|
+
"identification. Regex patterns can be used here.",
|
|
459
|
+
)
|
|
460
|
+
parser.add_argument(
|
|
461
|
+
"--shared-vars",
|
|
462
|
+
type=comma_separated_string_type,
|
|
463
|
+
default=[],
|
|
464
|
+
metavar="SHARED_VAR1,SHARED_VAR2,...",
|
|
465
|
+
help="Specify the names of variables that should be shared across "
|
|
466
|
+
"files that cannot be automatically identified, as a comma "
|
|
467
|
+
"separated list. Regex patterns can be used here.",
|
|
468
|
+
)
|
|
469
|
+
parser.add_argument(
|
|
470
|
+
"--excluded-vars",
|
|
471
|
+
type=comma_separated_string_type,
|
|
472
|
+
default=[],
|
|
473
|
+
metavar="EXCLUDED_VAR1,EXCLUDED_VAR2,...",
|
|
474
|
+
help="Specify the names of variables that should be excluded from "
|
|
475
|
+
"files. This option can be used with automatic identification of field "
|
|
476
|
+
"variables. Regex patterns can be used here.",
|
|
477
|
+
)
|
|
478
|
+
parser.add_argument(
|
|
479
|
+
"--rename-regex",
|
|
480
|
+
metavar="REGEX",
|
|
481
|
+
help="Look for duplicated coordinate names that match the given regex "
|
|
482
|
+
'and rename them to the first "newname" capture group in the '
|
|
483
|
+
'regex. E.g. "(?P<newname>.*)_\\d+" will match "time_0" and '
|
|
484
|
+
'rename it to "time".',
|
|
485
|
+
)
|
|
486
|
+
parser.add_argument(
|
|
487
|
+
"--use-esm1p6-filenames",
|
|
488
|
+
action="store_true",
|
|
489
|
+
help="Use the ESM1.6 filename pattern for the output files: "
|
|
490
|
+
"access-esm1p6.{component}.{dimensions}.{field}.{freq}.{time_cell_method}.{datestamp}.nc"
|
|
491
|
+
" splitnc will attempt to deduce all the components of the filename. "
|
|
492
|
+
"If this option is not given {field}_{original_filename} will be used."
|
|
493
|
+
)
|
|
494
|
+
parser.add_argument(
|
|
495
|
+
"--fix-cell-methods",
|
|
496
|
+
action="store_true",
|
|
497
|
+
help="Correct cell_methods by adding 'time: point' to cell_methods "
|
|
498
|
+
"for variables that have 'time' but not 'time_bnds' and no other "
|
|
499
|
+
"'time' cell_methods."
|
|
500
|
+
)
|
|
501
|
+
parser.add_argument(
|
|
502
|
+
"--file-freq",
|
|
503
|
+
default="1yr",
|
|
504
|
+
help="Specify the frequency of the files (not the data), e.g. if each "
|
|
505
|
+
"file contains a month of data then the file-frequency is '1mon'. Used "
|
|
506
|
+
"to determine the resolution of the timestamp for ESM1.6 filenames. "
|
|
507
|
+
"Follows the ACCESS frequency vocabulary (e.g. '1yr', '1mon', '1day', "
|
|
508
|
+
"'1hr'), any unrecognised frequency will use the full timestamp. "
|
|
509
|
+
"Defaults to '1yr'."
|
|
510
|
+
)
|
|
511
|
+
parser.add_argument(
|
|
512
|
+
"--output-dir",
|
|
513
|
+
help="Output directory for the processed files. If not given output "
|
|
514
|
+
"files will be placed in the same directory as the original file.",
|
|
515
|
+
)
|
|
516
|
+
parser.add_argument(
|
|
517
|
+
"--overwrite", action="store_true", help="Overwrite existing files"
|
|
518
|
+
)
|
|
519
|
+
# By default update the history attr
|
|
520
|
+
# To avoid passing around a negative store_false and rename this arg
|
|
521
|
+
parser.add_argument(
|
|
522
|
+
"--dont-update-history",
|
|
523
|
+
action="store_false",
|
|
524
|
+
dest="update_history",
|
|
525
|
+
help="Disable automatic update of history attribute"
|
|
526
|
+
)
|
|
527
|
+
parser.add_argument(
|
|
528
|
+
"-v",
|
|
529
|
+
"--verbose",
|
|
530
|
+
action="store_true",
|
|
531
|
+
)
|
|
532
|
+
parser.add_argument(
|
|
533
|
+
"-c",
|
|
534
|
+
"--command-line-file",
|
|
535
|
+
type=command_line_file,
|
|
536
|
+
help="A file containing a list of command-line arguments. Newlines in "
|
|
537
|
+
"this file will be ignored. If supplied all other command line "
|
|
538
|
+
"arguments will be ignored.",
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
args = parser.parse_args(args=cmdline_args)
|
|
542
|
+
|
|
543
|
+
# File paths may need flattened since glob was used
|
|
544
|
+
args.filepaths = [
|
|
545
|
+
filepath for glob_list in args.filepaths for filepath in glob_list
|
|
546
|
+
]
|
|
547
|
+
|
|
548
|
+
# If the command line yaml was supplied use the contents instead of argv
|
|
549
|
+
if args.command_line_file:
|
|
550
|
+
return arg_parse(args.command_line_file)
|
|
551
|
+
else:
|
|
552
|
+
return args
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def setup_logging(verbose=False):
|
|
556
|
+
logging.basicConfig(
|
|
557
|
+
level=logging.DEBUG if verbose else logging.WARNING,
|
|
558
|
+
format="{asctime} - {levelname} - {message}",
|
|
559
|
+
style="{",
|
|
560
|
+
datefmt="%Y-%m-%d %H:%M",
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def main():
|
|
565
|
+
args = arg_parse()
|
|
566
|
+
|
|
567
|
+
setup_logging(args.verbose)
|
|
568
|
+
|
|
569
|
+
logging.debug(f"Command line args are: {args}")
|
|
570
|
+
|
|
571
|
+
if len(args.filepaths) == 0:
|
|
572
|
+
logging.error("No files to process.")
|
|
573
|
+
raise ValueError("No files to process.")
|
|
574
|
+
|
|
575
|
+
for f in args.filepaths:
|
|
576
|
+
process_file(f, **vars(args))
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
if __name__ == "__main__":
|
|
580
|
+
main()
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: splitnc
|
|
3
|
+
Version: 0.1
|
|
4
|
+
Summary: Split multi-field ESM1.6 files into single-field files
|
|
5
|
+
Author-email: Joshua Torrance <joshua.torrance@anu.edu.au>, Spencer Wong <spencer.wong@anu.edu.au>
|
|
6
|
+
Maintainer-email: Joshua Torrance <joshua.torrance@anu.edu.au>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Repository, https://github.com/ACCESS-NRI/splitnc
|
|
9
|
+
Keywords: ACCESS-NRI,netcdf
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: netcdf4
|
|
14
|
+
Requires-Dist: xarray
|
|
15
|
+
Provides-Extra: test
|
|
16
|
+
Requires-Dist: pytest; extra == "test"
|
|
17
|
+
Requires-Dist: netCDF4; extra == "test"
|
|
18
|
+
Requires-Dist: xarray>2025.1.2; extra == "test"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# splitnc
|
|
22
|
+
This script splits multi-field netCDF files into single-field files.
|
|
23
|
+
It is designed to work on ESM1.6's atmosphere and ice files.
|
|
24
|
+
|
|
25
|
+
## Automatic Field Identification
|
|
26
|
+
By default `splitnc` will attempt to identify the fields for a multi-field netCDF files by looking for variables that no other variables depend on.
|
|
27
|
+
A variable that no others depend on is likely to be a field.
|
|
28
|
+
E.g. many variables depend on `time`, but none depend on `sea_surface_temperature`.
|
|
29
|
+
|
|
30
|
+
Alternatively the fields to separate to individual files can be specified as a comma separated list with the `--field-vars` command line option.
|
|
31
|
+
`--field-vars` interprets each item as regex, e.g. one could use `--field-vars fld_.+` to match all variable names that start with the string `fld_`.
|
|
32
|
+
|
|
33
|
+
## "Ancillary" Variables
|
|
34
|
+
|
|
35
|
+
Some variables with no dependents should not be separated into individual files, these variables must be manually identified with the `--shared-vars` command line option.
|
|
36
|
+
These variables will then be present in every output file.
|
|
37
|
+
Regex is also supported for this option.
|
|
38
|
+
|
|
39
|
+
If there are ancillary fields that should only be present in only some of the output field files then multiple invocations of `splitnc` using `--field-vars` and `--shared-vars` will be required.
|
|
40
|
+
|
|
41
|
+
Example of these variables are the `latitude_longitude` found in atmosphere files or the `uarea`, `tmask`, `tarea`, `VGRDb`, `VGRDi`, `VGRDs` variables from ice files.
|
|
42
|
+
|
|
43
|
+
## Config File
|
|
44
|
+
|
|
45
|
+
The `-c`/`--command-line-file` option can be used to supply a filepath to a file that contains command line options.
|
|
46
|
+
If this option is used, all other options supplied on the command line will be ignored.
|
|
47
|
+
Newline characters in the file will be treated as whitespace, i.e. newlines can be used as well as spaces to separate command line arguments.
|
|
48
|
+
|
|
49
|
+
For example to replicate this command line,
|
|
50
|
+
```
|
|
51
|
+
splitnc --verbose --overwrite --output-dir /output/directory --shared-vars latitude_longitude --rename-regex "(?P<newname>.+)_\d+" /input/directory/*.nc
|
|
52
|
+
```
|
|
53
|
+
the following file could be used;
|
|
54
|
+
```
|
|
55
|
+
--verbose
|
|
56
|
+
--overwrite
|
|
57
|
+
--output-dir /output/directory
|
|
58
|
+
--shared-vars latitude_longitude
|
|
59
|
+
--rename-regex "(?P<newname>.+)_\d+"
|
|
60
|
+
/input/directory/*.nc
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Command Line Options
|
|
64
|
+
|
|
65
|
+
```quote
|
|
66
|
+
usage: splitnc [-h] [--field-vars FIELD_VAR1,FIELD_VAR2,...] [--shared-vars SHARED_VAR1,SHARED_VAR2,...]
|
|
67
|
+
[--output-name-pattern OUTPUT_NAME_PATTERN] [--rename-regex REGEX] [--output-dir OUTPUT_DIR] [--overwrite] [-v]
|
|
68
|
+
[-c COMMAND_LINE_FILE]
|
|
69
|
+
[filepaths ...]
|
|
70
|
+
|
|
71
|
+
Splits a multi-field netCDF file into separate one-field files
|
|
72
|
+
|
|
73
|
+
positional arguments:
|
|
74
|
+
filepaths One or more filepaths to process
|
|
75
|
+
|
|
76
|
+
options:
|
|
77
|
+
-h, --help show this help message and exit
|
|
78
|
+
--field-vars FIELD_VAR1,FIELD_VAR2,...
|
|
79
|
+
Specify the names of the field variables to split into separate files - dimensions, bounds, and
|
|
80
|
+
coordinates of these fields will be included in each file. Disables automatic field variable
|
|
81
|
+
identification. Regex patterns can be used here.
|
|
82
|
+
--shared-vars SHARED_VAR1,SHARED_VAR2,...
|
|
83
|
+
Specify the names of variables that should be shared across files that cannot be automatically
|
|
84
|
+
identified, as a comma separated list. Regex patterns can be used here.
|
|
85
|
+
--excluded-vars EXCLUDED_VAR1,EXCLUDED_VAR2,...
|
|
86
|
+
Specify the names of variables that should be excluded from files. This option can be used with
|
|
87
|
+
automatic identification of field variables. Regex patterns can be used here.
|
|
88
|
+
--rename-regex REGEX Look for duplicated coordinate names that match the given regex and rename them to the first
|
|
89
|
+
"newname" capture group in the regex. E.g. "(?P<newname>.*)_\d+" will match "time_0" and rename
|
|
90
|
+
it to "time".
|
|
91
|
+
--use-esm1p6-filenames
|
|
92
|
+
Use the ESM1.6 filename pattern for the output files:
|
|
93
|
+
access-esm1p6.{component}.{dimensions}.{field}.{freq}.{time_cell_method}.{datestamp}.nc
|
|
94
|
+
splitnc will attempt to deduce all the components of the filename. If this option is not given
|
|
95
|
+
{field}_{original_filename} will be used.
|
|
96
|
+
--fix-cell-methods Correct cell_methods by adding 'time: point' to cell_methods for variables that have 'time' but
|
|
97
|
+
not 'time_bnds' and no other 'time' cell_methods.
|
|
98
|
+
--file-freq FILE_FREQ
|
|
99
|
+
Specify the frequency of the files (not the data), e.g. if each file contains a month of data
|
|
100
|
+
then the file-frequency is '1mon'. Used to determine the resolution of the timestamp for ESM1.6
|
|
101
|
+
filenames. Follows the ACCESS frequency vocabulary (e.g. '1yr', '1mon', '1day', '1hr'), any
|
|
102
|
+
unrecognised frequency will use the full timestamp. Defaults to '1yr'.
|
|
103
|
+
--output-dir OUTPUT_DIR
|
|
104
|
+
Output directory for the processed files. If not given output files will be placed in the same
|
|
105
|
+
directory as the original file.
|
|
106
|
+
--overwrite Overwrite existing files
|
|
107
|
+
--dont-update-history
|
|
108
|
+
Disable automatic update of history attribute
|
|
109
|
+
-v, --verbose
|
|
110
|
+
-c COMMAND_LINE_FILE, --command-line-file COMMAND_LINE_FILE
|
|
111
|
+
A file containing a list of command-line arguments. Newlines in this file will be ignored. If
|
|
112
|
+
supplied all other command line arguments will be ignored.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Example Usage
|
|
116
|
+
|
|
117
|
+
`splitnc` just needs the `xarray` and `netCDF4` python modules.
|
|
118
|
+
On Gadi use load any module with `xarray`, such as `conda/analysis3`.
|
|
119
|
+
Alternatively create a new python environment and install `xarray` and `netCDF4`.
|
|
120
|
+
|
|
121
|
+
### Atmosphere
|
|
122
|
+
To use this script for split multi-field atmosphere files from ACCESS-ESM1.6:
|
|
123
|
+
```bash
|
|
124
|
+
splitnc --shared-vars latitude_longitude --rename-regex "(?P<newname>.+)_\\d+" $INPUT_DIR/*.nc
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`splitnc` will automatically determine which variables are fields by looking at which variables depend on other variables.
|
|
128
|
+
Variables with nothing depending on them are deemed to be fields.
|
|
129
|
+
Alternatively one could use `--field-vars fld_.+` to match the variable names in these files.
|
|
130
|
+
|
|
131
|
+
The `--rename-regex` option with the supplied regex will rename variables like
|
|
132
|
+
`time_0` or `pseudo_level_0` are renamed to `time` or `pseudo_level`.
|
|
133
|
+
|
|
134
|
+
The `--shared-vars` option will ensure that the variable `latitude_longitude` is
|
|
135
|
+
included in all files even though none of the field variable depend on it.
|
|
136
|
+
|
|
137
|
+
### Ice
|
|
138
|
+
To use this script for split multi-field ice files from ACCESS-ESM1.6:
|
|
139
|
+
```bash
|
|
140
|
+
splitnc --shared-vars uarea,tmask,tarea --excluded-vars VGRD. $INPUT_DIR/*.nc
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
In comparison to the atmosphere files, ice files have different shared-vars and there are no duplicated variables that require renaming.
|
|
144
|
+
The variables `VGRDb`, `VGRDi`, and `VGRDs` are not required and can thus be excluded from the output.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
splitnc/__init__.py,sha256=YoWizDzFzj52Hb_0Lb8qzhWUL-HxOGv1exV-v1dSEW8,23
|
|
2
|
+
splitnc/esm1p6.py,sha256=WsOcUoLFuQmS2Z5QM663JmdnjEb6cEnk6IaFT6YPaM4,5285
|
|
3
|
+
splitnc/splitnc.py,sha256=Uckg9i0ATtRJ87k-7VlXwa7i_jjXPKPbz2PtBSKWNTg,20822
|
|
4
|
+
splitnc-0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
5
|
+
splitnc-0.1.dist-info/METADATA,sha256=y-Al-AXZMNlb8NJkw1Baxwi4QQ6KB-Gp4chrg4JCi8o,7718
|
|
6
|
+
splitnc-0.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
7
|
+
splitnc-0.1.dist-info/entry_points.txt,sha256=QbOAcAYWj8A_WygPT88igXxc-ke9hypfaqn2ZvFATvA,41
|
|
8
|
+
splitnc-0.1.dist-info/top_level.txt,sha256=lif5g27mG8Nw83f9OBwNwlfacXkin5Ud8xJPCYrXmlA,8
|
|
9
|
+
splitnc-0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
splitnc
|