Skip to content

Graph

Graph analysis

Connected components, communities, centrality and PageRank of a synthetic supplier network, shown with groups, collapsing and highlighting.

Live demoView on GitHub ↗

Graph analysis

Components, communities and node rankings of a synthetic supplier network.

Summary: 142 nodes, 298 edges, 3 components, 8 communities, modularity 0.77

S1-01 S1-01S1-02 S1-02S1-03 S1-03S1-04 S1-04S1-05 S1-05S1-06 S1-06S1-07 S1-07S1-08 S1-08S1-09 S1-09S1-10 S1-10S1-11 S1-11S1-12 S1-12S1-13 S1-13S1-14 S1-14S1-15 S1-15S1-16 S1-16S1-17 S1-17S1-18 S1-18S1-19 S1-19S1-20 S1-20S1-21 S1-21S1-22 S1-22S1-23 S1-23S1-24 S1-24S1-25 S1-25S1-26 S1-26S2-01 S2-01S2-02 S2-02S2-03 S2-03S2-04 S2-04S2-05 S2-05S2-06 S2-06S2-07 S2-07S2-08 S2-08S2-09 S2-09S2-10 S2-10S2-11 S2-11S2-12 S2-12S2-13 S2-13S2-14 S2-14S2-15 S2-15S2-16 S2-16S2-17 S2-17S2-18 S2-18S2-19 S2-19S2-20 S2-20S2-21 S2-21S2-22 S2-22S2-23 S2-23S2-24 S2-24S3-01 S3-01S3-02 S3-02S3-03 S3-03S3-04 S3-04S3-05 S3-05S3-06 S3-06S3-07 S3-07S3-08 S3-08S3-09 S3-09S3-10 S3-10S3-11 S3-11S3-12 S3-12S3-13 S3-13S3-14 S3-14S3-15 S3-15S3-16 S3-16S3-17 S3-17S3-18 S3-18S3-19 S3-19S3-20 S3-20S3-21 S3-21S3-22 S3-22S4-01 S4-01S4-02 S4-02S4-03 S4-03S4-04 S4-04S4-05 S4-05S4-06 S4-06S4-07 S4-07S4-08 S4-08S4-09 S4-09S4-10 S4-10S4-11 S4-11S4-12 S4-12S4-13 S4-13S4-14 S4-14S4-15 S4-15S4-16 S4-16S4-17 S4-17S4-18 S4-18S4-19 S4-19S4-20 S4-20S4-21 S4-21S4-22 S4-22S5-01 S5-01S5-02 S5-02S5-03 S5-03S5-04 S5-04S5-05 S5-05S5-06 S5-06S5-07 S5-07S5-08 S5-08S5-09 S5-09S5-10 S5-10S5-11 S5-11S5-12 S5-12S5-13 S5-13S5-14 S5-14S5-15 S5-15S5-16 S5-16S5-17 S5-17S5-18 S5-18S5-19 S5-19S5-20 S5-20S6-01 S6-01S6-02 S6-02S6-03 S6-03S6-04 S6-04S6-05 S6-05S6-06 S6-06S6-07 S6-07S6-08 S6-08S6-09 S6-09S6-10 S6-10S6-11 S6-11S6-12 S6-12S6-13 S6-13S6-14 S6-14S6-15 S6-15S6-16 S6-16S6-17 S6-17S6-18 S6-18X1-1 X1-1X1-2 X1-2X1-3 X1-3X1-4 X1-4X1-5 X1-5X1-6 X1-6X2-1 X2-1X2-2 X2-2X2-3 X2-3X2-4 X2-4
12%

Choose a ranking to highlight the five most central suppliers.

Drag the lower-right corner of the demo to change its height.

Source code

vue
<script setup lang="ts">
// Graph analysis on a synthetic supplier network: connected components, community detection, centrality and PageRank
// from `@eightkk/vue-weave/core`, shown with NetworkGraph groups, collapsing and highlighting. The data comes from a seeded
// generator and the metrics are pure functions of it, so each one is computed once and cached.
import { computed, nextTick, ref } from 'vue'
import {
  NetworkGraph, detectGraphCommunities, graphBetweennessCentrality, graphCommunityGroups, graphComponents,
  graphDegreeCentrality, graphPageRank, layoutForceGraph,
  type GraphEdge, type GraphLayoutFunction, type NetworkNode,
} from '../src'
import DemoPanel from './components/DemoPanel.vue'
import StatusLine from './components/StatusLine.vue'
import { useDemoLocale } from './i18n'

const { t, labels } = useDemoLocale()

// mulberry32: a small deterministic PRNG, so the demo and its tests see the same network every time.
function seeded(seed: number) {
  let state = seed >>> 0
  return () => {
    state = (state + 0x6D2B79F5) >>> 0
    let t = state
    t = Math.imul(t ^ (t >>> 15), t | 1)
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

function buildNetwork() {
  const random = seeded(2024)
  const nodes: NetworkNode[] = []
  const edges: GraphEdge[] = []
  const seen = new Set<string>()
  const tones = ['teal', 'blue', 'violet'] as const
  const link = (a: string, b: string) => {
    const key = a < b ? a + '|' + b : b + '|' + a
    if (a === b || seen.has(key)) return false
    seen.add(key)
    edges.push({ id: `${a}-${b}`, from: a, to: b, markerEnd: 'none' })
    return true
  }
  // Six regional clusters with dense links inside and a few links between neighbouring regions.
  const clusters: string[][] = []
  const sizes = [26, 24, 22, 22, 20, 18]
  sizes.forEach((size, region) => {
    const ids: string[] = []
    for (let i = 0; i < size; i++) {
      const id = `s${region + 1}-${String(i + 1).padStart(2, '0')}`
      ids.push(id)
      nodes.push({ id, label: id.toUpperCase(), tone: tones[region % tones.length] })
    }
    for (let i = 1; i < ids.length; i++) {
      link(ids[Math.floor(random() * i)]!, ids[i]!)
      for (let extra = 0; extra < 2; extra++) if (random() < 0.7) link(ids[i]!, ids[Math.floor(random() * i)]!)
    }
    clusters.push(ids)
  })
  for (let region = 0; region < clusters.length; region++) {
    const next = clusters[(region + 1) % clusters.length]!
    for (let k = 0; k < 3; k++) link(clusters[region]![Math.floor(random() * clusters[region]!.length)]!, next[Math.floor(random() * next.length)]!)
  }
  // Two small groups of suppliers that are not connected to the main network.
  for (const [name, size] of [['x1', 6], ['x2', 4]] as const) {
    const ids: string[] = []
    for (let i = 0; i < size; i++) {
      const id = `${name}-${i + 1}`
      ids.push(id)
      nodes.push({ id, label: id.toUpperCase(), tone: 'blue' })
      if (i) link(ids[Math.floor(random() * i)]!, id)
    }
  }
  return { nodes, edges }
}

const { nodes, edges } = buildNetwork()
const labelOf = new Map(nodes.map(node => [node.id, node.label]))
const nodeSettings = { nodeWidth: 76, nodeHeight: 30 }
// One stable layout function: the force layout is seeded, so the picture never changes between runs.
const layout: GraphLayoutFunction = (n, e) => layoutForceGraph(n, e, { seed: 1, ...nodeSettings, linkDistance: 110 })

const components = graphComponents(nodes, edges)
const { communities, modularity } = detectGraphCommunities(nodes, edges)
const groups = graphCommunityGroups(communities, {
  idPrefix: 'community-',
  label: (members, index) => t({ en: `Community ${index + 1} · ${members.length} nodes`, ja: `コミュニティ ${index + 1} · ${members.length} ノード` }),
  minSize: 2,
})
const groupOfNode = new Map<string, string>()
for (const group of groups) for (const id of group.nodeIds) groupOfNode.set(id, group.id)
const summary = t({
  en: `${nodes.length} nodes, ${edges.length} edges, ${components.length} components, ${communities.length} communities, modularity ${modularity.toFixed(2)}`,
  ja: `ノード ${nodes.length}、辺 ${edges.length}、連結成分 ${components.length}、コミュニティ ${communities.length}、モジュラリティ ${modularity.toFixed(2)}`,
})

type Metric = 'none' | 'degree' | 'betweenness' | 'pagerank'
const metricNames: Record<Exclude<Metric, 'none'>, string> = t({
  en: { degree: 'Degree', betweenness: 'Betweenness', pagerank: 'PageRank' },
  ja: { degree: '次数', betweenness: '媒介中心性', pagerank: 'PageRank' },
})
const cache = new Map<Metric, ReadonlyMap<string, number>>()
function scoresFor(metric: Metric): ReadonlyMap<string, number> {
  let scores = cache.get(metric)
  if (!scores) {
    scores = metric === 'degree' ? graphDegreeCentrality(nodes, edges)
      : metric === 'betweenness' ? graphBetweennessCentrality(nodes, edges, { directed: false })
        : metric === 'pagerank' ? graphPageRank(nodes, edges).scores : new Map()
    cache.set(metric, scores)
  }
  return scores
}

const grouped = ref(false)
const collapsed = ref<ReadonlySet<string>>(new Set())
const rankBy = ref<Metric>('none')
const graph = ref<InstanceType<typeof NetworkGraph>>()
const status = ref(t({ en: 'Choose a ranking to highlight the five most central suppliers.', ja: '順位の基準を選ぶと、中心性の高い上位5社を強調表示します。' }))

const top = computed(() => rankBy.value === 'none' ? [] : [...scoresFor(rankBy.value)]
  .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 5).map(([id, score]) => ({ id, label: labelOf.get(id)!, score })))
const highlighted = computed<ReadonlySet<string>>(() => new Set(top.value.map(entry => entry.id)))
const shownGroups = computed(() => grouped.value ? groups : undefined)
const shownCollapsed = computed(() => grouped.value ? collapsed.value : new Set<string>())

function formatScore(score: number) {
  return rankBy.value === 'degree' ? String(score) : score.toFixed(rankBy.value === 'pagerank' ? 4 : 3)
}
function collapseAll() { collapsed.value = new Set(groups.map(group => group.id)) }
function expandAll() { collapsed.value = new Set() }

async function focus(id: string) {
  const group = groupOfNode.get(id)
  if (group && shownCollapsed.value.has(group)) {
    collapsed.value = new Set([...collapsed.value].filter(item => item !== group))
    await nextTick()
  }
  try {
    graph.value?.focusNode(id)
    status.value = t({ en: `Centered on ${labelOf.get(id)}.`, ja: `${labelOf.get(id)} を中央に表示しました。` })
  } catch (error) {
    status.value = error instanceof Error ? error.message : String(error)
  }
}
</script>

<template>
  <DemoPanel title-id="analysis-title" :title="t({ en: 'Graph analysis', ja: 'グラフ分析' })" :subtitle="t({ en: 'Components, communities and node rankings of a synthetic supplier network.', ja: '架空の仕入先ネットワークの連結成分、コミュニティ、ノードの順位です。' })">
    <p class="hint">{{ t({ en: 'Summary:', ja: '概要:' }) }} <output :aria-label="t({ en: 'Network summary', ja: 'ネットワークの概要' })">{{ summary }}</output></p>
    <div class="options analysis-options" role="group" :aria-label="t({ en: 'Analysis options', ja: '分析のオプション' })">
      <label><input v-model="grouped" type="checkbox"> {{ t({ en: 'Group communities', ja: 'コミュニティでグループ化' }) }}</label>
      <button type="button" :disabled="!grouped" @click="collapseAll">{{ t({ en: 'Collapse all', ja: 'すべて折りたたむ' }) }}</button>
      <button type="button" :disabled="!grouped" @click="expandAll">{{ t({ en: 'Expand all', ja: 'すべて展開' }) }}</button>
      <label>{{ t({ en: 'Rank by', ja: '順位の基準' }) }}
        <select v-model="rankBy" :aria-label="t({ en: 'Rank by', ja: '順位の基準' })">
          <option value="none">{{ t({ en: 'None', ja: 'なし' }) }}</option>
          <option value="degree">{{ t({ en: 'Degree', ja: '次数' }) }}</option>
          <option value="betweenness">{{ t({ en: 'Betweenness', ja: '媒介中心性' }) }}</option>
          <option value="pagerank">PageRank</option>
        </select>
      </label>
    </div>
    <NetworkGraph ref="graph" :nodes="nodes" :edges="edges" :layout="layout" :options="nodeSettings"
      :groups="shownGroups" :collapsed-group-ids="shownCollapsed" collapsible-groups
      :highlighted-node-ids="highlighted" :height="480" :show-minimap="true"
      :labels="{ ...labels.graph, region: t({ en: 'Supplier network', ja: '仕入先ネットワーク' }) }" @update:collapsed-group-ids="collapsed = $event" />
    <StatusLine :label="t({ en: 'Analysis status', ja: '分析の状態' })">{{ status }}</StatusLine>
    <template v-if="top.length">
      <p class="hint">{{ t({ en: `Top 5 by ${metricNames[rankBy as Exclude<Metric, 'none'>]}:`, ja: `${metricNames[rankBy as Exclude<Metric, 'none'>]}の上位5件:` }) }}</p>
      <ol class="analysis-ranking" :aria-label="t({ en: 'Top ranked nodes', ja: '上位のノード' })">
        <li v-for="entry in top" :key="entry.id">
          <button type="button" @click="focus(entry.id)">{{ entry.label }}</button> <span>{{ formatScore(entry.score) }}</span>
        </li>
      </ol>
    </template>
  </DemoPanel>
</template>

<style scoped>
.analysis-options { flex-wrap: wrap; gap: 10px 16px; margin-bottom: 8px; }
.analysis-ranking { margin: 4px 0 0; padding-left: 24px; font-size: 12px; color: var(--vw-muted, #4f6574); display: grid; gap: 4px; }
.analysis-ranking span { margin-inline-start: 6px; }
</style>

Released under the MIT License.