{"spec_id":"network-force-directed","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nnetwork-force-directed: Force-Directed Graph\nLibrary: bokeh 3.9.1 | Python 3.13.14\nQuality: 87/100 | Updated: 2026-07-01\n\"\"\"\n\n# Remove the script's own directory from sys.path so 'bokeh.py' doesn't shadow\n# the installed bokeh package (this file is named bokeh.py).\nimport os as _os\nimport sys as _sys\n\n\n_script_dir = _os.path.dirname(_os.path.abspath(__file__))\n_sys.path = [p for p in _sys.path if _os.path.abspath(p or \".\") != _script_dir]\ndel _sys, _os\n\nimport os\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Imprint palette — positions 1, 2, 3 for the three communities\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nANYPLOT_AMBER = \"#DDCC77\"  # bridge edges — cross-community connections\n\n# Data — 50-node company social network with 3 communities\nnp.random.seed(42)\n\ncommunity_sizes = [18, 17, 15]\ncommunity_names = [\"Engineering\", \"Marketing\", \"Sales\"]\ncommunity_colors = [IMPRINT_PALETTE[0], IMPRINT_PALETTE[1], IMPRINT_PALETTE[2]]\n\nnodes = []\nnode_id = 0\nfor comm_idx, size in enumerate(community_sizes):\n    for _ in range(size):\n        nodes.append({\"id\": node_id, \"community\": comm_idx})\n        node_id += 1\n\n# Intra-community edges (dense within each team)\nboundaries = [0, 18, 35, 50]\nintra_edges = []\nfor c in range(3):\n    start, end = boundaries[c], boundaries[c + 1]\n    for i in range(start, end):\n        for j in range(i + 1, end):\n            if np.random.random() < 0.3:\n                intra_edges.append((i, j))\n\n# Inter-community bridge edges (sparse — highlight cross-team links)\nbridge_edges = [(0, 18), (5, 20), (10, 25), (18, 35), (22, 40), (30, 45), (8, 38), (15, 48)]\nall_edges = intra_edges + bridge_edges\n\n# Force-directed layout (Fruchterman-Reingold)\nn = len(nodes)\npositions = np.random.rand(n, 2) * 2 - 1\nk = 0.5\niterations = 200\n\nfor iteration in range(iterations):\n    displacement = np.zeros((n, 2))\n    for i in range(n):\n        for j in range(i + 1, n):\n            diff = positions[i] - positions[j]\n            dist = max(np.linalg.norm(diff), 0.01)\n            repulsive = (k * k / dist) * (diff / dist)\n            displacement[i] += repulsive\n            displacement[j] -= repulsive\n    for src, tgt in all_edges:\n        diff = positions[src] - positions[tgt]\n        dist = max(np.linalg.norm(diff), 0.01)\n        attractive = (dist * dist / k) * (diff / dist)\n        displacement[src] -= attractive\n        displacement[tgt] += attractive\n    temperature = 1 - iteration / iterations\n    for i in range(n):\n        d = np.linalg.norm(displacement[i])\n        if d > 0:\n            positions[i] += (displacement[i] / d) * min(d, 0.15 * temperature)\n\n# Normalize positions to [0.05, 0.95]\npos_min = positions.min(axis=0)\npos_max = positions.max(axis=0)\npositions = (positions - pos_min) / (pos_max - pos_min + 1e-6) * 0.9 + 0.05\npos = {node[\"id\"]: positions[i] for i, node in enumerate(nodes)}\n\n# Node degrees\ndegrees = {node[\"id\"]: 0 for node in nodes}\nfor src, tgt in all_edges:\n    degrees[src] += 1\n    degrees[tgt] += 1\n\n# Figure — canonical 3200×1800 landscape, toolbar disabled for correct PNG dimensions\np = figure(\n    width=3200,\n    height=1800,\n    title=\"network-force-directed · python · bokeh · anyplot.ai\",\n    x_range=(-0.05, 1.05),\n    y_range=(-0.05, 1.05),\n    toolbar_location=None,\n    background_fill_color=PAGE_BG,\n    border_fill_color=PAGE_BG,\n    min_border_bottom=50,\n    min_border_left=50,\n    min_border_top=110,\n    min_border_right=50,\n)\n\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\np.title.align = \"center\"\np.axis.visible = False\np.grid.visible = False\np.outline_line_color = None\n\n# Intra-community edges — subtle, thin\np.segment(\n    x0=[pos[src][0] for src, _ in intra_edges],\n    y0=[pos[src][1] for src, _ in intra_edges],\n    x1=[pos[tgt][0] for _, tgt in intra_edges],\n    y1=[pos[tgt][1] for _, tgt in intra_edges],\n    line_color=INK_SOFT,\n    line_alpha=0.22,\n    line_width=1.5,\n)\n\n# Bridge edges — amber, dashed, more prominent to show cross-team connections\np.segment(\n    x0=[pos[src][0] for src, _ in bridge_edges],\n    y0=[pos[src][1] for src, _ in bridge_edges],\n    x1=[pos[tgt][0] for _, tgt in bridge_edges],\n    y1=[pos[tgt][1] for _, tgt in bridge_edges],\n    line_color=ANYPLOT_AMBER,\n    line_alpha=0.75,\n    line_width=3.0,\n    line_dash=\"dashed\",\n)\n\n# Nodes — one renderer per community for legend and hover\nnode_renderers = []\nfor comm_idx, color, name in zip(range(3), community_colors, community_names, strict=True):\n    comm_nodes = [node for node in nodes if node[\"community\"] == comm_idx]\n    x_vals = [pos[node[\"id\"]][0] for node in comm_nodes]\n    y_vals = [pos[node[\"id\"]][1] for node in comm_nodes]\n    size_vals = [16 + degrees[node[\"id\"]] * 2 for node in comm_nodes]\n    degree_vals = [degrees[node[\"id\"]] for node in comm_nodes]\n    node_ids = [node[\"id\"] for node in comm_nodes]\n\n    source = ColumnDataSource(\n        data={\n            \"x\": x_vals,\n            \"y\": y_vals,\n            \"size\": size_vals,\n            \"degree\": degree_vals,\n            \"node_id\": node_ids,\n            \"team\": [name] * len(comm_nodes),\n        }\n    )\n\n    renderer = p.scatter(\n        x=\"x\",\n        y=\"y\",\n        size=\"size\",\n        source=source,\n        fill_color=color,\n        fill_alpha=0.9,\n        line_color=PAGE_BG,\n        line_width=2,\n        legend_label=name,\n    )\n    node_renderers.append(renderer)\n\n# Hover tool scoped to node renderers\np.add_tools(\n    HoverTool(\n        renderers=node_renderers, tooltips=[(\"Team\", \"@team\"), (\"Node ID\", \"@node_id\"), (\"Connections\", \"@degree\")]\n    )\n)\n\n# Spotlight — draw a glow ring around the single highest-degree hub node\ntop_hub_id = max(degrees, key=degrees.get)\ntop_hub_x = pos[top_hub_id][0]\ntop_hub_y = pos[top_hub_id][1]\ntop_hub_size = 16 + degrees[top_hub_id] * 2\np.scatter(\n    x=[top_hub_x],\n    y=[top_hub_y],\n    size=[top_hub_size + 20],\n    fill_color=None,\n    line_color=ANYPLOT_AMBER,\n    line_width=4,\n    line_alpha=0.85,\n)\n\n# Hub labels — threshold 9 keeps only the top hubs to avoid label crowding\nhub_x, hub_y, hub_labels = [], [], []\nfor node in nodes:\n    if degrees[node[\"id\"]] >= 9:\n        hub_x.append(pos[node[\"id\"]][0])\n        hub_y.append(pos[node[\"id\"]][1] + 0.045)\n        hub_labels.append(\"Top Hub\" if node[\"id\"] == top_hub_id else \"Hub\")\n\nif hub_x:\n    hub_source = ColumnDataSource(data={\"x\": hub_x, \"y\": hub_y, \"text\": hub_labels})\n    p.text(\n        x=\"x\",\n        y=\"y\",\n        text=\"text\",\n        source=hub_source,\n        text_font_size=\"24pt\",\n        text_font_style=\"bold\",\n        text_align=\"center\",\n        text_baseline=\"bottom\",\n        text_color=INK,\n    )\n\n# Legend — inside plot frame, top-left\np.legend.title = \"Teams\"\np.legend.location = \"top_left\"\np.legend.label_text_font_size = \"34pt\"\np.legend.title_text_font_size = \"34pt\"\np.legend.label_text_color = INK_SOFT\np.legend.title_text_color = INK\np.legend.background_fill_color = ELEVATED_BG\np.legend.background_fill_alpha = 0.95\np.legend.border_line_color = INK_SOFT\np.legend.border_line_alpha = 0.4\np.legend.spacing = 12\np.legend.padding = 20\np.legend.margin = 28\np.legend.glyph_height = 32\np.legend.glyph_width = 32\n\n# Save HTML (interactive artifact)\noutput_file(f\"plot-{THEME}.html\", title=\"network-force-directed · python · bokeh · anyplot.ai\")\nsave(p)\n\n# Screenshot via headless Chrome — CDP sets exact viewport (set_window_size alone is insufficient)\nW, H = 3200, 1800\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}