用法
度数是同步的计算属性,中心性与社区是异步的:
<script setup lang="ts">
import type { StylesDeclaration } from 'sigma/types'
const { data } = await useFetch('/api/data.json')
const COMMUNITY_COLORS: Record<number, string> = Object.fromEntries(
['#f43f5e', '#3b82f6', '#22c55e', '#a855f7', '#f59e0b', '#14b8a6'].map((color, index) => [index, color])
)
const styles: StylesDeclaration = {
nodes: {
size: attributes => (attributes.metric === undefined
? attributes.size as number
: 4 + (attributes.metric as number) * 22),
color: attributes => COMMUNITY_COLORS[attributes.community as number] ?? attributes.color as string
}
}
</script>
<template>
<SigmaGraph :data="data" :styles="styles">
<UseSigmaMetricsPanel />
</SigmaGraph>
</template>
UseSigmaMetricsPanel.vue
<script setup lang="ts">
const { degrees, maxDegree, centrality, communities } = useSigmaMetrics()
const scores = await centrality('betweenness')
const partition = await communities()
</script>
示例
指标算完写回属性,视觉映射交给 styles
数值走 min / max 线性映射,分类走 dict 查表:
const partition = await communities()
for (const [node, community] of Object.entries(partition)) {
graph.setNodeAttribute(node, 'community', community)
}
const styles = {
nodes: {
size: { attribute: 'degree', min: 0, max: maxDegree.value, minValue: 4, maxValue: 24 },
color: { attribute: 'community', dict: { 0: '#f43f5e', 1: '#3b82f6' }, defaultValue: '#666' }
}
}
degree 不走可选依赖
centrality('degree') 直接短路到 degrees——用核心 graphology 就能算,不引入额外依赖,也不进缓存(它本身就是计算属性,已经随版本缓存了)。degrees 与 maxDegree 随图变更自动重算,空图时 maxDegree 为 0。
按图版本缓存
betweenness、closeness、louvain 都是 O(n·m) 量级的开销,结果按 ${kind}@${version} 缓存——同一版本内重复调用不重算,图一变就自然失效。
缓存不做淘汰。图频繁变更且反复调用这些指标时,每个版本都会留下一份结果,直到 composable 的作用域销毁。万级图上这可能是可观的内存,需要长时间运行的场景请自己节流调用频率。
三个重指标都依赖可选 peer,用到时才动态导入,未安装时抛出的错误里带有安装命令:
centrality('betweenness') / centrality('closeness') → graphology-metrics,communities() → graphology-communities-louvain。graphology-metrics@2.4.0 的 betweenness 在分叉节点上偏低,首个插入的节点恒为 0。依赖它做判断(排序取头部、卡阈值)之前请自行核对结果。API
useSigmaMetrics()
useSigmaMetrics(): UseSigmaMetricsReturn
无选项。
Returns
degrees
ComputedRef<Record<string, number>>
各节点的度数,随图变更重算。
maxDegree
ComputedRef<number>
最大度数,度数映射到尺寸时作分母。空图时为
0。centrality()
(kind?: SigmaCentralityKind) => Promise<Record<string, number>>
中心性,按图版本缓存。
kind 默认 'degree',此时直接返回 degrees 的值,不加载任何可选依赖。communities()
() => Promise<Record<string, number>>
Louvain 社区划分,返回节点到社区编号的映射,同样按版本缓存。
SigmaCentralityKind 的取值为 'degree' | 'betweenness' | 'closeness'。类型从根出口取:
import type { SigmaCentralityKind, UseSigmaMetricsReturn } from '@movk/sigma'