Last active
November 6, 2018 17:57
-
-
Save tgarc/8296c4e6949d3c7b5fcaf25c0a4fb624 to your computer and use it in GitHub Desktop.
find runs of constant value, returning their indices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def mask2runs(mask): | |
''' | |
mask2runs | |
Turns a boolean array into an array of indices indicating the start and end indices of each run of 1's. | |
''' | |
runflip = np.nonzero(mask[1:] ^ mask[:-1])[0]+1 | |
runflip[1::2] -= 1 # Note that the prior step returns end indices as the end of a run plus 1 | |
# if the last run was a run of 1's, count the last epoch as the end of the run | |
# similarly if the first bit started a run of 1's | |
if mask[-1]: runflip = np.r_[runflip,len(mask)] | |
if mask[0]: runflip = np.r_[0,runflip] | |
return runflip[::2], runflip[1::2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment