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

Check dimensions in given context #1951

Open
khansson opened this issue Mar 8, 2024 · 1 comment
Open

Check dimensions in given context #1951

khansson opened this issue Mar 8, 2024 · 1 comment

Comments

@khansson
Copy link

khansson commented Mar 8, 2024

I have a function which needs to use a quantity that can energy units. I can check that the units are correct using check

import pint
ureg = pint.UnitRegistry()
q = 500 * ureg.eV
q.check('[energy]') #returns True

this is all good. However, I have some data coming in as cm^-1 or cm_1 in pint. This will not work.

import pint
ureg = pint.UnitRegistry()
q = 500 * ureg.cm_1
q.check('[energy]') #returns False

However, it will also not work in a context

import pint
ureg = pint.UnitRegistry()
q = 500 * ureg.cm_1
with ureg.context('sp'):
     q.check('[energy]') #returns False

I can use is_compatible_with but not with a dimension (i.e. I can do q.is_compatible_with('eV') not q.is_compatible_with('[energy]'))

I am not sure this is a design decision or not, or if there is a more correct way of going about this. Otherwise, it would be great if this capability were added.

@khansson
Copy link
Author

khansson commented Mar 8, 2024

I made a function that more or less works, but is not very elegant

def check_dimensions(registry : pint.UnitRegistry,  src :QuantityOrUnitLike, dimensions : UnitLike, *contexts , **ctx_kwargs):
    if contexts:
        src_dim = registry.get_dimensionality(src)
        dst_dim = registry.get_dimensionality(dimensions)
        with registry.context(*contexts, **ctx_kwargs):
            path = find_shortest_path(registry._active_ctx.graph, src_dim, dst_dim)
            return bool(path)
    elif registry._active_ctx:
        src_dim = registry.get_dimensionality(src)
        dst_dim = registry.get_dimensionality(dimensions)
        path = find_shortest_path(registry._active_ctx.graph, src_dim, dst_dim)
        return bool(path)  
    return src.check(dimensions)

ideally this would be a member function of the UnitRegistry?

BTW this works with 0.22, the master branch has the function _get_conversion_factor which may be better, or at least simpler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant