Skip to content
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

float32 instead of float64 when decoding int16 with scale_factor netcdf var using xarray #2304

Closed
DevDaoud opened this issue Jul 23, 2018 · 33 comments · Fixed by #8713 · May be fixed by #2751 or #6812
Closed

float32 instead of float64 when decoding int16 with scale_factor netcdf var using xarray #2304

DevDaoud opened this issue Jul 23, 2018 · 33 comments · Fixed by #8713 · May be fixed by #2751 or #6812

Comments

@DevDaoud
Copy link

Code Sample :

Considering a netcdf file file with the following variable:

short agc_40hz(time, meas_ind) ;
        agc_40hz:_FillValue = 32767s ;
        agc_40hz:units = "dB" ;
        agc_40hz:scale_factor = 0.01 ;

Code:

from netCDF4 import Dataset
import xarray as xr

d = Dataset("test.nc")
a = d.variables['agc_40hz'][:].flatten()[69] ## 21.940000000000001 'numpy.float64'
x = xr.open_dataset("test.nc")
b = x['agc_40hz'].values.flatten()[69] ## 21.939998626708984 'numpy.float32'
abs(a - b) # 0.000001373291017

Problem description :

Different behaviour of xarray comparing to netCDF4 Dataset

When reading the dataset with xarray we found that the decoded type was numpy.float32 instead of numpy.float64
This netcdf variable has an int16 dtype
when the variable is read with the netCDF4 library directly, it is automatically converted to numpy.float64.
in our case we loose on precision when using xarray.
We found two solutions for this:

First solution :

This solution aims to prevent auto_maskandscale

d = Dataset("test.nc")
a = d.variables['agc_40hz'][:].flatten()[69] ## 21.940000000000001 'numpy.float64'
x = xr.open_dataset("test.nc", mask_and_scale=False, decode_times=False)
b = x['agc_40hz'].values.flatten()[69] ## 21.940000000000001 'numpy.float64'
abs(a - b) # 0.000000000000000

Modification in xarray/backends/netCDF4_.py line 241

def _disable_auto_decode_variable(var):
    """Disable automatic decoding on a netCDF4.Variable.

    We handle these types of decoding ourselves.
    """
    pass
    # var.set_auto_maskandscale(False)
    # # only added in netCDF4-python v1.2.8
    # with suppress(AttributeError):
    #     var.set_auto_chartostring(False)

Second solution :

This solution uses numpy.float64 whatever integer type provided.

d = Dataset("test.nc")
a = d.variables['agc_40hz'][:].flatten()[69] ## 21.940000000000001 'numpy.float64'
x = xr.open_dataset("test.nc")
b = x['agc_40hz'].values.flatten()[69] ## 21.940000000000001 'numpy.float64'
abs(a - b) # 0.000000000000000

Modification in xarray/core/dtypes.py line 85

def maybe_promote(dtype):
    """Simpler equivalent of pandas.core.common._maybe_promote

    Parameters
    ----------
    dtype : np.dtype

    Returns
    -------
    dtype : Promoted dtype that can hold missing values.
    fill_value : Valid missing value for the promoted dtype.
    """
    # N.B. these casting rules should match pandas
    if np.issubdtype(dtype, np.floating):
        fill_value = np.nan
    elif np.issubdtype(dtype, np.integer):
        #########################
        #OLD CODE BEGIN
        #########################
        # if dtype.itemsize <= 2:
        #     dtype = np.float32
        # else:
        #     dtype = np.float64
        #########################
        #OLD CODE END
        #########################

        #########################
        #NEW CODE BEGIN
        #########################
        dtype = np.float64 # whether it's int16 or int32 we use float64
        #########################
        #NEW CODE END
        #########################
        fill_value = np.nan
    elif np.issubdtype(dtype, np.complexfloating):
        fill_value = np.nan + np.nan * 1j
    elif np.issubdtype(dtype, np.datetime64):
        fill_value = np.datetime64('NaT')
    elif np.issubdtype(dtype, np.timedelta64):
        fill_value = np.timedelta64('NaT')
    else:
        dtype = object
        fill_value = np.nan
    return np.dtype(dtype), fill_value

Solution number 2 would be great for us.
At this point we don't know if this modification would introduce some side effects.
Is there another way to avoid this problem ?

Expected Output

In our case we expect the variable to be in numpy.float64 as it is done by netCDF4.

Output of xr.show_versions()

INSTALLED VERSIONS ------------------ commit: None python: 3.5.2.final.0 python-bits: 64 OS: Linux OS-release: 4.15.0-23-generic machine: x86_64 processor: x86_64 byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: en_US.UTF-8

xarray: 0.10.8
pandas: 0.23.3
numpy: 1.15.0rc2
scipy: 1.1.0
netCDF4: 1.4.0
h5netcdf: None
h5py: None
Nio: None
zarr: None
bottleneck: None
cyordereddict: None
dask: 0.18.1
distributed: 1.22.0
matplotlib: 2.2.2
cartopy: None
seaborn: None
setuptools: 40.0.0
pip: 10.0.1
conda: None
pytest: 3.6.3
IPython: 6.4.0
sphinx: None

@shoyer
Copy link
Member

shoyer commented Jul 23, 2018

To clarify: why is it a problem for you to get floating point values like 21.939998626708984 instead of 21.940000000000001? Is it a loss of precision in some downstream calculation? Both numbers are accurate well within the precision indicated by the netCDF file (0.01).

Note that it's very easy to later convert from float32 to float64, e.g., by writing ds.astype(np.float64).

@DevDaoud
Copy link
Author

Thank you for your quick answer.
In our case we could evaluate std dev or square sums on long lists of values and the accumulation of those small values due to float32 type could create considerable differences.

@Thomas-Z
Copy link
Contributor

Thomas-Z commented Aug 6, 2018

You're right when you say

Note that it's very easy to later convert from float32 to float64, e.g., by writing ds.astype(np.float64).

You'll have a float64 in the end but you won't get your precision back and it might be a problem in some case.

I understand the benefits of using float32 on the memory side but it is kind of a problem for us each time we have variables using scale factors.

I'm surprised this issue (if considered as one) does not bother more people.

@DevDaoud
Copy link
Author

DevDaoud commented Aug 6, 2018

As mentioned in the original issue the modification is straightforward.
Any ideas if this could be integrated to xarray anytime soon ?

@fmaussion
Copy link
Member

As mentioned in the original issue the modification is straightforward.
Any ideas if this could be integrated to xarray anytime soon ?

Some people might prefer float32, so it is not as straightforward as it seems. It might be possible to add an option for this, but I didn't look into the details.

You'll have a float64 in the end but you won't get your precision back

Note that this is a fake sense of precision, because in the example above the compression used is lossy, i.e. precision was lost at compression and the actual precision is now 0.01:

short agc_40hz(time, meas_ind) ;
        agc_40hz:_FillValue = 32767s ;
        agc_40hz:units = "dB" ;
        agc_40hz:scale_factor = 0.01 ;

@dopplershift
Copy link
Contributor

dopplershift commented Aug 6, 2018

A float32 values has 24 bits of precision in the significand, which is more than enough to store the 16-bits in in the original data; the exponent (8 bits) will more or less take care of the * 0.01:

>>> import numpy as np
>>> np.float32(2194 * 0.01)
21.94

What you're seeing is an artifact of printing out the values. I have no idea why something is printing out a float (only 7 decimal digits) out to 17 digits. Even float64 only has 16 digits (which is overkill for this application).

The difference in subtracting the 32- and 64-bit values above are in the 8th decimal place, which is beyond the actual precision of the data; what you've just demonstrated is the difference in precision between 32-bit and 64-bit values, but it had nothing to do whatsoever with the data.

If you're really worried about precision round-off for things like std. dev, you should probably calculate it using the raw integer values and scale afterwards. (I don't actually think this is necessary, though.)

@shoyer
Copy link
Member

shoyer commented Aug 6, 2018

A float32 values has 24 bits of precision in the significand, which is more than enough to store the 16-bits in in the original data; the exponent (8 bits) will more or less take care of the * 0.01:

Right. The actual raw data is being stored as an integer 21940 (along with the scale factor of 0.01). Both 21.939998626708984 (as float32) and 21.940000000000001 (as float64) are floating point approximations of the exact decimal number 219.40.

I would be happy to add options for whether to default to float32 or float64 precision. There are clearly tradeoffs here:

  • float32 uses half the memory
  • float64 has more precision for downstream computation

I don't think we can make a statement about which is better in general. The best we can do is make an educated guess about which will be more useful / less surprising for most and/or new users, and pick that as the default.

@dopplershift
Copy link
Contributor

dopplershift commented Aug 6, 2018

@shoyer But since it's a downstream calculation issue, and does not impact the actual precision of what's being read from the file, what's wrong with saying "Use data.astype(np.float64)". It's completely identical to doing it internally to xarray.

@shoyer
Copy link
Member

shoyer commented Aug 6, 2018

But since it's a downstream calculation issue, and does not impact the actual precision of what's being read from the file, what's wrong with saying "Use data.astype(np.float64)". It's completely identical to doing it internally to xarray.

It's almost but not quite identical. The difference is that the data gets scaled twice. This adds twice the overhead for scaling the values (which to be fair is usually negligible compared to IO).

Also, to get exactly equivalent numerics for further computation you would need to round again, e.g., data.astype(np.float64).round(np.ceil(-np.log10(data.encoding['scale_factor']))). This starts to get a little messy :).

@dopplershift
Copy link
Contributor

I'm not following why the data are scaled twice.

Your point about the rounding being different is well-taken, though.

@shoyer
Copy link
Member

shoyer commented Aug 6, 2018

I'm not following why the data are scaled twice.

We automatically scale the data from int16->float32 upon reading it in xarray (if decode_cf=True). There's no way to turn that off and still get automatic scaling, so the best you can do is layer on int16->float32->float64, when you might prefer to only do int16->float64.

@dopplershift
Copy link
Contributor

Ah, ok, not scaling per-se (i.e. * 0.01), but a second round of value conversion.

@shoyer
Copy link
Member

shoyer commented Aug 6, 2018 via email

@Thomas-Z
Copy link
Contributor

Thomas-Z commented Aug 6, 2018

To explain the full context and why it became some kind of a problem to us :

We're experimenting with the parquet format (via pyarrow) and we first did something like :
netcdf file -> netcdf4 -> pandas -> pyarrow -> pandas (when read later on).

We're now looking at xarray and the huge ease of access it offers to netcdf like data and we tried something similar :
netcdf file -> xarray -> pandas -> pyarrow -> pandas (when read later on).

Our problem appears when we're reading and comparing the data stored with these 2 approches.
The difference between the 2 was - sometimes - larger than what expected/acceptable (10e-6 for float32 if I'm not mistaken).
We're not constraining any type and letting the system and modules decide how to encode what and in the end we have significantly different values.

There might be something wrong in our process but it originate here with this float32/float64 choice so we thought it might be a problem.

Thanks for taking the time to look into this.

@shoyer
Copy link
Member

shoyer commented Aug 6, 2018 via email

@Thomas-Z
Copy link
Contributor

Thomas-Z commented Aug 8, 2018

So, a more complete example showing this problem.
NetCDF file used in the example : test.nc.zip

from netCDF4 import Dataset
import xarray as xr
import numpy as np
import pandas as pd

d = Dataset("test.nc")
v = d.variables['var']

print(v)
#<class 'netCDF4._netCDF4.Variable'>
#int16 var(idx)
#    _FillValue: 32767
#    scale_factor: 0.01
#unlimited dimensions: 
#current shape = (2,)
#filling on

df_nc = pd.DataFrame(data={'var': v[:]})

print(df_nc)
#     var
#0  21.94
#1  27.04


ds = xr.open_dataset("test.nc")
df_xr = ds['var'].to_dataframe()

# Comparing both dataframes with float32 precision (1e-6)
mask = np.isclose(df_nc['var'], df_xr['var'], rtol=0, atol=1e-6)

print(mask)
#[False  True]

print(df_xr)
#           var
#idx           
#0    21.939999
#1    27.039999

# Changing the type and rounding the xarray dataframe
df_xr2 = df_xr.astype(np.float64).round(int(np.ceil(-np.log10(ds['var'].encoding['scale_factor']))))
mask = np.isclose(df_nc['var'], df_xr2['var'], rtol=0, atol=1e-6)

print(mask)
#[ True  True]

print(df_xr2)
#       var
#idx       
#0    21.94
#1    27.04

As you can see, the problem appears early in the process (not related to the way data are stored in parquet later on) and yes, rounding values does solve it.

@DevDaoud
Copy link
Author

Any updates about this ?

@fmaussion
Copy link
Member

I think we are still talking about different things. In the example by @Thomas-Z above there is still a problem at the line:

# Comparing both dataframes with float32 precision (1e-6)
mask = np.isclose(df_nc['var'], df_xr['var'], rtol=0, atol=1e-6)

As discussed several times above, this test is misleading: it should assert for atol=0.01, which is the real accuracy of the underlying data. For this purpose float32 is more than good enough.

@shoyer said:

I would be happy to add options for whether to default to float32 or float64 precision.

so we would welcome a PR in this direction! I don't think we need to change the default behavior though, as there is a slight possibility that some people are relying on the data being float32.

@DevDaoud
Copy link
Author

DevDaoud commented Jan 7, 2019

Hi,
thank you for your effort into making xarray a great library.
As mentioned in the issue the discussion went on a PR in order to make xr.open_dataset parametrable.
This post is about asking you about recommendations regarding our PR.

In this case we would add a parameter to the open_dataset function called "force_promote" which is a boolean and False by default and thus not mandatory.
And then spread that parameter down to the function maybe_promote in dtypes.py
Where we say the following:

if dtype.itemsize <= 2 and not force_promote:
dtype = np.float32
else:
dtype = np.float64

The downside of that is that we somehow pollute the code with a parameter that is used in a specific case.

The second approach would check the value of an environment variable called "XARRAY_FORCE_PROMOTE" if it exists and set to true would force promoting type to float64.

please tells us which approach suits best your vision of xarray.

Regards.

DevDaoud pushed a commit to DevDaoud/xarray that referenced this issue Feb 7, 2019
DevDaoud pushed a commit to DevDaoud/xarray that referenced this issue Feb 7, 2019
@magau
Copy link

magau commented Feb 12, 2019

Hi everyone,
I've start using xarray recently, so I apologize if I'm saying something wrong...
I've also faced the here reported issue, so have tried to find some answers.
Unpacking netcdf files with respect to the NUG attributes (scale_factor and add_offset) seems to be mentioned by the CF-Conventions directives. And it's clear about which data type should be applied to the unpacked data. cf-conventions-1.7/packed-data
In this chapter you can read that: "If the scale_factor and add_offset attributes are of the same data type as the associated variable, the unpacked data is assumed to be of the same data type as the packed data. However, if the scale_factor and add_offset attributes are of a different data type from the variable (containing the packed data) then the unpacked data should match the type of these attributes".
In my opinion this should be the default behavior of the xarray.decode_cf function. Which doesn't invalidate the idea of forcing the unpacked data dtype.
However non of the CFScaleOffsetCoder and CFMaskCoder de/encoder classes seems to be according with these CF directives, since the first one doesn't look for the scale_factor or add_offset dtypes, and the second one also changes the unpacked data dtype (maybe because nan values are being used to replace the fill values).
Sorry for such an extensive comment, without any solutions proposal...
Regards! 👍

@shoyer
Copy link
Member

shoyer commented Feb 12, 2019

@magau thanks for pointing this out -- I think we simplify missed this part of the CF conventions document!

Looking at the dtype for add_offset and scale_factor does seem like a much cleaner way to handle this issue. I think we should give that a try!

We will still need some fall-back choice for CFMaskCoder if neither a add_offset or scale_factor attribute is provided (due to xarray's representation of missing values as NaN), but this is a relatively uncommon situation.

@psybot-ca
Copy link

Hey everyone, tumbled on this while searching for approximately the same problem. Thought I'd share since the issue is still open. On my part, there is two situations that seem buggy. I haven't been using xarray for that long yet so maybe there is something I'm missing here...

My first problem relates to the data types of dimensions with float notation. To give another answer to @shoyer's question:

To clarify: why is it a problem for you

it is a problem in my case because I would like to perform slicing operations of a dataset using longitude values from another dataset. This operation raises a "KeyError : not all values found in index 'longitude'" since either one of the dataset's longitude is float32 and the other is float64 or because both datasets' float32 approximations are not exactly the same value in each dataset. I can work around this and assign new coords to be float64 after reading and it works, though it is kind of a hassle considering I have to perform this thousands of times. This situation also create a problem when concatenating multiple netCDF files together (along time dim in my case). The discrepancies between the approximations of float32 values or the float32 vs float 64 situation will add new dimension values where it shouldn't.

On the second part of my problem, it comes with writing/reading netCDF files (maybe more related to @daoudjahdou problem). I tried to change the data type to float64 for all my files, save them and then perform what I need to do, but for some reason even though dtype is float64 for all my dimensions when writing the files (using default args), it will sometime be float32, sometime float64 when reading the files (with default ags values) previously saved with float64 dtype. If using the default args, shouldn't the decoding makes the dtype of dimension the same for all files I read?

@ACHMartin
Copy link

ACHMartin commented Jun 1, 2021

Dear all and thank you for your work on Xarray,

Link to @magau comment, I have a netcdf with multiple variables in different format (float, short, byte).
Using open_mfdataset 'short' and 'byte' are converted in 'float64' (no scaling, but some masking for the float data).
It doesn't raise major issue for me, but it is taking plenty of memory space for nothing.

Below an example of the 3 format from (ncdump -h):

	short total_nobs(time, lat, lon) ;
		total_nobs:long_name = "Number of SSS in the time interval" ;
		total_nobs:valid_min = 0s ;
		total_nobs:valid_max = 10000s ;
	float pct_var(time, lat, lon) ;
		pct_var:_FillValue = NaNf ;
		pct_var:long_name = "Percentage of SSS_variability that is expected to be not explained by the products" ;
		pct_var:units = "%" ;
		pct_var:valid_min = 0. ;
		pct_var:valid_max = 100. ;
	byte sss_qc(time, lat, lon) ;
		sss_qc:long_name = "Sea Surface Salinity Quality, 0=Good; 1=Bad" ;
		sss_qc:valid_min = 0b ;
		sss_qc:valid_max = 1b ;

And how they appear after opening in as xarray using open_mfdataset:

total_nobs (time, lat, lon) float64 dask.array<chunksize=(48, 584, 1388), meta=np.ndarray>
pct_var (time, lat, lon) float32 dask.array<chunksize=(48, 584, 1388), meta=np.ndarray>
sss_qc (time, lat, lon) float64 dask.array<chunksize=(48, 584, 1388), met

Is there any recommandation?
Regards

@mankoff
Copy link
Contributor

mankoff commented Jul 19, 2022

I've run into this issue too, and the xarray decision to use float32 is causing problems. I recognize this is a generic floating-point representation issue, but it could be avoided with float64.

The data value is 1395.
The scale is 0.0001.

val = int(1395)
scale = 0.0001
print(val*scale) # 0.1395
print( val * np.array(scale).astype(float) ) # 0.1395
print( val * np.array(scale).astype(np.float16) ) # 0.1395213...
print( val * np.array(scale).astype(np.float32) ) # 0.13949999...
print( val * np.array(scale).astype(np.float64) ) # 0.1395

Because we are using *1E3 * round(), the difference between 0.1395 and 0.1394999 (or 139.5 and 139.49) ends up being quite large in the downstream product.

@dcherian
Copy link
Contributor

We'd happily take a PR implementing the suggestion above following CF-conventions.

Looking at the dtype for add_offset and scale_factor does seem like a much cleaner way to handle this issue. I think we should give that a try!

IIUC the change should be made here in _choose_float_dtype:

def decode(self, variable, name=None):
dims, data, attrs, encoding = unpack_for_decoding(variable)
if "scale_factor" in attrs or "add_offset" in attrs:
scale_factor = pop_to(attrs, encoding, "scale_factor", name=name)
add_offset = pop_to(attrs, encoding, "add_offset", name=name)
dtype = _choose_float_dtype(data.dtype, "add_offset" in attrs)
if np.ndim(scale_factor) > 0:
scale_factor = np.asarray(scale_factor).item()
if np.ndim(add_offset) > 0:
add_offset = np.asarray(add_offset).item()
transform = partial(
_scale_offset_decoding,
scale_factor=scale_factor,
add_offset=add_offset,
dtype=dtype,
)
data = lazy_elemwise_func(data, transform, dtype)

@mankoff
Copy link
Contributor

mankoff commented Jul 30, 2022

This issue, based on its title and initial post, is fixed by PR #6851. The code to select dtype was already correct, but the outer function that called it had a bug in the call.

Per the CF spec,

the unpacked data should match the type of these attributes, which must both be of type float or both be of type double. An additional restriction in this case is that the variable containing the packed data must be of type byte, short or int. It is not advised to unpack an int into a float as there is a potential precision loss.

I find this is ambiguous. is float above referring to float16 or float32? Is double referring to float64? If so, then they do recommend float64, as requested by the OP, because the test data is short and the scale_factor is float64 (a.k.a double?)

The broader discussion here is about CF compliance. I find the spec ambiguous and xarray non-compliant. So many tests rely on the existing behavior, that I am unsure how best to proceed to improve compliance. I worry it may be a major refactor, and possibly break things relying on the existing behavior. I'd like to discuss architecture. Should this be in a new issue, if this closes with PR #6851? Should there be a new keyword for cf_strict or something?

@shoyer
Copy link
Member

shoyer commented Jul 30, 2022

the unpacked data should match the type of these attributes, which must both be of type float or both be of type double. An additional restriction in this case is that the variable containing the packed data must be of type byte, short or int. It is not advised to unpack an int into a float as there is a potential precision loss.

I find this is ambiguous. is float above referring to float16 or float32? Is double referring to float64?

Yes, I'm pretty sure "float" means single precision (np.float32), given that "double" certainly means double precision (no.float64).

If so, then they do recommend float64, as requested by the OP, because the test data is short and the scale_factor is float64 (a.k.a double?)

Yes, I believe so.

The broader discussion here is about CF compliance. I find the spec ambiguous and xarray non-compliant. So many tests rely on the existing behavior, that I am unsure how best to proceed to improve compliance. I worry it may be a major refactor, and possibly break things relying on the existing behavior. I'd like to discuss architecture. Should this be in a new issue, if this closes with PR #6851? Should there be a new keyword for cf_strict or something?

I think we can treat this a bug fix and just go forward with it. Yes, some people are going to be surprised, but I don't think it's distruptive enough that we need to go to a major effort to preserve backwards compatibility. It should already be straightforward to work around by setting decode_cf=False when opening a file and then explicitly calling xarray.decode_cf().

@mankoff
Copy link
Contributor

mankoff commented Aug 1, 2022

Current algorithm

def _choose_float_dtype(dtype, has_offset):
    """Return a float dtype that can losslessly represent `dtype` values."""
    # Keep float32 as-is.  Upcast half-precision to single-precision,
    # because float16 is "intended for storage but not computation"
    if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floating):
        return np.float32
    # float32 can exactly represent all integers up to 24 bits
    if dtype.itemsize <= 2 and np.issubdtype(dtype, np.integer):
        # A scale factor is entirely safe (vanishing into the mantissa),
        # but a large integer offset could lead to loss of precision.
        # Sensitivity analysis can be tricky, so we just use a float64
        # if there's any offset at all - better unoptimised than wrong!
        if not has_offset:
            return np.float32
        # For all other types and circumstances, we just use float64.
        # (safe because eg. complex numbers are not supported in NetCDF)
    return np.float64

Due to calling bug, has_offset is always None, so this can be simplified to:

def _choose_float_dtype(dtype)
    if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floating):
        return np.float32
    if dtype.itemsize <= 2 and np.issubdtype(dtype, np.integer):
        return np.float32
    return np.float64

Here I call the function twice, once with has_offset False, then True.

import numpy as np

def _choose_float_dtype(dtype, has_offset):
    if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floating):
        return np.float32
    if dtype.itemsize <= 2 and np.issubdtype(dtype, np.integer):
        if not has_offset:
            return np.float32
    return np.float64

# generic types
for dtype in [np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong,
              np.half, np.float16, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble,
              np.int8, np.int16, np.int32, np.int64,
              np.uint8, np.uint16, np.uint32, np.uint64,
              np.float16, np.float32, np.float64]:
    print("|", dtype, "|", _choose_float_dtype(np.dtype(dtype), False), "|",  _choose_float_dtype(np.dtype(dtype), True), "|")
Input Output as called Output as written
<class 'numpy.int8'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.uint8'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.int16'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.uint16'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.int32'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.uint32'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.int64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.uint64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.longlong'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.ulonglong'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.float16'> <class 'numpy.float32'> <class 'numpy.float32'>
<class 'numpy.float16'> <class 'numpy.float32'> <class 'numpy.float32'>
<class 'numpy.float32'> <class 'numpy.float32'> <class 'numpy.float32'>
<class 'numpy.float64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.float128'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.complex64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.complex128'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.complex256'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.int8'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.int16'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.int32'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.int64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.uint8'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.uint16'> <class 'numpy.float32'> <class 'numpy.float64'>
<class 'numpy.uint32'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.uint64'> <class 'numpy.float64'> <class 'numpy.float64'>
<class 'numpy.float16'> <class 'numpy.float32'> <class 'numpy.float32'>
<class 'numpy.float32'> <class 'numpy.float32'> <class 'numpy.float32'>
<class 'numpy.float64'> <class 'numpy.float64'> <class 'numpy.float64'>

@mankoff
Copy link
Contributor

mankoff commented Aug 1, 2022

This standard is more restrictive than the NUG with respect to the use of the scalefactor and addoffset attributes; ambiguities and precision problems related to data type conversions are resolved by these restrictions.

If the scalefactor and addoffset attributes are of the same data type as the associated variable, the unpacked data is assumed to be of the same data type as the packed data.

  • What if the result of the operation leads to overflow?

However, if the scalefactor and addoffset attributes are of a different data type from the variable (containing the packed data) then the unpacked data should match the type of these attributes, which must both be of type float or both be of type double.

  • What if they are not of the same type?

    • Presumably, use the largest of the three types.
  • Again, this may lead to loss of precision. what if packed data is type int64 and scalefactor is type float16. Seems like the result should be float64, not float16.

An additional restriction in this case is that the variable containing the packed data must be of type byte, short or int.

  • What to do if packed data is type float or double?

It is not advised to unpack an int into a float as there is a potential precision loss.

I think this means double is advised? If so, this should be stated. Should be rephrased to advise what to do (if there is one or only a few choices) rather than what not to do, or at least include that if not replacing current wording.

@mankoff
Copy link
Contributor

mankoff commented Aug 1, 2022

Packing Qs

  • If "the variable containing the packed data must be of type byte, short or int", how do we choose what size int?
  • What to do if scale_factor and add_offset are not float or double? What if they are different types?
    • I assume issue a warning and continue?

Unpacking Qs

  • Should the unpacked data just be np.find_common_type([data, add_offset, scale_factor], []), or should we then bump the type up by 1 level (float16->32, 32->64, 64->128, etc.) to cover overflow?

@kmuehlbauer
Copy link
Contributor

New attempt to finally resolve this in #8713.

This is in line with @shoyer's suggestion:

Looking at the dtype for add_offset and scale_factor does seem like a much cleaner way to handle this issue. I think we should give that a try!

@kmuehlbauer
Copy link
Contributor

@magau and others who still are notified here. It would be great if you could check/test/review #8713 and let us know your thoughts over there. Much appreciated.

@eschalkargans
Copy link

Hello,

I recently upgraded to the latest version of xarray. I noticed a change in the dtype, and it is likely related to this issue and associated PR.

Briefly, I have a raster in uint16 format that I want to persist as is, but reopen as float32. Its attrs are like this:

                    "dtype": "<u2",
                    "units": "digital_counts",
                    "fill_value": 0,
                    "_FillValue": 0,
                    "scale_factor": 0.0001,
                    "add_offset": -0.1,
                    "valid_min": 1,
                    "valid_max": 65535,

It is encoded as an 2-byte unsigned integer (uint16), and before was opened as a float32 with the default decode_cf=True.
But now, I get a float64 instead. I debugged a little bit to understand what's happening in the following function:

def _choose_float_dtype(
    dtype: np.dtype, mapping: MutableMapping
) -> type[np.floating[Any]]:

(_choose_float_dtype in the related PR #8713

Here is a screenshot of the followed path in the function:

Screenshot from 2024-07-16 14-58-00

I also realize, that I relied on the previous behaviour of having float32 automagically selected to decode my persisted uint16, but I never mentioned that I needed this behaviour ; I was just lucky!

The issue is that, since I specify both scale_factor and add_offset, I don't enter in the path that can return a float32.

        if scale_factor is not None:
            scale_type = np.dtype(type(scale_factor))
        if add_offset is not None:
            offset_type = np.dtype(type(add_offset))

-> This will return the platform-dependant float (float64 for me), without checking the original size of the dtype.

Maybe this is the correct behaviour, but in my case I would like to be able to choose to use float32 ; even better, encoding this "target expected dtype" in the own raster metadata.

For now, I will probably have to open my rasters with decode_cf=False and perform the scaling and offsetting operation myself. I really don't want to load float64 and downcast to float32, as it would double the initial memory usage.

Versions

xr.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.11.6 (main, Jan 10 2024, 20:45:04) [GCC 9.4.0]
python-bits: 64
OS: Linux
OS-release: 5.15.0-113-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.12.2
libnetcdf: 4.9.3-development

xarray: 2024.5.0
pandas: 2.1.4
numpy: 1.26.4
scipy: 1.13.0
netCDF4: 1.6.5
pydap: None
h5netcdf: None
h5py: 3.10.0
zarr: 2.18.1
cftime: 1.6.3
nc_time_axis: None
iris: None
bottleneck: None
dask: 2024.5.2
distributed: 2024.5.2
matplotlib: 3.7.1
cartopy: 0.22.0
seaborn: None
numbagg: None
fsspec: 2024.5.0
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: 70.0.0
pip: 23.2.1
conda: None
pytest: 7.4.3
mypy: 1.7.0
IPython: 8.20.0
sphinx: 6.2.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment