76 lines
2.7 KiB
Python
76 lines
2.7 KiB
Python
import math
|
|
|
|
import matplotlib.pyplot as plt
|
|
import numpy as np
|
|
from graph_tool.all import *
|
|
|
|
from src import centrality
|
|
from src import plot
|
|
|
|
|
|
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, ax2, method):
|
|
# calculate centrality values
|
|
vp, ep = method(g, weight=weight)
|
|
vp.a = np.nan_to_num(vp.a) # correct floating point values
|
|
min_val, max_val = vp.a.min(), vp.a.max()
|
|
vp.a = (vp.a - min_val) / (max_val - min_val)
|
|
|
|
# euklidian distance
|
|
quantification = plot.quantification_data(g, vp, convex_hull)
|
|
plot.quantification_plot(ax, quantification, None, None, "Euklidian Distance", None)
|
|
|
|
# generate model based on convex hull and associated centrality values
|
|
# path distance (node based centrality)
|
|
quantification = plot.quantification_data_node_path_distance(g, weight, vp, convex_hull)
|
|
plot.quantification_plot(ax2, quantification, None, None, "Shortest Path Distance", None)
|
|
|
|
|
|
points, seed = random_graph(n=5000, seed=77011137629244244786159039169016117129)
|
|
g, weight = spatial_graph(points)
|
|
g = GraphView(g)
|
|
# calculate convex hull
|
|
convex_hull = centrality.convex_hull(g)
|
|
|
|
fig = plt.figure(figsize=(21, 5))
|
|
ax1, ax2, ax3 = fig.subplots(1, 3)
|
|
|
|
# plot graph with convex_hull
|
|
vp, ep = betweenness(g, weight=weight)
|
|
vp.a = np.nan_to_num(vp.a) # correct floating point values
|
|
min_val, max_val = vp.a.min(), vp.a.max()
|
|
vp.a = (vp.a - min_val) / (max_val - min_val)
|
|
|
|
plot.graph_plot(fig, ax1, g, vp, convex_hull, f"Pointcloud (seed: {seed})", False)
|
|
|
|
apply(g, seed, weight, convex_hull, ax2, ax3, betweenness)
|
|
|
|
fig.savefig(f"Distance_5000_node_betweenness.svg", format='svg')
|