feat: introduce weighting and popularity

This commit is contained in:
2025-02-12 15:39:52 +01:00
parent a34c88c18c
commit 3ec065aaf9
3 changed files with 45 additions and 18 deletions

View File

@@ -69,8 +69,8 @@ def sociogram_data():
.join(subquery, (C.user == subquery.c.user) & (C.time == subquery.c.latest))
)
for c in session.exec(statement2):
for p in c.love:
G.add_edge(c.user, p)
for i, p in enumerate(c.love):
G.add_edge(c.user, p, rank=i, popularity=1 - 0.08 * i)
links.append({"source": c.user, "target": p})
return G
@@ -81,10 +81,11 @@ class Params(BaseModel):
arrow_size: int | None = Field(default=20, alias="arrowSize")
edge_width: float | None = Field(default=1, alias="edgeWidth")
distance: float | None = 0.2
weighting: bool | None = True
popularity: bool | None = True
async def render_sociogram(params: Params):
plt.close()
plt.figure(figsize=(16, 10), facecolor="none")
ax = plt.gca()
ax.set_facecolor("none") # Set the axis face color to none (transparent)
@@ -92,15 +93,21 @@ async def render_sociogram(params: Params):
G = sociogram_data()
pos = nx.spring_layout(G, scale=2, k=params.distance, iterations=50, seed=None)
nx.draw_networkx_nodes(
nodes = nx.draw_networkx_nodes(
G,
pos,
node_color="#99ccff",
node_color=[v for k, v in G.in_degree(weight="popularity")]
if params.popularity
else "#99ccff",
edgecolors="#404040",
linewidths=1,
linewidths=0,
# node_shape="8",
node_size=params.node_size,
cmap="coolwarm",
alpha=0.86,
)
if params.popularity:
plt.colorbar(nodes)
nx.draw_networkx_labels(G, pos, font_size=params.font_size)
nx.draw_networkx_edges(
G,
@@ -110,6 +117,11 @@ async def render_sociogram(params: Params):
arrowsize=params.arrow_size,
node_size=params.node_size,
width=params.edge_width,
arrowstyle="-|>",
# connectionstyle="arc3,rad=0.2",
alpha=[1 - 0.08 * G.edges()[*edge]["rank"] for edge in G.edges()]
if params.weighting
else 1,
)
buf = io.BytesIO()
@@ -130,13 +142,3 @@ if __name__ == "__main__":
print("players in DB: ", session.exec(statement).first())
G = sociogram_data()
pos = nx.spring_layout(G, scale=1, k=2, iterations=50, seed=42)
edges = nx.draw_networkx_edges(
G,
pos,
arrows=True,
arrowsize=12,
)
nx.draw_networkx(
G, pos, with_labels=True, node_color="#99ccff", font_size=8, node_size=2000
)
plt.show()