root_numpy/_hist.py
def array2hist(array, hist, errors=None):
    """Convert a NumPy array into a ROOT histogram

    Parameters
    ----------
    array : numpy array
        A 1, 2, or 3-d numpy array that will set the bin contents of the
        ROOT histogram.
    hist : ROOT TH1, TH2, or TH3
        A ROOT histogram.
    errors : numpy array
        A numpy array of errors with matching dimensionality as the
        bin contents array. If not given, no errors are set

    Returns
    -------
    hist : ROOT TH1, TH2, or TH3
        The ROOT histogram with bin contents set from the array.

    Raises
    ------
    TypeError
        If hist is not a ROOT histogram.
    ValueError
        If the array and histogram are not compatible in terms of
        dimensionality or number of bins along any axis.

    Notes
    -----
    The NumPy array is copied into the histogram's internal array. If the input
    NumPy array is not of the same data type as the histogram bin contents
    (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow
    bins along any of the axes, an additional copy is made into a temporary
    array with all values converted into the matching data type and with
    overflow bins included. Avoid this second copy by ensuring that the NumPy
    array data type matches the histogram data type and that overflow bins are
    included.

    See Also
    --------
    hist2array

    Examples
    --------

    >>> from root_numpy import array2hist, hist2array
    >>> import numpy as np
    >>> from rootpy.plotting import Hist2D
    >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F')
    >>> array = np.random.randint(0, 10, size=(7, 5))
    >>> array
    array([[6, 7, 8, 3, 4],
           [8, 9, 7, 6, 2],
           [2, 3, 4, 5, 2],
           [7, 6, 5, 7, 3],
           [2, 0, 5, 6, 8],
           [0, 0, 6, 5, 2],
           [2, 2, 1, 5, 4]])
    >>> _ = array2hist(array, hist)
    >>> # dtype matches histogram type (D, F, I, S, C)
    >>> hist2array(hist)
    array([[ 9.,  7.,  6.],
           [ 3.,  4.,  5.],
           [ 6.,  5.,  7.],
           [ 0.,  5.,  6.],
           [ 0.,  6.,  5.]], dtype=float32)
    >>> # overflow is excluded by default
    >>> hist2array(hist, include_overflow=True)
    array([[ 6.,  7.,  8.,  3.,  4.],
           [ 8.,  9.,  7.,  6.,  2.],
           [ 2.,  3.,  4.,  5.,  2.],
           [ 7.,  6.,  5.,  7.,  3.],
           [ 2.,  0.,  5.,  6.,  8.],
           [ 0.,  0.,  6.,  5.,  2.],
           [ 2.,  2.,  1.,  5.,  4.]], dtype=float32)
    >>> array2 = hist2array(hist, include_overflow=True, copy=False)
    >>> hist[2, 2] = -10
    >>> # array2 views the same memory as hist because copy=False
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10.,   5.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)
    >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy
    >>> hist[2, 3] = -10
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10., -10.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)

    """
    import ROOT
    if isinstance(hist, ROOT.TH3):
        shape = (hist.GetNbinsX() + 2,
                 hist.GetNbinsY() + 2,
                 hist.GetNbinsZ() + 2)
    elif isinstance(hist, ROOT.TH2):
        shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2)
    elif isinstance(hist, ROOT.TH1):
        shape = (hist.GetNbinsX() + 2,)
    else:
        raise TypeError(
            "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3")

    # Determine the corresponding numpy dtype
    for hist_type in 'DFISC':
        if isinstance(hist, getattr(ROOT, 'TArray{0}'.format(hist_type))):
            break
    else:
        raise AssertionError(
            "hist is somehow an instance of TH[1|2|3] "
            "but not TArray[D|F|I|S|C]")

    # Constuct a NumPy array viewing the underlying histogram array
    dtype = np.dtype(DTYPE_ROOT2NUMPY[hist_type])
    # No copy is made if the dtype is the same as input
    _array = np.ascontiguousarray(array, dtype=dtype)
    if errors is not None:
        if errors.shape != array.shape:
            raise ValueError("Contents and errors are not compatible")
        # errors are specified as doubles in SetError function
        _errors = np.ascontiguousarray(errors, dtype=np.float64)
    else:
        _errors = None

    if _array.ndim != len(shape):
        raise ValueError(
            "array and histogram do not have "
            "the same number of dimensions")
    if _array.shape != shape:
        # Check for overflow along each axis
        slices = []
        for axis, bins in enumerate(shape):
            if _array.shape[axis] == bins - 2:
                slices.append(slice(1, -1))
            elif _array.shape[axis] == bins:
                slices.append(slice(None))
            else:
                raise ValueError(
                    "array and histogram are not compatible along "
                    "the {0}-axis".format("xyz"[axis]))
        array_overflow = np.zeros(shape, dtype=dtype)
        array_overflow[tuple(slices)] = _array
        _array = array_overflow

        if _errors is not None:
            errors_overflow = np.zeros(shape, dtype=np.float64)
            errors_overflow[tuple(slices)] = _errors
            _errors = errors_overflow

    ARRAY_NUMPY2ROOT[len(shape)][hist_type](
        ROOT.AsCObject(hist), np.ravel(np.transpose(_array)))
    # Set the number of entries to the number of array elements
    hist.SetEntries(_array.size)
    if _errors is not None:
        hist.SetError(np.ravel(_errors.T))
    return hist
Convert a NumPy array into a ROOT histogram

    Parameters
    ----------
    array : numpy array
        A 1, 2, or 3-d numpy array that will set the bin contents of the
        ROOT histogram.
    hist : ROOT TH1, TH2, or TH3
        A ROOT histogram.
    errors : numpy array
        A numpy array of errors with matching dimensionality as the
        bin contents array. If not given, no errors are set

    Returns
    -------
    hist : ROOT TH1, TH2, or TH3
        The ROOT histogram with bin contents set from the array.

    Raises
    ------
    TypeError
        If hist is not a ROOT histogram.
    ValueError
        If the array and histogram are not compatible in terms of
        dimensionality or number of bins along any axis.

    Notes
    -----
    The NumPy array is copied into the histogram's internal array. If the input
    NumPy array is not of the same data type as the histogram bin contents
    (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow
    bins along any of the axes, an additional copy is made into a temporary
    array with all values converted into the matching data type and with
    overflow bins included. Avoid this second copy by ensuring that the NumPy
    array data type matches the histogram data type and that overflow bins are
    included.

    See Also
    --------
    hist2array

    Examples
    --------

    >>> from root_numpy import array2hist, hist2array
    >>> import numpy as np
    >>> from rootpy.plotting import Hist2D
    >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F')
    >>> array = np.random.randint(0, 10, size=(7, 5))
    >>> array
    array([[6, 7, 8, 3, 4],
           [8, 9, 7, 6, 2],
           [2, 3, 4, 5, 2],
           [7, 6, 5, 7, 3],
           [2, 0, 5, 6, 8],
           [0, 0, 6, 5, 2],
           [2, 2, 1, 5, 4]])
    >>> _ = array2hist(array, hist)
    >>> # dtype matches histogram type (D, F, I, S, C)
    >>> hist2array(hist)
    array([[ 9.,  7.,  6.],
           [ 3.,  4.,  5.],
           [ 6.,  5.,  7.],
           [ 0.,  5.,  6.],
           [ 0.,  6.,  5.]], dtype=float32)
    >>> # overflow is excluded by default
    >>> hist2array(hist, include_overflow=True)
    array([[ 6.,  7.,  8.,  3.,  4.],
           [ 8.,  9.,  7.,  6.,  2.],
           [ 2.,  3.,  4.,  5.,  2.],
           [ 7.,  6.,  5.,  7.,  3.],
           [ 2.,  0.,  5.,  6.,  8.],
           [ 0.,  0.,  6.,  5.,  2.],
           [ 2.,  2.,  1.,  5.,  4.]], dtype=float32)
    >>> array2 = hist2array(hist, include_overflow=True, copy=False)
    >>> hist[2, 2] = -10
    >>> # array2 views the same memory as hist because copy=False
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10.,   5.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)
    >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy
    >>> hist[2, 3] = -10
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10., -10.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)

    
Convert a NumPy array into a ROOT histogram
Parameters

array : numpy array
A 1, 2, or 3-d numpy array that will set the bin contents of the
ROOT histogram.
hist : ROOT TH1, TH2, or TH3
A ROOT histogram.
errors : numpy array
A numpy array of errors with matching dimensionality as the
bin contents array. If not given, no errors are set

Returns

hist : ROOT TH1, TH2, or TH3
The ROOT histogram with bin contents set from the array.

Raises

TypeError
If hist is not a ROOT histogram.
ValueError
If the array and histogram are not compatible in terms of
dimensionality or number of bins along any axis.

Notes

The NumPy array is copied into the histogram's internal array. If the input
NumPy array is not of the same data type as the histogram bin contents
and/or the input array does not contain overflow
bins along any of the axes, an additional copy is made into a temporary
array with all values converted into the matching data type and with
overflow bins included. Avoid this second copy by ensuring that the NumPy
array data type matches the histogram data type and that overflow bins are
included.

See Also

hist2array

Examples


Convert a NumPy array into a ROOT histogram Parameters array : numpy array A 1 2 or 3 - d numpy array that will set the bin contents of the ROOT histogram . hist : ROOT TH1 TH2 or TH3 A ROOT histogram . errors : numpy array A numpy array of errors with matching dimensionality as the bin contents array . If not given no errors are set Returns hist : ROOT TH1 TH2 or TH3 The ROOT histogram with bin contents set from the array . Raises TypeError If hist is not a ROOT histogram . ValueError If the array and histogram are not compatible in terms of dimensionality or number of bins along any axis . Notes The NumPy array is copied into the histogram ' s internal array . If the input NumPy array is not of the same data type as the histogram bin contents and / or the input array does not contain overflow bins along any of the axes an additional copy is made into a temporary array with all values converted into the matching data type and with overflow bins included . Avoid this second copy by ensuring that the NumPy array data type matches the histogram data type and that overflow bins are included . See Also hist2array Examples
def array2hist(array, hist, errors=None):
    import ROOT
    if isinstance(hist, ROOT.TH3):
        shape = (hist.GetNbinsX() + 2,
                 hist.GetNbinsY() + 2,
                 hist.GetNbinsZ() + 2)
    elif isinstance(hist, ROOT.TH2):
        shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2)
    elif isinstance(hist, ROOT.TH1):
        shape = (hist.GetNbinsX() + 2,)
    else:
        raise TypeError(
            "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3")
    for hist_type in 'DFISC':
        if isinstance(hist, getattr(ROOT, 'TArray{0}'.format(hist_type))):
            break
    else:
        raise AssertionError(
            "hist is somehow an instance of TH[1|2|3] "
            "but not TArray[D|F|I|S|C]")
    dtype = np.dtype(DTYPE_ROOT2NUMPY[hist_type])
    _array = np.ascontiguousarray(array, dtype=dtype)
    if errors is not None:
        if errors.shape != array.shape:
            raise ValueError("Contents and errors are not compatible")
        _errors = np.ascontiguousarray(errors, dtype=np.float64)
    else:
        _errors = None
    if _array.ndim != len(shape):
        raise ValueError(
            "array and histogram do not have "
            "the same number of dimensions")
    if _array.shape != shape:
        slices = []
        for axis, bins in enumerate(shape):
            if _array.shape[axis] == bins - 2:
                slices.append(slice(1, -1))
            elif _array.shape[axis] == bins:
                slices.append(slice(None))
            else:
                raise ValueError(
                    "array and histogram are not compatible along "
                    "the {0}-axis".format("xyz"[axis]))
        array_overflow = np.zeros(shape, dtype=dtype)
        array_overflow[tuple(slices)] = _array
        _array = array_overflow
        if _errors is not None:
            errors_overflow = np.zeros(shape, dtype=np.float64)
            errors_overflow[tuple(slices)] = _errors
            _errors = errors_overflow
    ARRAY_NUMPY2ROOT[len(shape)][hist_type](
        ROOT.AsCObject(hist), np.ravel(np.transpose(_array)))
    hist.SetEntries(_array.size)
    if _errors is not None:
        hist.SetError(np.ravel(_errors.T))
    return hist
def array2hist ( array , hist , errors = None ) : import ROOT if isinstance ( hist , ROOT . TH3 ) : shape = ( hist . GetNbinsX ( ) + 2 , hist . GetNbinsY ( ) + 2 , hist . GetNbinsZ ( ) + 2 ) elif isinstance ( hist , ROOT . TH2 ) : shape = ( hist . GetNbinsX ( ) + 2 , hist . GetNbinsY ( ) + 2 ) elif isinstance ( hist , ROOT . TH1 ) : shape = ( hist . GetNbinsX ( ) + 2 , ) else : raise TypeError ( "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3" ) for hist_type in 'DFISC' : if isinstance ( hist , getattr ( ROOT , 'TArray{0}' . format ( hist_type ) ) ) : break else : raise AssertionError ( "hist is somehow an instance of TH[1|2|3] " "but not TArray[D|F|I|S|C]" ) dtype = np . dtype ( DTYPE_ROOT2NUMPY [ hist_type ] ) _array = np . ascontiguousarray ( array , dtype = dtype ) if errors is not None : if errors . shape != array . shape : raise ValueError ( "Contents and errors are not compatible" ) _errors = np . ascontiguousarray ( errors , dtype = np . float64 ) else : _errors = None if _array . ndim != len ( shape ) : raise ValueError ( "array and histogram do not have " "the same number of dimensions" ) if _array . shape != shape : slices = [ ] for axis , bins in enumerate ( shape ) : if _array . shape [ axis ] == bins - 2 : slices . append ( slice ( 1 , - 1 ) ) elif _array . shape [ axis ] == bins : slices . append ( slice ( None ) ) else : raise ValueError ( "array and histogram are not compatible along " "the {0}-axis" . format ( "xyz" [ axis ] ) ) array_overflow = np . zeros ( shape , dtype = dtype ) array_overflow [ tuple ( slices ) ] = _array _array = array_overflow if _errors is not None : errors_overflow = np . zeros ( shape , dtype = np . float64 ) errors_overflow [ tuple ( slices ) ] = _errors _errors = errors_overflow ARRAY_NUMPY2ROOT [ len ( shape ) ] [ hist_type ] ( ROOT . AsCObject ( hist ) , np . ravel ( np . transpose ( _array ) ) ) hist . SetEntries ( _array . size ) if _errors is not None : hist . SetError ( np . ravel ( _errors . T ) ) return hist
Convert a NumPy array into a ROOT histogram
Parameters
Convert a NumPy array into a ROOT histogram Parameters
"""Convert a NumPy array into a ROOT histogram

    Parameters
    ----------
    array : numpy array
        A 1, 2, or 3-d numpy array that will set the bin contents of the
        ROOT histogram.
    hist : ROOT TH1, TH2, or TH3
        A ROOT histogram.
    errors : numpy array
        A numpy array of errors with matching dimensionality as the
        bin contents array. If not given, no errors are set

    Returns
    -------
    hist : ROOT TH1, TH2, or TH3
        The ROOT histogram with bin contents set from the array.

    Raises
    ------
    TypeError
        If hist is not a ROOT histogram.
    ValueError
        If the array and histogram are not compatible in terms of
        dimensionality or number of bins along any axis.

    Notes
    -----
    The NumPy array is copied into the histogram's internal array. If the input
    NumPy array is not of the same data type as the histogram bin contents
    (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow
    bins along any of the axes, an additional copy is made into a temporary
    array with all values converted into the matching data type and with
    overflow bins included. Avoid this second copy by ensuring that the NumPy
    array data type matches the histogram data type and that overflow bins are
    included.

    See Also
    --------
    hist2array

    Examples
    --------

    >>> from root_numpy import array2hist, hist2array
    >>> import numpy as np
    >>> from rootpy.plotting import Hist2D
    >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F')
    >>> array = np.random.randint(0, 10, size=(7, 5))
    >>> array
    array([[6, 7, 8, 3, 4],
           [8, 9, 7, 6, 2],
           [2, 3, 4, 5, 2],
           [7, 6, 5, 7, 3],
           [2, 0, 5, 6, 8],
           [0, 0, 6, 5, 2],
           [2, 2, 1, 5, 4]])
    >>> _ = array2hist(array, hist)
    >>> # dtype matches histogram type (D, F, I, S, C)
    >>> hist2array(hist)
    array([[ 9.,  7.,  6.],
           [ 3.,  4.,  5.],
           [ 6.,  5.,  7.],
           [ 0.,  5.,  6.],
           [ 0.,  6.,  5.]], dtype=float32)
    >>> # overflow is excluded by default
    >>> hist2array(hist, include_overflow=True)
    array([[ 6.,  7.,  8.,  3.,  4.],
           [ 8.,  9.,  7.,  6.,  2.],
           [ 2.,  3.,  4.,  5.,  2.],
           [ 7.,  6.,  5.,  7.,  3.],
           [ 2.,  0.,  5.,  6.,  8.],
           [ 0.,  0.,  6.,  5.,  2.],
           [ 2.,  2.,  1.,  5.,  4.]], dtype=float32)
    >>> array2 = hist2array(hist, include_overflow=True, copy=False)
    >>> hist[2, 2] = -10
    >>> # array2 views the same memory as hist because copy=False
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10.,   5.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)
    >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy
    >>> hist[2, 3] = -10
    >>> array2
    array([[  6.,   7.,   8.,   3.,   4.],
           [  8.,   9.,   7.,   6.,   2.],
           [  2.,   3., -10., -10.,   2.],
           [  7.,   6.,   5.,   7.,   3.],
           [  2.,   0.,   5.,   6.,   8.],
           [  0.,   0.,   6.,   5.,   2.],
           [  2.,   2.,   1.,   5.,   4.]], dtype=float32)

    """ # Determine the corresponding numpy dtype # Constuct a NumPy array viewing the underlying histogram array # No copy is made if the dtype is the same as input # errors are specified as doubles in SetError function # Check for overflow along each axis # Set the number of entries to the number of array elements
array
hist
errors