Belle II Software  light-2303-iriomote
hist_utils.py
1 #!/usr/bin/env python3
2 
3 
10 
11 import numpy as np
12 
13 
14 def 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.GetLowEdge(edges[-1])
32  return arr, edges
33  return arr
34 
35 
36 def array2hist(array, hist):
37  """
38  Function to fill a histogram from an array
39  Parameters:
40  array: array
41  hist: histogram
42  """
43  ndim = array.ndim
44  if ndim == 1:
45  nbins = len(array)
46  for i in range(nbins):
47  hist.SetBinContent(i + 1, array[i])
48  elif ndim == 2:
49  for i in range(hist.GetNbinsX()):
50  for j in range(hist.GetNbinsY()):
51  hist.SetBinContent(i + 1, j + 1, array[i, j])