pint icon indicating copy to clipboard operation
pint copied to clipboard

Parametrized unit redefinition in context

Open BenjaminMidtvedt opened this issue 2 years ago • 3 comments

Hi! I have a system where it's natural to have several length-like units, for which the conversion to meters is defined by the parameters of the system. I set up a definition as follows (though with many more units):

myunit = nan meter
@context(factor=1) mycontext
    myunit = factor * 1 meter
@end

which gives a DefinitionSyntaxError: Context parameters {'factor'} not found in any equation.

I'm presuming the context parameters are only implemented for conversions between dimensionalities. However, in this case, that approach isn't desirable since each of my units would need a unique dimensionality when they are all lengths.

Would it be possible to extend the use of context parameters to unit redefinitions?

BenjaminMidtvedt avatar Jul 11 '22 15:07 BenjaminMidtvedt

Indeed, contexts are used to implement conversions between dimensionality, and it is not possible to use them for redefinitions. Can you comment more about your use case?

hgrecco avatar Jul 13 '22 22:07 hgrecco

I'm trying to do something similar, but it seems the context parameter is only used for dimension transformations, and isn't passed to unit conversions.

@hgrecco I am a bit confused, the docs describe how to use contexts for redefinitions: https://pint.readthedocs.io/en/stable/contexts.html#using-contexts-for-unit-redefinition Or do you just mean this sort of parameterisation can't be used for redefinitions?

ZedThree avatar Aug 30 '22 15:08 ZedThree

My use case was defining units such as pixels in optical systems / video microscopy. The length scale a pixel represents will depend on physical parameters of the optical device. As such, it felt natural to create a context that takes those parameters to define the conversion between meters and pixels.

In the end, I settled on defining a function that creates a new context with the correct conversions from scratch wherever necessary. It's not as pretty or user-friendly as a parametrized unit redefinition, but it is sufficient for my needs.

BenjaminMidtvedt avatar Aug 30 '22 21:08 BenjaminMidtvedt