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

104 lines
3.2 KiB
Python

import math
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np
import squidpy as sq
from graph_tool.all import *
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 mibitof():
"""
Mibitof dataset from `squidpy`.
"""
adata = sq.datasets.mibitof()
return adata
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 draw_graph(G, ax, name):
pos = G.vp["pos"]
x = []
y = []
for v in G.vertices():
# print(pos[v])
ver = pos[v]
x.append(ver[0])
y.append(ver[1])
# convex hull -> Bounding-Box
# ch = LineCollection([convex_hull], colors=['g'], linewidths=1)
# ax.add_collection(ch)
# edges
for e in G.edges():
ex = [pos[e.source()][0], pos[e.target()][0]]
ey = [pos[e.source()][1], pos[e.target()][1]]
ax.add_collection(LineCollection([np.column_stack([ex, ey])], colors=['k'], linewidths=0.1))
ax.scatter(x, y, s=1) # map closeness values as color mapping on the verticies
# for v in G.vertices():
# neighbours = g.get_all_neighbours(v)
# if len(neighbours) == 0:
# ax.scatter(pos[v][0], pos[v][1], s=1, color=['r'])
ax.set_title(name)
#
# - 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=3000)
# g, weight = spatial_graph(points)
adata = mibitof()
g, weight = spatial_graph(adata.obsm['spatial'])
g = GraphView(g)
for v in g.vertices():
neighbours = g.get_all_neighbours(v)
if len(neighbours) == 0:
g.remove_vertex(v)
break
pos = g.vp["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
# plot graph with convex_hull
fig_graph, ax_graph = plt.subplots(figsize=(15, 12))
draw_graph(g, ax_graph, f"mibitof")
fig_graph.savefig("mibitof_graph.svg", format='svg')