-
Notifications
You must be signed in to change notification settings - Fork 0
ESM1.6 style output filenames #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
joshuatorrance
wants to merge
25
commits into
main
Choose a base branch
from
4-esm1p6-filenames
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
ad727cd
Rough draft and tests for esm1.6 style output filenames
joshuatorrance 2cc52a8
Fixed bug in tests
joshuatorrance fea12ca
Need to add time values to one more cdl file
joshuatorrance 518bfc6
Removed unnecessary double space
joshuatorrance b0216ac
Removed an excess newline
joshuatorrance ebdd284
Moved a TODO
joshuatorrance dc4aa8a
Added a sub-daily datestamp format
joshuatorrance 747c84c
Added cases to the frequency identification, explicit 4 digit years, …
joshuatorrance 0712bd1
Filename timestamp creation now uses time_bnds if possible. open_data…
joshuatorrance 8770185
Updated ToDo for yearly/subhourly files
joshuatorrance 4562ffa
Added command line arg for file-freq. Commented out previously failin…
joshuatorrance e18d769
Tweaked handling of commandline options so that required ones can be …
joshuatorrance ca6b2f6
Ice timestep files now fail to parse since freq is unknown. Updated t…
joshuatorrance c9ef98d
Updated comments to indicate no sub-hourly data expected
joshuatorrance ee4c8e9
Default arguments for esm1p6_filename now match default commandline o…
joshuatorrance ddbc0ee
Updated test to match comment
joshuatorrance 518791e
Tweaked handling of frequency parsing to support Xhr/day/mon for ice …
joshuatorrance 6e94bd9
Extracted ESM1.6 filename fucntionality to a separate file
joshuatorrance 2b5836e
Instantaneous files now use "snap" for filename, added tests and bett…
joshuatorrance 49588d7
Tweaked _build_cell_methods to make it more reliable and consistent
joshuatorrance d51b3c0
Attempting to move to src-layout since there are multiple modules now…
joshuatorrance 14558d8
Github runner is struggling with diskspace - so cleaning up ncfiles i…
joshuatorrance cd85ef7
Py3.10 doesn't have exception.add_note, missing f for str
joshuatorrance d41e065
Removed unused import
joshuatorrance c6a97d0
Updated readme with new commanline options and commandline script
joshuatorrance File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| from .splitnc import * |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import logging | ||
| import re | ||
|
|
||
|
|
||
| def _build_model(): | ||
| # Model is always access-esm1p6 | ||
| return "access-esm1p6" | ||
|
|
||
|
|
||
| def _build_component(ds): | ||
| # Component: either CICE5 or UM7.3 | ||
| source = ds.attrs["source"] | ||
| if "Los Alamos Sea Ice Model (CICE) Version 5" in source: | ||
| return "cice5" | ||
| elif "Data from Met Office Unified Model" in source and \ | ||
| ds.attrs['um_version'] == "7.3": | ||
| return "um7p3" | ||
| else: | ||
| raise ValueError(f"Unknown source, {source}") | ||
|
|
||
|
|
||
| def _build_dimensions(ds, field_name): | ||
| # Dimensions: Don't count time when seeing if field is 2d or 3d | ||
| ndims = len([d for d in ds[field_name].dims if d!='time']) | ||
| if ndims == 2: | ||
| return "2d" | ||
| elif ndims == 3: | ||
| return "3d" | ||
| else: | ||
| raise ValueError(f"Unexpected number for dimensions, {ndims}") | ||
|
|
||
|
|
||
| def _build_frequency(ds, field_name, input_filepath): | ||
| # Frequency: use fx if no time dim | ||
| if 'time' not in ds[field_name].dims: | ||
| return "fx" | ||
|
|
||
| # Attempt to parse from expected filenames | ||
| filename = input_filepath.name | ||
|
|
||
| # Define the expected ice filenames | ||
| # e.g. iceh-2hourly-mean_0272.nc, iceh-1yearly-mean_0272.nc | ||
| ice_regex = r"iceh-(?P<num>\d+)(?P<unit>yearly|monthly|daily|hourly)-" | ||
| ice_unit_mapping = { | ||
| "yearly": "yr", | ||
| "monthly": "mon", | ||
| "daily": "day", | ||
| "hourly": "hr" | ||
| } | ||
|
|
||
| if match:=re.match(ice_regex, filename): | ||
| # Extract the frequency number and units for ice files | ||
| return f"{match['num']}{ice_unit_mapping[match['unit']]}" | ||
| elif "_mon.nc" in filename: | ||
| # Match the monthly pattern for atmosphere files | ||
| return "1mon" | ||
| elif "_dai.nc" in filename: | ||
| # Match the daily pattern for atmosphere files | ||
| return "1day" | ||
| elif match:=re.match(r".+_(\d+hr).nc", filename): | ||
| # Get the frequency from the atmosphere regex match for Xhr | ||
| return match[1] | ||
| elif "aiihca.pc" in filename: | ||
| # Match another pattern for hourly atmosphere files | ||
| return "1hr" | ||
|
|
||
| # No sub-hourly frequency data expected | ||
| raise ValueError("Unable to deduce frequency from filename") | ||
|
|
||
|
|
||
|
|
||
| def _build_cell_method(ds, field_name): | ||
| attrs = ds[field_name].attrs | ||
|
|
||
| try: | ||
| if attrs['time_rep'] == "instantaneous": | ||
| # ice files sometimes have time_rep = instantaneous but not | ||
| # cell_methods = time: point | ||
| return ".snap" | ||
| except KeyError: | ||
| # Continue if 'time_rep' not in attrs | ||
| pass | ||
|
|
||
| # Time cell_method: Should be able to deduce from the cell_method | ||
| cell_method_regx = r"time: (\w+)" | ||
| try: | ||
| if m:= re.search(cell_method_regx, attrs["cell_methods"]): | ||
| method = m[1] | ||
| if method == "point": | ||
| method = "snap" | ||
|
|
||
| # Since this element is optional add the . here | ||
| return "." + method | ||
| except KeyError: | ||
| # Continue if 'cell_methods' not in attrs | ||
| pass | ||
|
|
||
| # Otherwise omit this element from the filename | ||
| return "" | ||
|
|
||
|
|
||
| def _build_datestamp(ds, field_name, file_freq): | ||
| if 'time' not in ds[field_name].dims: | ||
| # No datetime for fixed files | ||
| return "" | ||
|
|
||
| # Truncate average time val by output file frequency | ||
| # datetimes do not correctly zero-pad so need to use %4Y | ||
| if re.match(r'\d+(yr|dec)', file_freq): | ||
| fmt = '%4Y' | ||
| elif re.match(r'\d+mon', file_freq): | ||
| fmt = '%4Y-%m' | ||
| elif re.match(r'\d+day', file_freq): | ||
| fmt = '%4Y-%m-%d' | ||
| else: | ||
| fmt = '%4Y-%m-%dT%H:%M:%S' | ||
|
|
||
| # Get the appropriately truncated datetime for the average time | ||
| try: | ||
| # Try the time bounds | ||
| time_arr = ds[ds['time'].attrs["bounds"]] | ||
| logging.debug("Using time bounds to calculate filename timestamp") | ||
| except KeyError: | ||
| # If there are no time bounds just use time | ||
| logging.debug("Unable to find time bounds, using time to calculate filename timestamp") | ||
| time_arr = ds['time'] | ||
|
|
||
| # Calculate the middle point | ||
| first, last = time_arr.min(), time_arr.max() | ||
| datestamp_dt = (first + (last - first) / 2).dt | ||
|
|
||
| return "." + datestamp_dt.strftime(fmt).data.flatten()[0] | ||
|
|
||
|
|
||
| def build_esm1p6_filename(ds, field_name, input_filepath, esm1p6_filename=False, file_freq="1yr"): | ||
| template = "{model}.{component}.{dimensions}.{field}.{freq}{time_cell_method}{datestamp}.nc" | ||
|
|
||
| # Model is always access-esm1p6 | ||
| try: | ||
| d = { | ||
| "model": _build_model(), | ||
| "component": _build_component(ds), | ||
| "dimensions": _build_dimensions(ds, field_name), | ||
| "field": field_name, | ||
| "freq": _build_frequency(ds, field_name, input_filepath), | ||
| "time_cell_method": _build_cell_method(ds, field_name), | ||
| "datestamp": _build_datestamp(ds, field_name, file_freq), | ||
| } | ||
| except ValueError as e: | ||
| # Reraise the exception with some extra information | ||
| e.args = (*e.args, f"While building output filename for field {field_name} and {input_filepath}") | ||
| raise | ||
|
|
||
| return template.format(**d) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.