Skip to content

Commit d855770

Browse files
authored
fix: writing TProfiles from hist (#1532)
* Fix writing TProfiles from hist * Fix WeightedMean check and avoid warning * Avoid repeated sum computation
1 parent 5a4017f commit d855770

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/uproot/writing/identify.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -269,17 +269,31 @@ def to_writable(obj):
269269
if len(axes) == 1:
270270
if obj.kind == "MEAN":
271271
if hasattr(obj, "storage_type"):
272-
if "fSumw2" in obj.metadata.keys():
272+
obj_sum = obj.sum()
273+
# Use __dir__ instead of hasattr to avoid a warning
274+
if (
275+
"metadata" in obj.__dir__()
276+
and obj.metadata is not None
277+
and "fSumw2" in obj.metadata.keys()
278+
):
273279
fSumw2 = obj.metadata["fSumw2"]
280+
fTsumw = obj_sum["sum_of_weights"]
281+
fTsumw2 = obj_sum["sum_of_weights_squared"]
282+
elif obj.storage_type is boost_histogram.storage.WeightedMean:
283+
fSumw2 = obj.view()["sum_of_weights_squared"]
284+
fTsumw = obj_sum["sum_of_weights"]
285+
fTsumw2 = obj_sum["sum_of_weights_squared"]
274286
else:
275-
raise ValueError(f"fSumw2 has not been set for {obj}")
287+
fSumw2 = obj.view()["count"]
288+
fTsumw = obj_sum["count"]
289+
fTsumw2 = obj_sum["count"]
276290
return to_TProfile(
277291
fName=None,
278292
fTitle=title,
279293
data=obj.values(flow=True),
280294
fEntries=obj.size + 1,
281-
fTsumw=obj.sum()["sum_of_weights"],
282-
fTsumw2=obj.sum()["sum_of_weights_squared"],
295+
fTsumw=fTsumw,
296+
fTsumw2=fTsumw2,
283297
fTsumwx=0,
284298
fTsumwx2=0,
285299
fTsumwy=0,

0 commit comments

Comments
 (0)