Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions bindings/pyroot/pythonizations/python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ if(roofit)
ROOT/_pythonization/_roofit/_utils.py)
endif()

if(root7)
list(APPEND PYROOT_EXTRA_PYTHON_SOURCES
ROOT/_pythonization/_histv7.py)
endif()

if(tmva)
list(APPEND PYROOT_EXTRA_PYTHON_SOURCES
ROOT/_pythonization/_tmva/_crossvalidation.py
Expand Down
219 changes: 219 additions & 0 deletions bindings/pyroot/pythonizations/python/ROOT/_pythonization/_histv7.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
from . import pythonization


def _is_RBinIndex(index):
return hasattr(type(index), "__cpp_name__") and type(index).__cpp_name__ == "ROOT::Experimental::RBinIndex"


def _is_index(index):
import ROOT

# TODO: implement support for loc
return isinstance(index, int) or _is_RBinIndex(index) or index == ROOT.uhi.underflow or index == ROOT.uhi.overflow


def _is_tuple_of_indices(indices):
return all([_is_index(i) for i in indices])


def _translate_index(index):
"""Translate a single Python index into an RBinIndex."""
import ROOT

# TODO: implement support for loc

if isinstance(index, int):
return ROOT.Experimental.RBinIndex(index)
elif _is_RBinIndex(index):
return index
elif index == ROOT.uhi.underflow:
return ROOT.Experimental.RBinIndex.Underflow()
elif index == ROOT.uhi.overflow:
return ROOT.Experimental.RBinIndex.Overflow()
else:
raise TypeError(f"unsupported index type: {type(index).__name__}")


def _translate_indices(self, indices):
"""Translate a tuple of Python indices into a std::vector<RBinIndex>."""
if len(indices) != self.GetNDimensions():
raise IndexError(f"invalid number of indices: expected {self.GetNDimensions()}, but got {len(indices)}")

import ROOT

axes = self.GetAxes()
vec = ROOT.std.vector["ROOT::Experimental::RBinIndex"]()
for i, index in enumerate(indices):
binIndex = _translate_index(index)
if not axes[i].IsValidIndex(binIndex):
raise IndexError(f"invalid bin index for axis {i}: {index}")
vec.push_back(binIndex)
return vec


def _ensure_tuple(arg):
"""Ensure that the passed Python argument is wrapped in a tuple."""
return (arg,) if not isinstance(arg, tuple) else arg


def _expand_slices(slices, ndim):
"""Expand user argument into a tuple of Python slices."""
if isinstance(slices, dict):
# A dictionary sets the slice operation for a subset of the axes
expanded = [slice(None)] * ndim
for axis, value in slices.items():
if not isinstance(axis, int):
raise IndexError("keys of dictionary must be integers")
if axis >= ndim:
raise IndexError(f"invalid axis key: {axis}")
expanded[axis] = value
return tuple(expanded)

slices = _ensure_tuple(slices)

if ... not in slices:
return slices

if slices.count(...) > 1:
raise IndexError("more than one ellipsis found")

pos = slices.index(...)
return slices[:pos] + (slice(None),) * (ndim - len(slices) + 1) + slices[pos + 1 :]


def _is_operation(op):
import ROOT

return isinstance(op, ROOT.uhi.rebin) or op == ROOT.uhi.sum or op == sum


def _translate_operation(op):
"""Translate a single Python "object" representing an operation into an object for RSliceSpec."""
import ROOT

if isinstance(op, ROOT.uhi.rebin):
return ROOT.Experimental.RSliceSpec.ROperationRebin(op.ngroup)
elif op == ROOT.uhi.sum or op == sum:
return ROOT.Experimental.RSliceSpec.ROperationSum()
else:
raise TypeError(f"unsupported operation type: {type(op).__name__}")


def _translate_slice(self, i, axis, s):
"""Translate a single Python slice into an RSliceSpec."""
import ROOT

RSliceSpec = ROOT.Experimental.RSliceSpec

if _is_index(s):
index = _translate_index(s)
if not axis.IsValidIndex(index):
raise IndexError(f"invalid bin index for axis {i}: {s}")
if not index.IsNormal():
raise IndexError("normal bin required in slicing")

# A single value v is like v:v+1:sum
r = axis.GetNormalRange(index, index + 1)
return RSliceSpec(r, RSliceSpec.ROperationSum())

elif _is_operation(s):
operation = _translate_operation(s)
return RSliceSpec(operation)

elif isinstance(s, slice):
begin = None
if s.start is not None:
begin = _translate_index(s.start)
if not begin.IsNormal():
raise IndexError("normal bin required in slicing")

end = None
if s.stop is not None:
if s.stop == len:
end = ROOT.Experimental.RBinIndex(axis.GetNNormalBins())
else:
end = _translate_index(s.stop)
if not end.IsNormal():
raise IndexError("normal bin required in slicing")

operation = None
if s.step is not None:
operation = _translate_operation(s.step)

if begin is None and end is None:
if operation is None:
return RSliceSpec()
else:
return RSliceSpec(operation)

# At least one endpoint is given.
elif operation is not None and type(operation).__cpp_name__ == "ROOT::Experimental::RSliceSpec::ROperationSum":
# For sums it makes a difference whether flow bins are included. If only one endpoint is given, we cannot guess.
if begin is None or end is None:
raise IndexError("either none or both endpoints required for sum")

r = axis.GetNormalRange(begin, end)
return RSliceSpec(r, operation)

# For other slice operations, it does not make a difference whether the range includes the flow bins.
elif begin is None:
begin = ROOT.Experimental.RBinIndex(0)
elif end is None:
end = ROOT.Experimental.RBinIndex(axis.GetNNormalBins())

r = axis.GetNormalRange(begin, end)
if operation is None:
return RSliceSpec(r)
else:
return RSliceSpec(r, operation)

else:
raise TypeError(f"unsupported index type: {type(s).__name__}")


def _translate_slices(self, slices):
"""Translate a tuple of Python slices into a std::vector<RSliceSpec>."""
slices = _expand_slices(slices, self.GetNDimensions())

if len(slices) != self.GetNDimensions():
raise IndexError(f"invalid number of slices: expected {self.GetNDimensions()}, but got {len(slices)}")

import ROOT

axes = self.GetAxes()
vec = ROOT.std.vector["ROOT::Experimental::RSliceSpec"]()
for i, s in enumerate(slices):
sliceSpec = _translate_slice(self, i, axes[i], s)
vec.push_back(sliceSpec)
return vec


def _getitem(self, index):
if not isinstance(index, dict):
indices = _ensure_tuple(index)
if _is_tuple_of_indices(indices):
indices = _translate_indices(self, indices)
return self.GetBinContent(indices)

slices = _translate_slices(self, index)
return self.Slice(slices)


def _setitem(self, index, value):
indices = _ensure_tuple(index)
if not _is_tuple_of_indices(indices):
raise ValueError("could not convert indices")
indices = _translate_indices(self, indices)
self.SetBinContent(indices, value)


@pythonization("RHistEngine<", ns="ROOT::Experimental", is_prefix=True)
def pythonize_engine(klass):
klass.__getitem__ = _getitem
klass.__setitem__ = _setitem


@pythonization("RHist<", ns="ROOT::Experimental", is_prefix=True)
def pythonize_hist(klass):
klass.__getitem__ = _getitem
klass.__setitem__ = _setitem
17 changes: 17 additions & 0 deletions hist/histv7/inc/ROOT/RAxisVariant.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "RBinIndex.hxx"
#include "RBinIndexRange.hxx"
#include "RCategoricalAxis.hxx"
#include "RLinearizedIndex.hxx"
#include "RRegularAxis.hxx"
#include "RSliceSpec.hxx"
#include "RVariableBinAxis.hxx"
Expand Down Expand Up @@ -78,6 +79,22 @@ public:
}
}

/// \return true if the bin index is valid
bool IsValidIndex(RBinIndex index) const
{
RLinearizedIndex linIndex;
if (auto *regular = GetRegularAxis()) {
linIndex = regular->GetLinearizedIndex(index);
} else if (auto *variable = GetVariableBinAxis()) {
linIndex = variable->GetLinearizedIndex(index);
} else if (auto *categorical = GetCategoricalAxis()) {
linIndex = categorical->GetLinearizedIndex(index);
} else {
throw std::logic_error("unimplemented axis type"); // GCOVR_EXCL_LINE
}
return linIndex.fValid;
}

/// Get the range of all normal bins.
///
/// \return the bin index range from the first to the last normal bin, inclusive
Expand Down
33 changes: 31 additions & 2 deletions hist/histv7/inc/ROOT/RHist.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,34 @@ public:
fStats.Taint();
}

/// Set the content of a single bin.
///
/// \code
/// ROOT::Experimental::RHist<int> hist({/* two dimensions */});
/// std::vector<ROOT::Experimental::RBinIndex> indices = {3, 5};
/// int value = /* ... */;
/// hist.SetBinContent(indices, value);
/// \endcode
///
/// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
/// values. See also the class documentation of RBinIndex.
///
/// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
///
/// \warning Setting the bin content will taint the global histogram statistics. Attempting to access its values, for
/// example calling GetNEntries(), will throw exceptions.
///
/// \param[in] indices the vector of indices for each axis
/// \param[in] value the new value of the bin content
/// \par See also
/// the \ref SetBinContent(const A &... args) "variadic function template overload" accepting arguments directly
template <typename V>
void SetBinContent(const std::vector<RBinIndex> &indices, const V &value)
{
fEngine.SetBinContent(indices, value);
fStats.Taint();
}

/// Set the content of a single bin.
///
/// \code
Expand All @@ -299,8 +327,9 @@ public:
///
/// \param[in] args the arguments for each axis and the new value of the bin content
/// \par See also
/// the \ref SetBinContent(const std::array<RBinIndex, N> &indices, const V &value) "function overload" accepting
/// `std::array`
/// the function overloads accepting
/// \ref SetBinContent(const std::array<RBinIndex, N> &indices, const V &value) const "`std::array`" or
/// \ref SetBinContent(const std::vector<RBinIndex> &indices, const V &value) const "`std::vector`"
template <typename... A>
void SetBinContent(const A &...args)
{
Expand Down
41 changes: 39 additions & 2 deletions hist/histv7/inc/ROOT/RHistEngine.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,42 @@ public:
fBinContents[index.fIndex] = value;
}

/// Set the content of a single bin.
///
/// \code
/// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
/// std::vector<ROOT::Experimental::RBinIndex> indices = {3, 5};
/// int value = /* ... */;
/// hist.SetBinContent(indices, value);
/// \endcode
///
/// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
/// values. See also the class documentation of RBinIndex.
///
/// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
///
/// \param[in] indices the vector of indices for each axis
/// \param[in] value the new value of the bin content
/// \par See also
/// the \ref SetBinContent(const A &... args) "variadic function template overload" accepting arguments directly
template <typename V>
void SetBinContent(const std::vector<RBinIndex> &indices, const V &value)
{
// We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
// be confusing for users.
if (indices.size() != GetNDimensions()) {
throw std::invalid_argument("invalid number of indices passed to SetBinContent");
}
RLinearizedIndex index = fAxes.ComputeGlobalIndex(indices);
if (!index.fValid) {
throw std::invalid_argument("bin not found in SetBinContent");
}
assert(index.fIndex < fBinContents.size());
// To allow conversion, we have to accept value with a template type V to capture any argument. Otherwise it would
// select the variadic function template...
fBinContents[index.fIndex] = value;
}

/// \}
// End the group to ensure that all contained member functions are public.

Expand Down Expand Up @@ -330,8 +366,9 @@ public:
///
/// \param[in] args the arguments for each axis and the new value of the bin content
/// \par See also
/// the \ref SetBinContent(const std::array<RBinIndex, N> &indices, const V &value) "function overload" accepting
/// `std::array`
/// the function overloads accepting
/// \ref SetBinContent(const std::array<RBinIndex, N> &indices, const V &value) const "`std::array`" or
/// \ref SetBinContent(const std::vector<RBinIndex> &indices, const V &value) const "`std::vector`"
template <typename... A>
void SetBinContent(const A &...args)
{
Expand Down
1 change: 1 addition & 0 deletions hist/histv7/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ if(NOT DEFINED histv7_standalone)

if(pyroot)
ROOT_ADD_PYUNITTEST(hist_py hist.py)
ROOT_ADD_PYUNITTEST(hist_uhi_py hist_uhi.py)
endif()
endif()
Loading
Loading