-
Couldn't load subscription status.
- Fork 297
Support character arrays #6764
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
Draft
pp-mo
wants to merge
12
commits into
SciTools:main
Choose a base branch
from
pp-mo:chardata
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.
Draft
Support character arrays #6764
Changes from 7 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4653710
Disable byte decoding on load.
pp-mo 3c50da4
Fix label data decoding, for when coded bytes contain zero-bytes: WIP…
pp-mo a0a969b
Initial tests.
pp-mo 9d894f6
Get 'create_cf_data_variable' to call 'create_generic_cf_array_var': …
pp-mo b0b673b
Fix to temporary tests.
pp-mo 1bcc78d
Support encoding on array writes.
pp-mo 292ca9f
Reinstate decode on load, now in-Iris coded.
pp-mo c3f9192
Hack to preserve the existing order of attributes on saved Coords and…
pp-mo 5a5a07f
Fix for dataless; avoid FUTURE global state change from temporary tests.
pp-mo adf4229
Further fix to attribute ordering.
pp-mo 536c932
Fix use of ncdump for tests in Iris.
pp-mo 86ccbc6
Fixes for data packing.
pp-mo 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,7 @@ | |
| """ | ||
|
|
||
| from abc import ABCMeta, abstractmethod | ||
| import codecs | ||
| from collections.abc import Iterable, MutableMapping | ||
| import os | ||
| import re | ||
|
|
@@ -89,6 +90,11 @@ def __init__(self, name, data): | |
|
|
||
| self.cf_data = data | ||
| """NetCDF4 Variable data instance.""" | ||
| # Note: *always* disable encoding/decoding translations | ||
| # To avoid current known problems | ||
| # See https://github.com/Unidata/netcdf4-python/issues/1440 | ||
| data.set_auto_chartostring(False) | ||
| # ALSO NOTE: not stored. NetCDFDataProxy must re-assert when re-loading. | ||
|
|
||
| """File source of the NetCDF content.""" | ||
| try: | ||
|
|
@@ -790,25 +796,73 @@ def cf_label_data(self, cf_data_var): | |
|
|
||
| # Determine the name of the label string (or length) dimension by | ||
| # finding the dimension name that doesn't exist within the data dimensions. | ||
| str_dim_name = list(set(self.dimensions) - set(cf_data_var.dimensions)) | ||
| str_dim_names = list(set(self.dimensions) - set(cf_data_var.dimensions)) | ||
| n_nondata_dims = len(str_dim_names) | ||
|
|
||
| if n_nondata_dims == 0: | ||
| # *All* dims are shared with the data-variable. | ||
| # This is only ok if the data-var is *also* a string type. | ||
| dim_ok = _is_str_dtype(cf_data_var) | ||
| # In this case, we must just *assume* that the last dimension is "the" | ||
| # string dimension | ||
| str_dim_name = self.dimensions[-1] | ||
| else: | ||
| # If there is exactly one non-data dim, that is the one we want | ||
| dim_ok = len(str_dim_names) == 1 | ||
| (str_dim_name,) = str_dim_names | ||
|
|
||
| if len(str_dim_name) != 1: | ||
| if not dim_ok: | ||
| raise ValueError( | ||
| "Invalid string dimensions for CF-netCDF label variable %r" | ||
| % self.cf_name | ||
| ) | ||
|
|
||
| str_dim_name = str_dim_name[0] | ||
| label_data = self[:] | ||
|
|
||
| if ma.isMaskedArray(label_data): | ||
| label_data = label_data.filled() | ||
| label_data = label_data.filled(b"\0") | ||
|
|
||
| default_encoding = "utf-8" | ||
| encoding = getattr(self, "_Encoding", None) | ||
| if encoding is None: | ||
| # utf-8 is a reasonable "safe" default, equivalent to 'ascii' for ascii data | ||
| encoding = default_encoding | ||
| else: | ||
| try: | ||
| # Accept + normalise naming of encodings | ||
| encoding = codecs.lookup(encoding).name | ||
| # NOTE: if encoding does not suit data, errors can occur. | ||
| # For example, _Encoding = "ascii", with non-ascii content. | ||
| except LookupError: | ||
| # Replace some invalid setting with "safe"(ish) fallback. | ||
| encoding = default_encoding | ||
|
|
||
| def string_from_1d_bytearray(array, encoding): | ||
| r"""Because numpy bytes arrays behave very oddly. | ||
|
|
||
| Elements which "should" contain a zero byte b'\0' instead appear to contain | ||
| an *empty* byte b''. So a "b''.join()" will *omit* any zero bytes. | ||
| """ | ||
| assert array.dtype.kind == "S" and array.dtype.itemsize == 1 | ||
| assert array.ndim == 1 | ||
| bytelist = [b"\0" if byte == b"" else byte for byte in array] | ||
| bytes = b"".join(bytelist) | ||
| assert len(bytes) == array.shape[0] | ||
| try: | ||
| string = bytes.decode(encoding=encoding) | ||
| except UnicodeDecodeError: | ||
| # if encoding == "ascii": | ||
| # print("\n\n*** FIX !!") | ||
| # string = bytes.decode("utf-8") | ||
| # else: | ||
|
Comment on lines
+854
to
+857
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: remove |
||
| raise | ||
| result = string.strip() | ||
| return result | ||
|
|
||
| # Determine whether we have a string-valued scalar label | ||
| # i.e. a character variable that only has one dimension (the length of the string). | ||
| if self.ndim == 1: | ||
| label_string = b"".join(label_data).strip() | ||
| label_string = label_string.decode("utf8") | ||
| label_string = string_from_1d_bytearray(label_data, encoding) | ||
| data = np.array([label_string]) | ||
| else: | ||
| # Determine the index of the string dimension. | ||
|
|
@@ -829,9 +883,10 @@ def cf_label_data(self, cf_data_var): | |
| else: | ||
| label_index = index + (slice(None, None),) | ||
|
|
||
| label_string = b"".join(label_data[label_index]).strip() | ||
| label_string = label_string.decode("utf8") | ||
| data[index] = label_string | ||
| label_string = string_from_1d_bytearray( | ||
| label_data[label_index], encoding | ||
| ) | ||
| data[index] = label_string.strip() | ||
|
|
||
| return data | ||
|
|
||
|
|
||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NOTE: this possibly needs to be implemented for ancillary-variables too