I have two 1D grids, each of them is a finite collection of cells, where the cell is defined by the left end and the right end, $[cell]_{i}$=$[x_{i}^{left}$,$x_{i}^{right}$]. I need to find the overlap of these grids, i.e., what cell of grid #1 overlaps with what cell of grid #2, and what is the overlapping area (length).
This must be a very standard problem, and probably there is a standard algorithm for it. Is it implemented in a standard library, preferably in Python?
Below I am including a Python script that solves this problem in a simple way, checking every pair of grid cells. The code can print grids used, if keyword is set show=True in test_grid_overlap()
# Usage (in Python)
# > exec(open("grid_overlap.py").read())
# > test_grid_overlap()
#==============================================#
import numpy as np
import time
def overlap(min1, max1, min2, max2):
#-find overlap of two segments
return max(0, min(max1, max2) - max(min1, min2))
def grid_overlap(grid1, grid2):
#-calculate overlap between cells of two 1D grids
ngrid1=len(grid1[0,:])
ngrid2=len(grid2[0,:])
ovlap=np.zeros([ngrid1,ngrid2])
for i in range(0,ngrid1):
for j in range(0,ngrid2):
ovlap[i,j] = overlap(grid1[0,i], grid1[1,i], grid2[0,j], grid2[1,j])
return ovlap
def make_1D_grid(ngrid):
#-generate a 1D grid as a 2D array combining left and right boundaries of cells
#generate a random monotonic sequence
arr = np.sort(np.random.rand(ngrid+1))
left = arr[0:ngrid]
right = arr[1:ngrid+1]
#-combine two 1D arrays (left,right) in a 2D array
grid=np.concatenate([[left],[right]])
return grid
def test_grid_overlap(n1=5, n2=3, show=False):
#-see how it all works
grid1 = make_1D_grid(n1)
grid2 = make_1D_grid(n2)
start=time.time()
res = grid_overlap(grid1, grid2)
end=time.time()
print ("Time elapsed:", end - start)
if show:
print("grid1:")
print(grid1)
print("grid2:")
print(grid2)
print("overlap:")
print(res)