Skip to content

Instantly share code, notes, and snippets.

@tgarc
Last active November 6, 2018 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgarc/8296c4e6949d3c7b5fcaf25c0a4fb624 to your computer and use it in GitHub Desktop.
Save tgarc/8296c4e6949d3c7b5fcaf25c0a4fb624 to your computer and use it in GitHub Desktop.
find runs of constant value, returning their indices
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