Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve groupby behavior for operation histogram #6172

Merged
merged 6 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
36 changes: 24 additions & 12 deletions holoviews/operation/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
examples.
"""
import warnings
from functools import partial

import numpy as np
import param
Expand Down Expand Up @@ -754,6 +755,9 @@ class histogram(Operation):
groupby = param.ClassSelector(default=None, class_=(str, Dimension), doc="""
Defines a dimension to group the Histogram returning an NdOverlay of Histograms.""")

groupby_range = param.Selector(default="shared", objects=["shared", "separated"], doc="""
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better names here are welcome.

Whether to group the histograms along the same range or separate them.""")

log = param.Boolean(default=False, doc="""
Whether to use base 10 logarithmic samples for the bin edges.""")

Expand Down Expand Up @@ -781,15 +785,7 @@ class histogram(Operation):
style_prefix = param.String(default=None, allow_None=None, doc="""
Used for setting a common style for histograms in a HoloMap or AdjointLayout.""")

def _process(self, element, key=None):
if self.p.groupby:
if not isinstance(element, Dataset):
raise ValueError('Cannot use histogram groupby on non-Dataset Element')
grouped = element.groupby(self.p.groupby, group_type=Dataset, container_type=NdOverlay)
self.p.groupby = None
return grouped.map(self._process, Dataset)

normed = False if self.p.mean_weighted and self.p.weight_dimension else self.p.normed
def _get_dim_and_data(self, element):
if self.p.dimension:
selected_dim = self.p.dimension
else:
Expand All @@ -800,6 +796,21 @@ def _process(self, element, key=None):
data = element.interface.values(element, selected_dim, compute=False)
else:
data = element.dimension_values(selected_dim)
return dim, data

def _process(self, element, key=None, groupby=False):
if self.p.groupby:
if not isinstance(element, Dataset):
raise ValueError('Cannot use histogram groupby on non-Dataset Element')
grouped = element.groupby(self.p.groupby, group_type=Dataset, container_type=NdOverlay)
if self.p.groupby_range == 'shared' and not self.p.bin_range:
_, data = self._get_dim_and_data(element)
self.bin_range = (data.min(), data.max())
hoxbro marked this conversation as resolved.
Show resolved Hide resolved
self.p.groupby = None
return grouped.map(partial(self._process, groupby=True), Dataset)

normed = False if self.p.mean_weighted and self.p.weight_dimension else self.p.normed
dim, data = self._get_dim_and_data(element)

is_datetime = isdatetime(data)
if is_datetime:
Expand Down Expand Up @@ -859,7 +870,7 @@ def _process(self, element, key=None):
if isdatetime(edges):
edges = edges.astype('datetime64[ns]').astype('int64')
else:
hist_range = self.p.bin_range or element.range(selected_dim)
hist_range = self.p.bin_range or element.range(dim)
# Suppress a warning emitted by Numpy when datetime or timedelta scalars
# are compared. See https://github.com/numpy/numpy/issues/10095 and
# https://github.com/numpy/numpy/issues/9210.
Expand Down Expand Up @@ -939,8 +950,9 @@ def _process(self, element, key=None):
# Save off the computed bin edges so that if this operation instance
# is used to compute another histogram, it will default to the same
# bin edges.
self.bins = list(edges)
return Histogram((edges, hist), kdims=[element.get_dimension(selected_dim)],
if not groupby:
self.bins = list(edges)
return Histogram((edges, hist), kdims=[dim],
label=element.label, **params)


Expand Down
42 changes: 42 additions & 0 deletions holoviews/tests/operation/test_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,48 @@ def test_dataset_histogram_empty_explicit_bins(self):
hist = Histogram(([0, 1, 2], [0, 0]), vdims=('x_count', 'Count'))
self.assertEqual(op_hist, hist)

def test_dataset_histogram_groupby_range_shared(self):
x = np.arange(10)
y = np.arange(10) + 10
xy = np.concatenate([x, y])
label = ["x"] * 10 + ["y"] * 10

ds = Dataset(pd.DataFrame([xy, label], index=["xy", "label"]).T, vdims=["xy", "label"])
hist = histogram(ds, groupby="label", groupby_range="shared")
exp = np.linspace(0, 19, 21)
for k, v in hist.items():
np.testing.assert_equal(exp, v.data["xy"])
sel = np.asarray(label) == k
assert (v.data["xy_count"][sel] == 1).all()
assert (v.data["xy_count"][~sel] == 0).all()

def test_dataset_histogram_groupby_range_separated(self):
x = np.arange(10)
y = np.arange(10) + 10
xy = np.concatenate([x, y])
label = ["x"] * 10 + ["y"] * 10

ds = Dataset(pd.DataFrame([xy, label], index=["xy", "label"]).T, vdims=["xy", "label"])
hist = histogram(ds, groupby="label", groupby_range="separated")

for idx, v in enumerate(hist):
exp = np.linspace(idx * 10, 10 * idx + 9, 21)
np.testing.assert_equal(exp, v.data["xy"])
assert v.data["xy_count"].sum() == 10

def test_dataset_histogram_groupby_datetime(self):
x = pd.date_range("2020-01-01", periods=100)
y = pd.date_range("2020-01-01", periods=100)
xy = np.concatenate([x, y])
label = ["x"] * 100 + ["y"] * 100
ds = Dataset(pd.DataFrame([xy, label], index=["xy", "label"]).T, vdims=["xy", "label"])
hist = histogram(ds, groupby="label")

exp = pd.date_range("2020-01-01", '2020-04-09', periods=21)
for h in hist:
np.testing.assert_equal(exp, h.data["xy"])
assert (h.data["xy_count"] == 5).all()

@da_skip
def test_dataset_histogram_dask(self):
import dask.array as da
Expand Down
Loading