使用 astropy.units 和自定义转换创建自定义复杂单位

问题描述 投票:0回答:1

我正在处理天文数据,需要使用自定义单位,特别是每球面度的兆扬斯基单位。我想使用 astropy.units 库创建这些自定义单位,并实现一个类似于 astropy .to() 提供的自定义转换函数,该函数将我的像素大小作为参数,以便转换为 Jy/pixel

我使用以下代码实现了自定义转换函数:(参见示例)。 虽然这个解决方案有效,但我发现它有点不优雅。 astropy.units 中是否有更复杂或内置的方法来处理此类转换,同时考虑以弧秒为单位的像素大小?

是否可以使用 astropy.units 定义自定义单位,例如每球面度的 Mega Jansky?如果是这样,您能否提供一个如何在计算中定义和使用它们的示例?

为了清楚起见:我对实现这个自定义单位及其转换参数感兴趣,因为我正在开发一个管道,并且能够在开始时定义测量单位(并不总是相同)将为我节省很多头痛。

from astropy import units as u


class CustomUnitConverter:
    def __init__(self, value, unit):
        self.value = value
        self.unit = unit

    def to(self, target_unit, pixel_size):
        if self.unit == u.MJy / u.steradian and target_unit == u.Jy / u.pixel:
            sr_to_arcsec = 4.25e10  # conversion factor
            conversion_factor = 1e6 / sr_to_arcsec * (pixel_size**2)
            converted_value = self.value * conversion_factor
            return CustomUnitConverter(converted_value, target_unit)
        
        raise u.UnitConversionError(f"Cannot convert {self.unit} to {target_unit}")

# Example
mjy_per_sr = CustomUnitConverter(10.0, u.MJy / u.steradian)
pixel_size_arcsec = 0.25  # dimesion of px in arcsec
jy_per_pixel = mjy_per_sr.to(u.Jy / u.pixel, pixel_size_arcsec)

print(jy_per_pixel.value)
print(jy_per_pixel.unit)
python astropy astronomy
1个回答
0
投票

关注https://docs.astropy.org/en/stable/units/equivalcies.html#writing-new-equivalcies,例如:

from astropy import units as u
pixel_scale = 0.1*u.arcsec
equiv = [(u.MJy/u.sr, u.MJy/u.pixel,
          lambda x: (pixel_scale**2).to(u.sr).value * x,
          lambda x: 1/(pixel_scale**2).to(u.sr).value)]
x = 5*u.MJy/u.sr
x.to(u.Jy/u.pixel, equiv)

这涵盖了单位转换。如果你想要一个自定义单位,你只需要组合它们,例如:

MJySr = u.MJy/u.sr
JyPx = u.Jy/u.pixel
© www.soinside.com 2019 - 2024. All rights reserved.