11
11
from .common import AbstractWritableDataStore
12
12
from .netcdf3 import encode_nc3_variable , maybe_convert_to_char_array
13
13
14
+ # This lookup table maps from dtype.byteorder to a readable endian
15
+ # string used by netCDF4.
16
+ _endian_lookup = {'=' : 'native' ,
17
+ '>' : 'big' ,
18
+ '<' : 'little' ,
19
+ '|' : 'native' }
20
+
14
21
15
22
class NetCDF4ArrayWrapper (NDArrayMixin ):
16
23
def __init__ (self , array ):
@@ -83,6 +90,27 @@ def _ensure_fill_value_valid(data, attributes):
83
90
attributes ['_FillValue' ] = np .string_ (attributes ['_FillValue' ])
84
91
85
92
93
+ def _force_native_endianness (var ):
94
+ # possible values for byteorder are:
95
+ # = native
96
+ # < little-endian
97
+ # > big-endian
98
+ # | not applicable
99
+ # Below we check if the data type is not native or NA
100
+ if var .dtype .byteorder not in ['=' , '|' ]:
101
+ # if endianness is specified explicitly, convert to the native type
102
+ data = var .values .astype (var .dtype .newbyteorder ('=' ))
103
+ var = Variable (var .dims , data , var .attrs , var .encoding )
104
+ # if endian exists, remove it from the encoding.
105
+ var .encoding .pop ('endian' , None )
106
+ # check to see if encoding has a value for endian its 'native'
107
+ if not var .encoding .get ('endian' , 'native' ) is 'native' :
108
+ raise NotImplementedError ("Attempt to write non-native endian type, "
109
+ "this is not supported by the netCDF4 python "
110
+ "library." )
111
+ return var
112
+
113
+
86
114
class NetCDF4DataStore (AbstractWritableDataStore ):
87
115
"""Store for reading and writing data via the Python-NetCDF4 library.
88
116
@@ -152,6 +180,9 @@ def set_attribute(self, key, value):
152
180
153
181
def set_variable (self , name , variable ):
154
182
attrs = variable .attrs .copy ()
183
+
184
+ variable = _force_native_endianness (variable )
185
+
155
186
if self .format == 'NETCDF4' :
156
187
variable , datatype = _nc4_values_and_dtype (variable )
157
188
else :
@@ -167,6 +198,8 @@ def set_variable(self, name, variable):
167
198
fill_value = None
168
199
169
200
encoding = variable .encoding
201
+ data = variable .values
202
+
170
203
nc4_var = self .ds .createVariable (
171
204
varname = name ,
172
205
datatype = datatype ,
@@ -177,11 +210,11 @@ def set_variable(self, name, variable):
177
210
fletcher32 = encoding .get ('fletcher32' , False ),
178
211
contiguous = encoding .get ('contiguous' , False ),
179
212
chunksizes = encoding .get ('chunksizes' ),
180
- endian = encoding . get ( 'endian' , ' native') ,
213
+ endian = ' native' ,
181
214
least_significant_digit = encoding .get ('least_significant_digit' ),
182
215
fill_value = fill_value )
183
216
nc4_var .set_auto_maskandscale (False )
184
- nc4_var [:] = variable . values
217
+ nc4_var [:] = data
185
218
for k , v in iteritems (attrs ):
186
219
# set attributes one-by-one since netCDF4<1.0.10 can't handle
187
220
# OrderedDict as the input to setncatts
0 commit comments