Belle II Software development
hist_utils.py
1#!/usr/bin/env python3
2
3
10
11import numpy as np
12
13
14def hist2array(hist, return_edges=False):
15 """
16 Function to convert a histogram into a numpy array and optionally also
17 return a list of the bin edges
18 Parameters:
19 hist: one-dimensional histogram
20 return_edges (bool): flag whether bin edges should be calculated and returned
21 Return:
22 numpy array and optionally a list of the bin edges
23 """
24 nbins = hist.GetNbinsX()
25 arr = np.zeros(nbins)
26 for i in range(nbins):
27 arr[i] = hist.GetBinContent(i + 1)
28 if return_edges:
29 edges = []
30 edges.append(np.empty(nbins + 1))
31 hist.GetXaxis().GetLowEdge(edges[-1])
32 edges[-1][nbins] = hist.GetXaxis().GetBinUpEdge(nbins)
33 return arr, edges
34 return arr
35
36
37def array2hist(array, hist):
38 """
39 Function to fill a histogram from an array
40 Parameters:
41 array: array
42 hist: histogram
43 """
44 ndim = array.ndim
45 if ndim == 1:
46 nbins = len(array)
47 for i in range(nbins):
48 hist.SetBinContent(i + 1, array[i])
49 elif ndim == 2:
50 for i in range(hist.GetNbinsX()):
51 for j in range(hist.GetNbinsY()):
52 hist.SetBinContent(i + 1, j + 1, array[i, j])