xarray-contrib / pint-xarray

Interface for using pint with xarray, providing convenience accessors
https://pint-xarray.readthedocs.io/en/latest/
Apache License 2.0
105 stars 12 forks source link

Unexpected unit conversion from Celsius to Kelvin when multiplying two DataArrays #146

Closed paigem closed 2 years ago

paigem commented 2 years ago

I have just started to use pint-xarray and have found that there is an unexpected conversion from Celsius to Kelvin when I multiply two xarray.DataArrays together. Below I have included a reproducible example of this:

import numpy as np
import xarray as xr
import cf_xarray.units
import pint_xarray

time = np.arange(10)

data = xr.DataArray(np.arange(-1,1,0.2), coords=[time], dims=['time'], attrs={'units':'degC'})
data_quantified = data.pint.quantify()
data_quantified

Output: image

Now if I try to square the quantity, I would expect to get units of degC^2, but instead it looks like the units have been converted to Kelvin and then squared:

data_quantified**2

Output: image

This same behavior occurs when multiplying data_quantified with any xarray.DataArray that has different units as well. As far as I can tell, I haven't found the same behavior with any other unit except degC.

I am using pint-xarray version 0.2.1 on Pangeo Cloud, installed via pip.

As I am very new to this package, I'm not sure where to look for the source of this bug, so any help or input on this would be appreciated!

jthielen commented 2 years ago

While this may be surprising at first, this is actually the expected behavior! Since temperature units like degrees Celsius have an offset (i.e. 0 is not actually 0 in an absolute sense), they are non-multiplicative, or in other words, trying to multiply quantities in those units is not well-defined. To get around this, Pint (at least how it is configured by default in pint-xarray) automatically converts such non-multiplicative units to the corresponding absolute version--hence Kelvin here.

If you're interested in reading more about how these kinds of units work in Pint, I recommend this page of the documentation: https://pint.readthedocs.io/en/stable/nonmult.html

paigem commented 2 years ago

Thanks @jthielen - I see now why this is the expected behavior, and apologies that I didn't see that page in the docs before opening this issue. I'll go ahead and close this issue then!