-
-
Notifications
You must be signed in to change notification settings - Fork 404
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
Use contourpy for contour calculations #5910
Changes from all commits
1bef1ae
a398dad
4fe9e2f
bdac077
b33418e
0d653a5
fb4eb3f
662d4fb
4d5efe7
682c3d1
4f9af4f
279ab20
7dcf8fe
939456e
ba342a5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -38,6 +38,7 @@ | |
from ..element.raster import RGB, Image | ||
from ..element.util import categorical_aggregate2d # noqa (API import) | ||
from ..streams import RangeXY | ||
from ..util.locator import MaxNLocator | ||
|
||
column_interfaces = [ArrayInterface, DictInterface, PandasInterface] | ||
|
||
|
@@ -560,13 +561,9 @@ class contours(Operation): | |
|
||
def _process(self, element, key=None): | ||
try: | ||
from matplotlib.axes import Axes | ||
from matplotlib.contour import QuadContourSet | ||
from matplotlib.dates import date2num, num2date | ||
from matplotlib.figure import Figure | ||
from contourpy import FillType, LineType, contour_generator | ||
except ImportError: | ||
raise ImportError("contours operation requires matplotlib.") | ||
extent = element.range(0) + element.range(1)[::-1] | ||
raise ImportError("contours operation requires contourpy.") | ||
|
||
xs = element.dimension_values(0, True, flat=False) | ||
ys = element.dimension_values(1, True, flat=False) | ||
|
@@ -586,6 +583,15 @@ def _process(self, element, key=None): | |
# if any data is a datetime, transform to matplotlib's numerical format | ||
data_is_datetime = tuple(isdatetime(arr) for k, arr in enumerate(data)) | ||
if any(data_is_datetime): | ||
if any(data_is_datetime[:2]) and self.p.filled: | ||
raise RuntimeError("Datetime spatial coordinates are not supported " | ||
"for filled contour calculations.") | ||
|
||
try: | ||
from matplotlib.dates import date2num, num2date | ||
except ImportError: | ||
raise ImportError("contours operation using datetimes requires matplotlib.") from None | ||
|
||
data = tuple( | ||
date2num(d) if is_datetime else d | ||
for d, is_datetime in zip(data, data_is_datetime) | ||
|
@@ -598,61 +604,97 @@ def _process(self, element, key=None): | |
contour_type = Contours | ||
vdims = element.vdims[:1] | ||
|
||
kwargs = {} | ||
levels = self.p.levels | ||
zmin, zmax = element.range(2) | ||
if isinstance(self.p.levels, int): | ||
if isinstance(levels, int): | ||
if zmin == zmax: | ||
contours = contour_type([], [xdim, ydim], vdims) | ||
return (element * contours) if self.p.overlaid else contours | ||
data += (levels,) | ||
else: | ||
# The +1 is consistent with Matplotlib's use of MaxNLocator for contours. | ||
locator = MaxNLocator(levels + 1) | ||
hoxbro marked this conversation as resolved.
Show resolved
Hide resolved
|
||
levels = locator.tick_values(zmin, zmax) | ||
else: | ||
kwargs = {'levels': levels} | ||
levels = np.array(levels) | ||
|
||
if data_is_datetime[2]: | ||
levels = date2num(levels) | ||
|
||
fig = Figure() | ||
ax = Axes(fig, [0, 0, 1, 1]) | ||
contour_set = QuadContourSet(ax, *data, filled=self.p.filled, | ||
extent=extent, **kwargs) | ||
levels = np.array(contour_set.get_array()) | ||
crange = levels.min(), levels.max() | ||
if self.p.filled: | ||
levels = levels[:-1] + np.diff(levels)/2. | ||
vdims = [vdims[0].clone(range=crange)] | ||
|
||
cont_gen = contour_generator( | ||
*data, | ||
line_type=LineType.ChunkCombinedOffset, | ||
fill_type=FillType.ChunkCombinedOffsetOffset, | ||
) | ||
|
||
def points_to_datetime(points): | ||
# transform x/y coordinates back to datetimes | ||
xs, ys = np.split(points, 2, axis=1) | ||
if data_is_datetime[0]: | ||
xs = np.array(num2date(xs)) | ||
if data_is_datetime[1]: | ||
ys = np.array(num2date(ys)) | ||
return np.concatenate((xs, ys), axis=1) | ||
|
||
paths = [] | ||
empty = np.array([[np.nan, np.nan]]) | ||
for level, cset in zip(levels, contour_set.collections): | ||
exteriors = [] | ||
interiors = [] | ||
for geom in cset.get_paths(): | ||
interior = [] | ||
polys = geom.to_polygons(closed_only=False) | ||
for ncp, cp in enumerate(polys): | ||
if any(data_is_datetime[0:2]): | ||
# transform x/y coordinates back to datetimes | ||
xs, ys = np.split(cp, 2, axis=1) | ||
if data_is_datetime[0]: | ||
xs = np.array(num2date(xs)) | ||
if data_is_datetime[1]: | ||
ys = np.array(num2date(ys)) | ||
cp = np.concatenate((xs, ys), axis=1) | ||
if ncp == 0: | ||
exteriors.append(cp) | ||
if self.p.filled: | ||
empty = np.array([[np.nan, np.nan]]) | ||
for lower_level, upper_level in zip(levels[:-1], levels[1:]): | ||
filled = cont_gen.filled(lower_level, upper_level) | ||
# Only have to consider last index 0 as we are using contourpy without chunking | ||
if (points := filled[0][0]) is None: | ||
continue | ||
|
||
exteriors = [] | ||
interiors = [] | ||
if any(data_is_datetime[0:2]): | ||
points = points_to_datetime(points) | ||
|
||
offsets = filled[1][0] | ||
outer_offsets = filled[2][0] | ||
|
||
# Loop through exterior polygon boundaries. | ||
for jstart, jend in zip(outer_offsets[:-1], outer_offsets[1:]): | ||
if exteriors: | ||
exteriors.append(empty) | ||
else: | ||
interior.append(cp) | ||
if len(polys): | ||
exteriors.append(points[offsets[jstart]:offsets[jstart + 1]]) | ||
|
||
# Loop over the (jend-jstart-1) interior boundaries. | ||
interior = [points[offsets[j]:offsets[j + 1]] for j in range(jstart+1, jend)] | ||
interiors.append(interior) | ||
if not exteriors: | ||
continue | ||
geom = { | ||
element.vdims[0].name: | ||
num2date(level) if data_is_datetime[2] else level, | ||
(xdim, ydim): np.concatenate(exteriors[:-1]) | ||
} | ||
if self.p.filled and interiors: | ||
geom['holes'] = interiors | ||
paths.append(geom) | ||
level = (lower_level + upper_level) / 2 | ||
geom = { | ||
element.vdims[0].name: | ||
num2date(level) if data_is_datetime[2] else level, | ||
(xdim, ydim): np.concatenate(exteriors) if exteriors else [], | ||
} | ||
if interiors: | ||
geom['holes'] = interiors | ||
paths.append(geom) | ||
else: | ||
for level in levels: | ||
lines = cont_gen.lines(level) | ||
# Only have to consider last index 0 as we are using contourpy without chunking | ||
if (points := lines[0][0]) is None: | ||
continue | ||
|
||
if any(data_is_datetime[0:2]): | ||
points = points_to_datetime(points) | ||
|
||
offsets = lines[1][0] | ||
if offsets is not None and len(offsets) > 2: | ||
# Casting offsets to int64 to avoid possible numpy UFuncOutputCastingError | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a concern. It isn't needed for There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What was the type of the KDE test? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With a clean environment this is now needed to avoid the "UFunc add" error in many tests ( |
||
offsets = offsets[1:-1].astype(np.int64) | ||
points = np.insert(points, offsets, np.nan, axis=0) | ||
geom = { | ||
element.vdims[0].name: | ||
num2date(level) if data_is_datetime[2] else level, | ||
(xdim, ydim): points if points is not None else [], | ||
} | ||
paths.append(geom) | ||
contours = contour_type(paths, label=element.label, kdims=element.kdims, vdims=vdims) | ||
if self.p.overlaid: | ||
contours = element * contours | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is no longer used as I don't think it is required. There is explicit code to set the
x
andy
arrays and pass them through, so theextent
kwarg would have been ignored.