Creates a boolean mask to include points within k nearest
    neighbours, and exclude the rest.
    Logic can be OR or AND. OR gives the k-nearest-neighbour mask,
    AND gives the mutual k-nearest-neighbour mask.

def kmask(matrix, k=7, dists=None, logic='or'):
    """ Creates a boolean mask to include points within k nearest
    neighbours, and exclude the rest.
    Logic can be OR or AND. OR gives the k-nearest-neighbour mask,
    AND gives the mutual k-nearest-neighbour mask."""

    dists = (kdists(matrix, k=k) if dists is None else dists)
    mask = (matrix <= dists)
    if logic == 'or' or logic == '|':
        return mask | mask.T
    elif logic == 'and' or logic == '&':
        return mask & mask.T
    return mask