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

More streamlined unit conversion #48

Open
barneydobson opened this issue Feb 21, 2024 · 0 comments
Open

More streamlined unit conversion #48

barneydobson opened this issue Feb 21, 2024 · 0 comments
Labels
enhancements feature Adding a new functionality, small or large

Comments

@barneydobson
Copy link
Collaborator

From discussion at 31

This might be debatable, but I think unit conversion functions should go on their own and be functions (in their own module), not constant conversion factors:

def m3perh_to_m3pers(value: float) -> float:
    factor = 1 / 60 / 60
    return value * factor

q = m3perh_to_m3pers(tot * pipe_design.precipitation)

This is more readable, easier to re-use and to test.

I have to deal with units in every project, it's so annoying. I found something called quantities. The use case above would be something like:

import quantities
def convert_unit(value: float, from_unit: str, to_unit: str):
   from_unit = quantities.CompoundUnit(from_unit)
   to_unit = quantities.CompoundUnit(to_unit)
   return (value * from_unit).rescale(to_unit).magnitude

# Example
>>> print(convert_unit(1, "m**3/h", "m**3/s"))
0.0002777777777777778 
>>> print(convert_unit([1,2], "m**3/h", "m**3/s"))
[0.00027778 0.00055556]

It's another dependancy, but it's quite a pleasing solution - what do you think? Maybe also cheginit would be interested.

Interestingly it looks like if you had any number implemented as quantities, it would just handle it automatically throughout.

>>> 1 * pq.CompoundUnit("m**3/h") + 0.003 * pq.CompoundUnit("m**3/s") 
array(11.8) * (m**3/h)

I agree that using a functional approach might be better. I think adding a new dependency depends on the frequency of unit conversion in the code. If you think, there will more of such instances, I recommend using something more mature like Pint that supports pandas and xarray.

@barneydobson barneydobson added feature Adding a new functionality, small or large enhancements labels Feb 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancements feature Adding a new functionality, small or large
Projects
None yet
Development

No branches or pull requests

1 participant