我想在hdf5属性中存储一个令人费解的Quantity
。
此刻我正在做什么:
from astropy import units
import h5py
length_1 = 5.3 * units.meter
# -- Write attribute ----------
with h5py.File("./temp.hdf5", "w") as data:
# write value
data.attrs.create("length", length_1.value)
# write unit
data.attrs.create("lengthUnit", length_1.unit.to_string())
# -- Read attribute -----------
with h5py.File("./temp.hdf5", "r") as data:
# read value
lengthValue = data.attrs["length"]
# read unit
lengthUnit = data.attrs["lengthUnit"]
# recreate length as Quantity
length_2 = lengthValue * units.Unit(lengthUnit)
但是,如我在这里所做的那样,如果我可以修改AttributeManager
的getter / setter流程以处理任何Quantity
会很有帮助。
例如。
class QuantityAttributeManager(h5py.AttributeManager):
def __init__(self, parent):
super().__init__(parent)
# __setitem__ uses create
def create(self, name, data, shape=None, dtype=None):
if isinstance(data, units.Quantity):
super().create(
name,
data.value
)
super().create(
"{:s}Unit".format(name),
data.unit.to_string().encode("utf-8")
)
else:
super().create(name, data, shape, dtype)
# def __getitem__
# [...]
with h5py.File("./temp.hdf5", "w") as data:
# really this should be:
# data.attrs["length"] = length
# and this is where the problem lies
attr = QuantityAttributeManager(data["/"])
attr["length"] = length_1
print(list(attr.keys())) # ['length', 'lengthUnit']
.attrs
属性定义为([source])
@property
def attrs(self):
""" Attributes attached to this object """
from . import attrs
with phil:
return attrs.AttributeManager(self)
在HLObject
和Dataset
继承的Group
中
我看到的最好的选择是将from . import attrs
行重定向为使用QuantityAttributeManager
,但是我不确定如何。
(最好不要太客气。)
答案 0 :(得分:0)
一种可行的解决方案可能是猴子补丁,但随后将始终使用新的属性管理器。
h5py._hl.attrs.AttributeManager = QuantityAttributeManager
with h5py.File("./temp.hdf5", "w") as data:
data.attrs["length"] = length
print(list(data.attrs.keys())) # ['length', 'lengthUnit']