Skip to content

feat(louvain): support returning the same cluster id #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions packages/graph/src/louvain.ts
Original file line number Diff line number Diff line change
@@ -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[],
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 = {};
Expand Down
4 changes: 4 additions & 0 deletions packages/graph/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down