Files
boundary-aware-centrality/comparison_edge_scores.py
2026-04-16 07:20:19 +02:00

175 lines
5.5 KiB
Python

import math
import matplotlib.pyplot as plt
import numpy as np
import squidpy as sq
from graph_tool.all import *
from src import centrality
from src import plot
from src import fitting
def merfish():
"""
Merfish dataset from `squidpy`.
"""
adata = sq.datasets.merfish()
adata = adata[adata.obs.Bregma == -9].copy()
return adata
def mibitof():
"""
Mibitof dataset from `squidpy`.
"""
adata = sq.datasets.mibitof()
return adata
def degree(g, weight):
# VertexPropertyMap
vp = g.new_vertex_property("double")
for v in g.vertices():
neighbours = g.get_all_neighbours(v)
vp[v] = len(neighbours)
return vp
def leverage(g, weight):
# VertexPropertyMap
vp = g.new_vertex_property("double")
for v in g.vertices():
li = 0.0
neighbours = g.get_all_neighbours(v)
ki = len(neighbours)
if ki == 0:
continue
# sum
for nv in neighbours:
other_neighbours = g.get_all_neighbours(nv)
kj = len(other_neighbours)
li += (ki - kj) / (ki + kj)
li /= ki
vp[v] = li
return vp
def path(g, weight):
# NOTE is this not just betweenness?
ep = g.new_vertex_property("double")
for v in g.vertices():
for u in g.vertices():
if (v == u):
continue
paths = graph_tool.topology.all_shortest_paths(g, v, u, weights=weight, edges=True)
for edges in paths:
for edge in edges:
for idx, g_e in enumerate(g.edges()):
if (g_e == edge):
# NOTE we end up counting twice!
ep[idx] += 0.5;
break
# for e in g.edges():
# ep[e] /= 2;
return ep
def random_graph(n=5000, seed=None):
"""
Uniformly random point cloud generation.
`n` [int] Number of points to generate. Default 5000 seems like a good starting point in point density and corresponding runtime for the subsequent calculations.
@return [numpy.ndarray] Array of shape(n, 2) containing the coordinates for each point of the generated point cloud.
"""
if seed is None:
import secrets
seed = secrets.randbits(128)
rng = np.random.default_rng(seed=seed)
return rng.random((n, 2)), seed
def spatial_graph(adata):
"""
Generate the spatial graph using delaunay for the given `adata`.
`adata` will contain the calculated spatial graph contents in the keys
adata.obsm['spatial']` in case the `adata` is created from a dataset of *squidpy*.
@return [Graph] generated networkx graph from adata.obsp['spatial_distances']
"""
g, pos = graph_tool.generation.triangulation(adata, type="delaunay")
g.vp["pos"] = pos
weight = g.new_edge_property("double")
for e in g.edges():
weight[e] = math.sqrt(sum(map(abs, pos[e.source()].a - pos[e.target()].a)))**2
return g, weight
def apply(g, seed, weight, convex_hull, ax, method, method_name):
# calculate centrality values
ep = None
if method_name == "Betweeness":
vp, ep = method(g, weight=weight)
else:
ep = method(g, weight=weight)
ep.a = np.nan_to_num(ep.a) # correct floating point values
# normalization
min_val, max_val = ep.a.min(), ep.a.max()
ep.a = (ep.a - min_val) / (max_val - min_val)
quantification = plot.quantification_data_edges(g, ep, convex_hull)
# optimize model's piece-wise linear function
d = quantification[:, 0]
C = quantification[:, 1]
m_opt, c0_opt, b_opt, aic_opt = fitting.fit_piece_wise_linear(d, C)
# TODO
# should this be part of the plotting function itself, it should not be necessary for me to do this
d_curve = np.linspace(min(d), max(d), 500)
C_curve = np.piecewise(
d_curve,
[d_curve <= b_opt, d_curve > b_opt],
[lambda x: m_opt * x + c0_opt, lambda x: m_opt * b_opt + c0_opt]
)
# plot model containing modeled piece-wise linear function
plot.quantification_plot(ax, quantification, d_curve, C_curve, method_name, aic_opt)
#
# - Create a random point cloud and calculate a triangulation on it
# - For that graph calculate the convex hull
# - Draw the graph with the convex hull
# - For each centrality measure
# - apply centrality measure to the next axis
# - Draw the corresponding resulting models into a grid
#
points, seed = random_graph(n=5000)
g, weight = spatial_graph(points)
g = GraphView(g)
# calculate convex hull
convex_hull = centrality.convex_hull(g)
# plot graph with convex_hull
fig_graph, ax_graph = plt.subplots(figsize=(15, 12))
# draw without any centrality measure `ep`
ep = g.new_edge_property("double")
plot.graph_plot(fig_graph, ax_graph, g, ep, convex_hull, f"Pointcould (seed: {seed})", True) # draw edges
fig_graph.savefig(f"comparison_edge_scores_artificial_graph.svg", format='svg')
fig = plt.figure(figsize=(15, 12))
row1, row2 = fig.subplots(2, 4)
# TODO run, betweenness, k-path, eigenedge, etc.
# - some share similarities to the node based counter parts
ax1, ax2, ax3, ax4 = row1
apply(g, None, weight, convex_hull, ax1, betweenness, "Betweeness")
# ax1, ax2, ax3, ax4 = row2
# apply(g, None, weight, convex_hull, ax1, katz, "Katz")
# apply(g, None, weight, convex_hull, ax2, hits, "Hits")
# apply(g, None, weight, convex_hull, ax3, leverage, "Leverage")
# apply(g, None, weight, convex_hull, ax4, degree, "Degree")
fig.savefig(f"Comparison_edge_centralities_artificial_.svg", format='svg')