import math import matplotlib.pyplot as plt import numpy as np from graph_tool.all import * from src import centrality from src import plot from src import fitting 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 # 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 quantification = plot.quantification_data_path_distance(g, weight, vp, convex_hull) plot.quantification_plot(ax2, quantification, None, None, "Shortest Path Distance", None) points, seed = random_graph(n=5000) 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 # draw without any centrality measure `vp` vp, ep = betweenness(g, weight=weight) vp.a = np.nan_to_num(vp.a) # correct floating point values plot.graph_plot(fig, ax1, g, vp, convex_hull, f"Pointcloud (seed: {seed})") apply(g, seed, weight, convex_hull, ax2, ax3, betweenness) fig.savefig(f"Distance_5000_betweenness_euklidian.svg", format='svg')