"""Exact spatial membership index. Original source order and height cuts retained.""" import numpy as np class SpatialIndex: def __init__(self, world, relative, lower, upper, cell=20.): self.world=world;self.cell=cell valid=np.flatnonzero((relative>=lower)&(relative<=upper)&np.isfinite(world[:,:2]).all(1)) xy=np.floor(world[valid,:2]/cell).astype(np.int64) self.low=xy.min(0) if len(xy) else np.zeros(2,np.int64) self.width=int(np.ptp(xy[:,0])+1) if len(xy) else 1 codes=(xy[:,1]-self.low[1])*self.width+xy[:,0]-self.low[0] order=np.argsort(codes,kind='stable');self.indices=valid[order];self.codes=codes[order] self.high=xy.max(0) if len(xy) else self.low-1 def query(self, bounds): bounds=np.asarray(bounds);lo=np.maximum(np.floor(bounds[0]/self.cell).astype(np.int64),self.low) hi=np.minimum(np.floor(bounds[1]/self.cell).astype(np.int64),self.high) parts=[] for y in range(lo[1],hi[1]+1): if lo[0]>hi[0]:continue first=(y-self.low[1])*self.width+lo[0]-self.low[0] last=(y-self.low[1])*self.width+hi[0]-self.low[0] a,b=np.searchsorted(self.codes,[first,last],side='left');b=np.searchsorted(self.codes,last,side='right') parts.append(self.indices[a:b]) ids=np.sort(np.concatenate(parts)) if parts else np.array([],dtype=np.int64) return ids[((self.world[ids,:2]>=bounds[0])&(self.world[ids,:2]<=bounds[1])).all(1)]