Files
boundary-aware-centrality/point_cloud_example.py
Yves Biener 7581966c88 WIP different small python scripts to generate corresponding images
The final API will be derived from these scripts into a different
repository, which then only holds the corresponding functions that
provide the corresponding functionalities described in the associated
master thesis.
2026-03-28 15:04:38 +01:00

77 lines
2.5 KiB
Python

import math
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np
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 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
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)
g = GraphView(g)
# plot graph with convex_hull
fig_graph, ax_graph = plt.subplots(figsize=(15, 12))
draw_graph(g, ax_graph, f"Pointcould (seed: {seed} | n: 500)")
fig_graph.savefig("point_cloud_example.svg", format='svg')