Astropy units: automatic conversion to the closest human readable unit

Hi,

I’m a contributor of the astropy-affiliated package gammapy, an analysis package for gamma-ray astronomy.
The gamma-ray energy range is open-ended and we use energy units ranging from MeV to PeV energies spanning 9 decades !

In gammapy we use astropy units but can sometime end up with values as E=1.5e6 MeV which is hard to understand from a user point of view. E=1.5 TeV is more readable.

In this gammapy PR, I proposed a helper function to transform :
E = [1.54e2 *u.GeV, 4300 u.keV, 300.6e12 u.eV] (astropy unit list)
=> [‘154 GeV’, ‘4.30 MeV’, ‘301 TeV’] (string representation for label, legends, titles, etc)

Right now, I’m just doing an if/elif test to find the most appropriate unit.
See the full code description here.

Is there already way to do this with astropy ?
Same issue exists with distance units (nm,cm,m, lyr, Mpc, etc) or time.
Would you see a more astropy/pythonic way to do this ?

Thanks for any suggestions you might have,
Fabio

1 Like

I don’t have a better solution; I think this is not bad. It might be useful to have that more general (e.g. length → mirometer, mm, m, km) function in astropy, but I don’t think it exists. Part of that is to figure out what a general algorithm should do, e.g. I use cm, but not ceV.

I’ll open a feature request on the issue tracker for that because I think it’s a good feature that astropy should have - but right now I only get errors from github, so I’ll have to try again later.

A similar feature request was apparently opened in 2017 concerning time and bytes.

I don’t know if it’s worth opening a new one.
Maybe yes as a more general implementation would require more discussion about what unit would be concerned, how to apply this to arrays, and several other aspects.