Moran’s I#
[1]:
#%load_ext autoreload
#%autoreload 2
#
from astropathdb import load_astrosample
from astropathdb import plotting as pl
from astropathdb import analysis as al
from astropathdb import tools as tl
import numpy
#
import geopandas as gpd
from libpysal import weights
from esda.moran import Moran_Local
import matplotlib.pyplot as plt
#
import colorcet as cc
import datashader as ds
import datashader.transfer_functions as tf
#
[ ]:
sampleid = 1
s = load_astrosample(sampleid = sampleid, cell_positions = True, cell_tables= True)
[223]:
s.cellmeta.mixing_matrix = 'default'
[230]:
s.load_image(x = (20000,50000), y = (6000, 30000), coords_type = 'pixels', resolution = 6)
[231]:
pl.ShowAnno(s, contrast = 3, annos_kwargs={'lw':.0001, 'alpha':0}, imshow_kwargs = {'yincrease': True}).show()
[236]:
pl.ShowAnno(s, annos_kwargs={'color':['tab:blue','tab:olive'],'lw':1}, imshow_kwargs = {'yincrease': True}).show()
[233]:
#s.load_image(x = (20000,50000), y = (6000, 30000), coords_type = 'pixels')
#tl.apply_rgb_transformation(s)
tl.get_spatial_heatmap(s, column = 'centirecell620', alpha = .65)
pl.ShowAnno(s, image_element_id = f'sampleid_{sampleid}_hmap_256_centirecell620_6', annos_kwargs={'color':['tab:blue','tab:olive'], 'lw':0.001, 'alpha':0}, imshow_kwargs = {'yincrease': True}).show()
[235]:
pl.ShowAnno(s, image_element_id = f'sampleid_{sampleid}_hmap_256_centirecell620_6', annos_kwargs={'color':['tab:blue','tab:olive'], 'lw':1, 'alpha':0}, imshow_kwargs = {'yincrease': True}).show()
[132]:
expression = 'centirecell620'
idx = s[f'sampleid_{sampleid}_mIF'].var.index.get_loc(expression)
db = s[f'sampleid_{sampleid}_cell_positions'].copy()
db.set_index('cellid', inplace = True)
db.loc[s[f'sampleid_{sampleid}_mIF'].obs.index, expression] = s[f'sampleid_{sampleid}_mIF'].X[:, idx]
[133]:
db.head()
[133]:
| ptype | exprphenotype | sampleid | geometry | radius | centirecell620 | |
|---|---|---|---|---|---|---|
| cellid | ||||||
| 1002100005 | 3 | 64 | 1 | POINT (45585.338 8489.776) | 5 | 3.486857 |
| 1002100009 | 1 | 0 | 1 | POINT (45587.338 7934.776) | 5 | 12.686810 |
| 1002100010 | 1 | 0 | 1 | POINT (45557.338 7977.776) | 5 | 82.857720 |
| 1002100011 | 1 | 0 | 1 | POINT (45501.338 8048.776) | 5 | 19.579080 |
| 1002100012 | 1 | 0 | 1 | POINT (45515.338 8047.776) | 5 | 100.174800 |
[142]:
canvas = ds.Canvas(plot_width=400, plot_height=400)
agg = canvas.points(db, geometry="geometry", agg=ds.mean(f"{expression}"))
im = tf.shade(tf.spread(agg), cmap=cc.rainbow4, how="eq_hist")
tf.set_background(im, "black")
[142]:
[131]:
expression
[131]:
'cmembrane540'
[138]:
w = weights.DistanceBand.from_dataframe(db, geom_col = 'geometry', threshold = 500, use_index = True)
w.transform = 'R'
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\libpysal\weights\util.py:826: UserWarning: The weights matrix is not fully connected:
There are 2 disconnected components.
w = W(neighbors, weights, ids, **kwargs)
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\libpysal\weights\distance.py:844: UserWarning: The weights matrix is not fully connected:
There are 2 disconnected components.
W.__init__(
[139]:
lisa = Moran_Local(db[expression], w, n_jobs = -1)
db[f"{expression}_Is"] = lisa.Is
db[f"{expression}_z_sim"] = lisa.z_sim
db[f"{expression}_p_sim"] = lisa.p_sim
db[f"{expression}_q"] = lisa.q
[141]:
canvas = ds.Canvas(plot_width=400, plot_height=400)
agg = canvas.points(db, geometry="geometry", agg=ds.mean(f"{expression}"))
im = tf.shade(tf.spread(agg), cmap=cc.bkr, how="eq_hist")
tf.set_background(im, "black")
[141]:
[192]:
from datashader.utils import export_image
from matplotlib import cm
[197]:
canvas = ds.Canvas(plot_width=400, plot_height=400)
agg = canvas.points(db, geometry="geometry", agg=ds.mean(f"{expression}_Is"))
im = tf.shade(agg, cmap=cc.rainbow4, how="eq_hist")
tf.set_background(im, "black")
export_image(im, "out", background="black", export_path=".")
[197]:
[49]:
from astropathdb.tools.spatial_heatmap import BuildHeatmap
[53]:
thing = BuildHeatmap(s)
ws = thing.get_expression_weights()
X, Y, mesh = thing.get_2d_mesh_on_astrosample(weights=ws)
[ ]:
expression = 'cmembrane540'
idx = s[f'sampleid_{sampleid}_mIF'].var.index.get_loc(expression)
db = s[f'sampleid_{sampleid}_cell_positions'].copy()
db[expression] = numpy.log10(s[f'sampleid_{sampleid}_mIF'].X[:, idx] + 1)
w = weights.KNN.from_dataframe(db, geom_col = 'geometry', k=50, radius = 50)
w.transform = "R"
lisa = Moran_Local(db[expression], w)
db[f"{expression}_Is"] = lisa.Is
db[f"{expression}_z_sim"] = lisa.z_sim
db[f"{expression}_p_sim"] = lisa.p_sim
db[f"{expression}_q"] = lisa.q
#dd = db[db['centirecell620_p_sim'] < .05]
canvas = ds.Canvas(plot_width=800, plot_height=800)
agg = canvas.points(db, geometry="geometry", agg=ds.mean(f"{expression}_Is"))
im = tf.shade(agg, cmap=cc.bkr, how="eq_hist")
tf.set_background(im, "black")
[8]:
import seaborn as sns
[34]:
d = s[f'sampleid_{sampleid}_mIF'].X[:, idx]
[39]:
def get_gdf(s, sampleid=1,expression='centirecell620'):
idx = s[f'sampleid_{sampleid}_mIF'].var.index.get_loc(expression)
db = s[f'sampleid_{sampleid}_cell_positions'].copy()
db[expression] = numpy.log10(d[d>15] + .0001)
return db
def compute_local_morans(s, sampleid = 1, expression = 'centirecell620', k=50, p=2, v = False):
# get expression vector from spatialdata
db = get_gdf(s, sampleid, expression)
# Generate W from the GeoDataFrame
w = weights.DistanceBand.from_dataframe(db, geom_col = 'geometry', use_index = True, threshold = 50, binary = False, alpha=-1.0)
w1 = w
# Row-standardization
w.transform = "R"
#db[f"w_{expression}"] = weights.lag_spatial(w, db[expression])
#db[f"{expression}_std"] = db[expression] - db[expression].mean()
#db[f"w_{expression}_std"] = weights.lag_spatial(w, db[f"{expression}_std"])
#
lisa = Moran_Local(db[expression], w)
db[f"{expression}_Is"] = lisa.Is
db[f"{expression}_z_sim"] = lisa.z_sim
db[f"{expression}_p_sim"] = lisa.p_sim
db[f"{expression}_q"] = lisa.q
return db, lisa
[21]:
expression = 'centirecell620'
db, lisa = compute_local_morans(s, sampleid =sampleid)
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\scipy\sparse\_data.py:133: RuntimeWarning: divide by zero encountered in reciprocal
return self._with_data(data ** n)
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\libpysal\weights\util.py:826: UserWarning: The weights matrix is not fully connected:
There are 103 disconnected components.
There are 64 islands with ids: 4, 175, 178, 910, 1533, 1843, 4082, 6255, 7398, 8031, 8616, 8681, 8699, 9537, 11844, 11877, 11991, 17030, 17062, 17066, 17070, 17071, 17072, 17135, 17138, 17340, 17349, 17598, 19355, 19367, 20948, 20950, 21091, 21139, 21536, 21544, 21547, 21578, 21689, 21937, 21986, 21991, 22323, 25605, 25638, 25642, 25712, 25718, 25737, 25773, 25787, 25830, 25930, 26080, 26153, 26163, 26166, 26214, 26216, 26640, 26701, 26867, 26951, 26976.
w = W(neighbors, weights, ids, **kwargs)
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\libpysal\weights\distance.py:844: UserWarning: The weights matrix is not fully connected:
There are 103 disconnected components.
There are 64 islands with ids: 4, 175, 178, 910, 1533, 1843, 4082, 6255, 7398, 8031, 8616, 8681, 8699, 9537, 11844, 11877, 11991, 17030, 17062, 17066, 17070, 17071, 17072, 17135, 17138, 17340, 17349, 17598, 19355, 19367, 20948, 20950, 21091, 21139, 21536, 21544, 21547, 21578, 21689, 21937, 21986, 21991, 22323, 25605, 25638, 25642, 25712, 25718, 25737, 25773, 25787, 25830, 25930, 26080, 26153, 26163, 26166, 26214, 26216, 26640, 26701, 26867, 26951, 26976.
W.__init__(
('WARNING: ', 4, ' is an island (no neighbors)')
('WARNING: ', 175, ' is an island (no neighbors)')
('WARNING: ', 178, ' is an island (no neighbors)')
('WARNING: ', 910, ' is an island (no neighbors)')
('WARNING: ', 1533, ' is an island (no neighbors)')
('WARNING: ', 1843, ' is an island (no neighbors)')
('WARNING: ', 4082, ' is an island (no neighbors)')
('WARNING: ', 6255, ' is an island (no neighbors)')
('WARNING: ', 7398, ' is an island (no neighbors)')
('WARNING: ', 8031, ' is an island (no neighbors)')
('WARNING: ', 8616, ' is an island (no neighbors)')
('WARNING: ', 8681, ' is an island (no neighbors)')
('WARNING: ', 8699, ' is an island (no neighbors)')
('WARNING: ', 9537, ' is an island (no neighbors)')
('WARNING: ', 11844, ' is an island (no neighbors)')
('WARNING: ', 11877, ' is an island (no neighbors)')
('WARNING: ', 11991, ' is an island (no neighbors)')
('WARNING: ', 17030, ' is an island (no neighbors)')
('WARNING: ', 17062, ' is an island (no neighbors)')
('WARNING: ', 17066, ' is an island (no neighbors)')
('WARNING: ', 17070, ' is an island (no neighbors)')
('WARNING: ', 17071, ' is an island (no neighbors)')
('WARNING: ', 17072, ' is an island (no neighbors)')
('WARNING: ', 17135, ' is an island (no neighbors)')
('WARNING: ', 17138, ' is an island (no neighbors)')
('WARNING: ', 17340, ' is an island (no neighbors)')
('WARNING: ', 17349, ' is an island (no neighbors)')
('WARNING: ', 17598, ' is an island (no neighbors)')
('WARNING: ', 19355, ' is an island (no neighbors)')
('WARNING: ', 19367, ' is an island (no neighbors)')
('WARNING: ', 20948, ' is an island (no neighbors)')
('WARNING: ', 20950, ' is an island (no neighbors)')
('WARNING: ', 21091, ' is an island (no neighbors)')
('WARNING: ', 21139, ' is an island (no neighbors)')
('WARNING: ', 21536, ' is an island (no neighbors)')
('WARNING: ', 21544, ' is an island (no neighbors)')
('WARNING: ', 21547, ' is an island (no neighbors)')
('WARNING: ', 21578, ' is an island (no neighbors)')
('WARNING: ', 21689, ' is an island (no neighbors)')
('WARNING: ', 21937, ' is an island (no neighbors)')
('WARNING: ', 21986, ' is an island (no neighbors)')
('WARNING: ', 21991, ' is an island (no neighbors)')
('WARNING: ', 22323, ' is an island (no neighbors)')
('WARNING: ', 25605, ' is an island (no neighbors)')
('WARNING: ', 25638, ' is an island (no neighbors)')
('WARNING: ', 25642, ' is an island (no neighbors)')
('WARNING: ', 25712, ' is an island (no neighbors)')
('WARNING: ', 25718, ' is an island (no neighbors)')
('WARNING: ', 25737, ' is an island (no neighbors)')
('WARNING: ', 25773, ' is an island (no neighbors)')
('WARNING: ', 25787, ' is an island (no neighbors)')
('WARNING: ', 25830, ' is an island (no neighbors)')
('WARNING: ', 25930, ' is an island (no neighbors)')
('WARNING: ', 26080, ' is an island (no neighbors)')
('WARNING: ', 26153, ' is an island (no neighbors)')
('WARNING: ', 26163, ' is an island (no neighbors)')
('WARNING: ', 26166, ' is an island (no neighbors)')
('WARNING: ', 26214, ' is an island (no neighbors)')
('WARNING: ', 26216, ' is an island (no neighbors)')
('WARNING: ', 26640, ' is an island (no neighbors)')
('WARNING: ', 26701, ' is an island (no neighbors)')
('WARNING: ', 26867, ' is an island (no neighbors)')
('WARNING: ', 26951, ' is an island (no neighbors)')
('WARNING: ', 26976, ' is an island (no neighbors)')
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\esda\moran.py:1084: RuntimeWarning: invalid value encountered in divide
self.z_sim = (self.Is - self.EI_sim) / self.seI_sim
[26]:
idx = s[f'sampleid_{sampleid}_mIF'].var.index.get_loc(expression)
db = s[f'sampleid_{sampleid}_cell_positions'].copy()
db[expression] = numpy.log10(s[f'sampleid_{sampleid}_mIF'].X[:, idx] + .0001)
w = weights.Kernel.from_dataframe(db, geom_col = 'geometry', fixed=False, k=15)
w.transform = "R"
lisa = Moran_Local(db[expression], w)
db[f"{expression}_Is"] = lisa.Is
db[f"{expression}_z_sim"] = lisa.z_sim
db[f"{expression}_p_sim"] = lisa.p_sim
db[f"{expression}_q"] = lisa.q
e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\libpysal\weights\distance.py:563: UserWarning: The weights matrix is not fully connected:
There are 3 disconnected components.
W.__init__(self, neighbors, weights, ids, **kwargs)
[95]:
def spaital_correlogram(s, sampleid=1,expression='centirecell620'):
# Load the GeoDataFrame
gdf = get_gdf(s, sampleid=sampleid, expression=expression)
# Extract the variable of interest
y = gdf[expression].values
# Calculate Moran's I at different spatial lags
moran_values = []
for k in range(1, 50):
print(k)
w_lag = weights.distance.KNN.from_dataframe(gdf, geom_col = 'geometry', use_index = True, k = k)
w_lag.transform = "R"
#w_lag = w.k_nearest_neighbors(k)
moran = Moran(y, w_lag)
moran_values.append(moran.I)
#
return moran_values
[ ]:
moran_values = numpy.array(moran_values)
# Plot the spatial correlogram
plt.figure(figsize=(2, 2))
plt.plot(range(1, len(moran_values) + 1), moran_values, marker='o')
plt.title('Spatial Correlogram')
plt.xlabel('Spatial Lag (k-nearest neighbors)')
plt.ylabel("Moran's I")
plt.grid(True)
plt.show()
[151]:
from splot import esda as esdaplot
import pandas
[156]:
# Set up figure and axes
f, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 12), facecolor = 'white')
# Make the axes accessible with single indexing
axs = axs.flatten()
# Subplot 1 #
# Choropleth of local statistics
# Grab first axis in the figure
ax = axs[0]
# Assign new column with local statistics on-the-fly
db.assign(
Is=lisa.Is
# Plot choropleth of local statistics
).plot(
column="Is",
cmap="plasma",
scheme="quantiles",
k=5,
edgecolor = 'none',
alpha=0.75,
legend=True,
ax=ax,
s = 1
)
# Subplot 2 #
# Quadrant categories
# Grab second axis of local statistics
ax = axs[1]
# Plot Quadrant colors (note to ensure all polygons are assigned a
# quadrant, we "trick" the function by setting significance level to
# 1 so all observations are treated as "significant" and thus assigned
# a quadrant color
esdaplot.lisa_cluster(lisa, db, p=1, ax=ax, s=1, edgecolor = 'none')
# Subplot 3 #
# Significance map
# Grab third axis of local statistics
ax = axs[2]
#
# Find out significant observations
labels = pandas.Series(
1 * (lisa.p_sim < 0.05), # Assign 1 if significant, 0 otherwise
index=db.index # Use the index in the original data
# Recode 1 to "Significant and 0 to "Non-significant"
).map({1: "Significant", 0: "Non-Significant"})
# Assign labels to `db` on the fly
db.assign(
cl=labels
# Plot choropleth of (non-)significant areas
).plot(
column="cl",
categorical=True,
k=2,
cmap="Paired",
edgecolor = 'none',
legend=True,
ax=ax,
s=1
)
# Subplot 4 #
# Cluster map
# Grab second axis of local statistics
ax = axs[3]
# Plot Quadrant colors In this case, we use a 5% significance
# level to select polygons as part of statistically significant
# clusters
esdaplot.lisa_cluster(lisa, db, p=0.05, ax=ax, s=1, edgecolor = 'none')
# Figure styling #
# Set title to each subplot
for i, ax in enumerate(axs.flatten()):
ax.set_axis_off()
ax.set_title(
[
"Local Statistics",
"Scatterplot Quadrant",
"Statistical Significance",
"Moran Cluster Map",
][i],
y=0,
)
# Tight layout to minimize in-between white space
f.tight_layout()
# Display the figure
plt.show()
[ ]:
# Set up the figure and axis
f, ax = plt.subplots(1, figsize=(6, 6))
# Plot values
seaborn.regplot(
x="tumor_std", y="w_tumor_std", data=db, ci=None
)
plt.show()
# Set up the figure and axis
f, ax = plt.subplots(1, figsize=(6, 6))
# Plot values
seaborn.regplot(
x="tumor_std", y="w_tumor_std", data=db, ci=None
)
# Add vertical and horizontal lines
plt.axvline(0, c="k", alpha=0.5)
plt.axhline(0, c="k", alpha=0.5)
# Add text labels for each quadrant
plt.text(20, 5, "HH", fontsize=25, c="r")
plt.text(12, -11, "HL", fontsize=25, c="r")
plt.text(-20, 8.0, "LH", fontsize=25, c="r")
plt.text(-25, -11.0, "LL", fontsize=25, c="r")
# Display
plt.show()
# Draw KDE line
ax = seaborn.kdeplot(lisa.Is)
# Add one small bar (rug) for each observation
# along horizontal axis
seaborn.rugplot(lisa.Is, ax=ax);
[ ]:
thing = BuildHeatmap(s)
ws = thing.get_expression_weights()
X, Y, mesh = thing.get_2d_mesh_on_astrosample(weights=ws)
pop = mesh
w_surface_sp = weights.Queen.from_xarray(pop)
w_surface_all = weights.WSP2W( # 3.Convert `WSP` object to `W`
weights.WSP( # 2a.Build `WSP` from the float sparse matrix
w_surface_sp.sparse.astype(
float
), # 1.Convert sparse matrix to floats
id_order=w_surface_sp.index.tolist() # 2b. Ensure `W` is indexed
)
)
w_surface_all.index = w_surface_sp.index # 4.Assign index to new `W`
# Convert `DataArray` to a `pandas.Series`
pop_values = pop.to_series()
# Subset to keep only values that aren't missing
#pop_values = pop_values[pop_values != pop.rio.nodata]
#pop.rio.nodata
w_surface = weights.w_subset(w_surface_all, pop_values.index)
w_surface.index = pop_values.index
# NOTE: this may take a bit longer to run depending on hardware
pop_lisa = Moran_Local(
pop_values.astype(float), w_surface, n_jobs=-1
)
[66]:
pop = s['sampleid_1_image_4'][4, :, :]
w_surface_sp = weights.Queen.from_xarray(pop)
w_surface_all = weights.WSP2W( # 3.Convert `WSP` object to `W`
weights.WSP( # 2a.Build `WSP` from the float sparse matrix
w_surface_sp.sparse.astype(
float
), # 1.Convert sparse matrix to floats
id_order=w_surface_sp.index.tolist() # 2b. Ensure `W` is indexed
)
)
w_surface_all.index = w_surface_sp.index # 4.Assign index to new `W`
# Convert `DataArray` to a `pandas.Series`
pop_values = pop.to_series()
# Subset to keep only values that aren't missing
#pop_values = pop_values[pop_values != pop.rio.nodata]
#pop.rio.nodata
w_surface = weights.w_subset(w_surface_all, pop_values.index)
w_surface.index = pop_values.index
# NOTE: this may take a bit longer to run depending on hardware
pop_lisa = Moran_Local(
pop_values.astype(float), w_surface, n_jobs=-1
)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[66], line 15
13 pop_values = pop.to_series()
14 # Subset to keep only values that aren't missing
---> 15 pop_values = pop_values[pop_values != pop.rio.nodata]
16 pop.rio.nodata
17 w_surface = weights.w_subset(w_surface_all, pop_values.index)
File e:\tbcr_pilot_data\envs\astropath_test\lib\site-packages\xarray\core\common.py:280, in AttrAccessMixin.__getattr__(self, name)
278 with suppress(KeyError):
279 return source[name]
--> 280 raise AttributeError(
281 f"{type(self).__name__!r} object has no attribute {name!r}"
282 )
AttributeError: 'DataArray' object has no attribute 'rio'
[68]:
pop_lisa
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[68], line 1
----> 1 pop_lisa
NameError: name 'pop_lisa' is not defined
[ ]:
canvas = ds.Canvas(plot_width=800, plot_height=800)
agg = canvas.points(db, geometry="geometry", agg=ds.mean(f"{expression}_Is"))
im = tf.shade(agg, cmap=cc.bkr, how="eq_hist")
tf.set_background(im, "black")
[ ]:
sig_pop = pandas.Series(
pop_lisa.q
* (
pop_lisa.p_sim < 0.01
), # Quadrant of significant at 1% (0 otherwise)
index=pop_values.index, # Index from the Series and aligned with `w_surface`
)
# Build `DataArray` from a set of values and weights
lisa_da = raster.w2da(
sig_pop, # Values
w_surface, # Spatial weights
attrs={
"nodatavals": [pop.rio.nodata]
} # Value for missing data
# Add CRS information in a compliant manner
).rio.write_crs(pop.rio.crs)
lisa_da.to_series().unique()
# LISA colors
lc = {
"ns": "lightgrey", # Values of 0
"HH": "#d7191c", # Values of 1
"LH": "#abd9e9", # Values of 2
"LL": "#2c7bb6", # Values of 3
"HL": "#fdae61", # Values of 4
}
# Set up figure and axis
f, axs = plt.subplots(1, 2, figsize=(12, 6))
# Subplot 1 #
# Select pixels that do not have the `nodata` value
# (ie. they are not missing data)
pop.where(
pop
!= pop.rio.nodata
# Plot surface with a horizontal colorbar
).plot(
ax=axs[0],
add_colorbar=False, # , cbar_kwargs={"orientation": "horizontal"}
)
# Subplot 2 #
# Select pixels with no missing data and rescale to [0, 1] by
# dividing by 4 (maximum value in `lisa_da`)
(
lisa_da.where(lisa_da != -200)
/ 4
# Plot surface without a colorbar
).plot(cmap=lisa_cmap, ax=axs[1], add_colorbar=False)
# Aesthetics #
# Subplot titles
titles = ["Population by pixel", "Population clusters"]
# Apply the following to each of the two subplots
for i in range(2):
# Keep proportion of axes
axs[i].axis("equal")
# Remove axis
axs[i].set_axis_off()
# Add title
axs[i].set_title(titles[i])
# Add basemap
contextily.add_basemap(axs[i], crs=lisa_da.rio.crs)