'python pint: defined offset unit definition behaves unexpected on conversion
I'm trying to define gauge pressure (barg) as an offset unit using python/pint assuming the predefined unit (bar) refers to absolute pressure. When using the defined unit to set up a quantity in 'barg' and convert it to 'bar' there is an unexpected factor of 1e-8 in the magnitude. Implying this factor in the unit definition solves the issue but is somehow not satisfactory. Here is a minimal example:
import pint
ureg = pint.UnitRegistry()
ureg.define('barg = bar; offset: 1')
ureg.define('barg_corr = 1e8*bar; offset: 1e8')
Q_ = ureg.Quantity
press_barg = Q_(1,'barg')
press_bar = press_barg.to('bar')
print(press_bar)
press_barg = Q_(1,'barg_corr')
press_bar = press_barg.to('bar')
print(press_bar)
Investigating further yielded that it might be due to an internal conversion to base units which can be handled by
ureg = pint.UnitRegistry(autoconvert_offset_to_baseunit=False)
However, switching this option to True (default = False) does not change the behaviour at all.
I am using python 3.8 with pint 0.18 here.
So my questions are:
- Am I doing it the right way, i.e., should it work as I think it should?
- Does anyone have an idea, whats going on?
Thanks in advance and best regards, M
Solution 1:[1]
I think I find where the matter comes from (but I don't know how to correct it).
The autoconvert_offset_to_baseunit seems to be a false lead, it doesn't seem to be used during conversion (but I can be wrong).
In the _convert function from NonMultiplicativeRegistry class, I find this part:
# clean src from offset units by converting to reference
if src_offset_unit:
value = self._units[src_offset_unit].converter.to_reference(value, inplace)
src = src.remove([src_offset_unit])
# Add reference unit for multiplicative section
src = self._add_ref_of_log_unit(src_offset_unit, src)
If I comment the line src = src.remove([src_offset_unit]) the result is correct.
Why?
When removing the unit, the code change src from "barg" to "dimensionless". This change leads to a wrong factor computation in _convert function from BaseRegistry class (10e8 instead of 1).
But I don't have further information about the need of this line I commented, I am almost sure there is one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ndclt |
