Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6007164

Browse files
committed
ENH: speed-up mlab.contiguous_regions using numpy
1 parent 4f31d27 commit 6007164

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

lib/matplotlib/mlab.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3874,23 +3874,17 @@ def contiguous_regions(mask):
38743874
"""
38753875
return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
38763876
True and we cover all such regions
3877-
3878-
TODO: this is a pure python implementation which probably has a much
3879-
faster numpy impl
38803877
"""
3878+
mask = np.asarray(mask, dtype=bool)
3879+
3880+
if not mask.size:
3881+
return []
38813882

3882-
in_region = None
3883-
boundaries = []
3884-
for i, val in enumerate(mask):
3885-
if in_region is None and val:
3886-
in_region = i
3887-
elif in_region is not None and not val:
3888-
boundaries.append((in_region, i))
3889-
in_region = None
3883+
idx, = np.nonzero(mask[:-1] != mask[1:])
3884+
idx = np.concatenate((([0],) if mask[0] else ()) + (idx + 1,) +
3885+
(([len(mask)],) if mask[-1] else ()))
38903886

3891-
if in_region is not None:
3892-
boundaries.append((in_region, i+1))
3893-
return boundaries
3887+
return list(zip(idx[::2], idx[1::2]))
38943888

38953889

38963890
def cross_from_below(x, threshold):

0 commit comments

Comments
 (0)