|
| 1 | +from threading import local |
| 2 | +import numpy as np |
| 3 | +from requests import patch |
| 4 | +from scipy.ndimage import gaussian_filter, maximum_filter |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +def get_histograms(sdata, category=None,resolution=5): |
| 9 | + |
| 10 | + mins = sdata.coordinates.min(0) |
| 11 | + maxs = sdata.coordinates.max(0) |
| 12 | + |
| 13 | + n_bins = np.ceil(np.divide(maxs-mins, resolution)).astype(int) |
| 14 | + |
| 15 | + histograms=[] |
| 16 | + |
| 17 | + if category is None: |
| 18 | + for gene in sdata.genes: |
| 19 | + histograms.append(np.histogram2d(*sdata[sdata.g==gene].coordinates.T, bins=n_bins, range=([mins[0], maxs[0]], [mins[1], maxs[1]]))[0]) |
| 20 | + |
| 21 | + else: |
| 22 | + for c in sdata[category].cat.categories: |
| 23 | + histograms.append(np.histogram2d(*sdata[sdata[category]==c].coordinates.T, bins=n_bins, range=([mins[0], maxs[0]], [mins[1], maxs[1]]))[0]) |
| 24 | + |
| 25 | + return histograms |
| 26 | + |
| 27 | + |
| 28 | +def ssam(sdata,adata=None,kernel_bandwidth=2.5, patch_length=500): |
| 29 | + |
| 30 | + patch_delimiters = list(range(0,np.ceil(sdata.x.max()).astype(int),int(patch_length-kernel_bandwidth*3)))+[np.ceil(sdata.x.max()).astype(int)] |
| 31 | + |
| 32 | + localmax_vectors = [] |
| 33 | + for i,p in enumerate(patch_delimiters[:-1]): |
| 34 | + hists = get_histograms(sdata.spatial[p:patch_delimiters[i+1]],resolution=1) |
| 35 | + hists = [gaussian_filter(h,kernel_bandwidth) for h in hists] |
| 36 | + |
| 37 | + norm=np.sum(hists,axis=0) |
| 38 | + |
| 39 | + if adata is None: |
| 40 | + localmaxs=maximum_filter(norm,size=5) |
| 41 | + localmaxs = (localmaxs==norm)&(localmaxs!=0) |
| 42 | + # localmaxs = np.where(localmaxs) |
| 43 | + localmaxs= [h[localmaxs] for h in hists] |
| 44 | + localmax_vectors.append(localmaxs) |
| 45 | + # break |
| 46 | + |
| 47 | + return localmax_vectors |
| 48 | + |
| 49 | + |
| 50 | + |
0 commit comments