Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Last active July 28, 2022 03:14
Show Gist options
  • Save thehappycheese/b61a1f9132349813be0ddfaad9e080e5 to your computer and use it in GitHub Desktop.
Save thehappycheese/b61a1f9132349813be0ddfaad9e080e5 to your computer and use it in GitHub Desktop.
Interval overlap (signed distance) for numpy lists of intervals
import numpy as np
from numpy import typing as npt
def overlap(a:npt.NDArray, b:npt.NDArray, x:npt.NDArray, y:npt.NDArray):
"""Compute the signed distance between lists of intervals"""
overlap_min = np.maximum(a, x.reshape(-1,1))
overlap_max = np.minimum(b, y.reshape(-1,1))
signed_overlap_len = overlap_max - overlap_min
return signed_overlap_len
ab = np.array([
[100,200], # <-- represents interval from 100 to 200
[200,300],
[300,400]
])
xy = np.array([
[50,120],
[120,310],
[350,450],
[450,550]
])
overlap(ab[:,0],ab[:,1],xy[:,0],xy[:,1])
# array([[ 20, -80, -180],
# [ 80, 100, 10],
# [-150, -50, 50],
# [-250, -150, -50]])
# Note
# - positive values in the output are overlap distance
# - negative values in the output are minimum separation distance
# - the columns in the output correspond to the rows in `ab`, and
# - the rows in the output correspond to the rows in `xy`
# - zero values indicate either
# - touching intervals, OR
# - one of the inputs was zero length
# - if the input contains intervals which are
# - zero length; the outputs will be AMBIGUOUS
# - reversed; the outputs will be INVALID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment