From 590a15394df2dc3f5d88d18656c1b83bdf7c6133 Mon Sep 17 00:00:00 2001 From: zuiidea Date: Wed, 17 Mar 2021 15:55:31 +0800 Subject: [PATCH] feat: support returning the same cluster id when executing the same data --- packages/graph/src/louvain.ts | 20 ++++++++++++++++---- packages/graph/src/types.ts | 4 ++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/graph/src/louvain.ts b/packages/graph/src/louvain.ts index 65e1cb3..ac9aeac 100644 --- a/packages/graph/src/louvain.ts +++ b/packages/graph/src/louvain.ts @@ -1,6 +1,5 @@ import getAdjMatrix from './adjacent-matrix' -import { uniqueId } from './util'; -import { NodeConfig, ClusterData, GraphData } from './types'; +import { NodeConfig, ClusterData, GraphData, ClusterMap } from './types'; const getModularity = ( nodes: NodeConfig[], @@ -41,12 +40,13 @@ const louvain = ( ): ClusterData => { // the origin data const { nodes = [], edges = [] } = graphData; + let uniqueId = 1; - const clusters = {}; + const clusters: ClusterMap = {}; const nodeMap = {}; // init the clusters and nodeMap nodes.forEach((node, i) => { - const cid: string = uniqueId(); + const cid: string = String(uniqueId++); node.clusterId = cid; clusters[cid] = { id: cid, @@ -210,6 +210,18 @@ const louvain = ( } }); + Object.keys(clusters).forEach((clusterId, index) => { + const cluster = clusters[clusterId]; + const newId = String(index + 1); + if (newId === clusterId) { + return; + } + cluster.id = newId; + cluster.nodes = cluster.nodes.map(item => ({ id: item.id, clusterId: newId })); + clusters[newId] = cluster; + delete clusters[clusterId]; + }); + // get the cluster edges const clusterEdges = []; const clusterEdgeMap = {}; diff --git a/packages/graph/src/types.ts b/packages/graph/src/types.ts index 25afab2..3f22dde 100644 --- a/packages/graph/src/types.ts +++ b/packages/graph/src/types.ts @@ -30,6 +30,10 @@ export interface ClusterData { clusterEdges: EdgeConfig[]; } +export interface ClusterMap { + [key: string]: Cluster +} + // 图算法回调方法接口定义 export interface IAlgorithmCallbacks { enter?: (param: { current: string; previous: string }) => void;