Bookmark this: tool.io/clustering/birch-microclusters/source-code
BIRCH Microclustering Demonstrator Source Code
Browse the implementation files for BIRCH Microclustering Demonstrator.tool.ts typescript
import { parseFiniteNumberList } from '../../parse/numeric-dataset/tool';
import { parseFiniteNumber } from '../../parse/number/tool';
type Cluster = {
count: number;
centroid: number[];
points: number[][];
};
const distance = (first: number[], second: number[]): number =>
Math.hypot(
...first.map((value, index) => value - second[index])
);
const centroid = (points: number[][]): number[] =>
points[0].map(
(_, dimension) =>
points.reduce((sum, point) => sum + point[dimension], 0) /
points.length
);
const radius = (points: number[][], center: number[]): number =>
Math.max(...points.map((point) => distance(point, center)));
export const createBirchMicroclusters = (
pointsInput: unknown,
thresholdInput: unknown
): string => {
if (typeof pointsInput !== 'string') return '';
const threshold = parseFiniteNumber(thresholdInput);
const points = pointsInput
.trim()
.split(/\n+/)
.map(parseFiniteNumberList);
if (
threshold === null ||
threshold < 0 ||
points.length === 0 ||
points.some((point) => !point) ||
new Set(points.map((point) => point!.length)).size !== 1
)
return '';
const clusters: Cluster[] = [];
for (const point of points as number[][]) {
const nearest = clusters
.map((cluster, index) => ({
index,
distance: distance(point, cluster.centroid)
}))
.sort((a, b) => a.distance - b.distance)[0];
if (nearest) {
const candidatePoints = [
...clusters[nearest.index].points,
point
];
const candidateCentroid = centroid(candidatePoints);
if (
radius(candidatePoints, candidateCentroid) <= threshold
) {
clusters[nearest.index] = {
count: candidatePoints.length,
centroid: candidateCentroid,
points: candidatePoints
};
continue;
}
}
clusters.push({
count: 1,
centroid: [...point],
points: [point]
});
}
return JSON.stringify(
{
clusterCount: clusters.length,
clusters: clusters.map(({ count, centroid: center }) => ({
centroid: center.map((value) =>
Number(value.toPrecision(10))
),
count
})),
threshold
},
null,
2
);
};
export const Tool: TypeTool = {
name: 'BIRCH Microclustering Demonstrator',
slug: 'clustering/birch-microclusters',
intro:
'Build order-dependent BIRCH-style microclusters using a maximum-radius threshold.',
tool: createBirchMicroclusters,
i: [
{
example: '1,1\n1.2,1.1\n8,8\n8.1,8.2',
label: 'Points',
placeholder: 'One vector per line',
render: 'textarea',
type: 'text'
},
{
example: '0.5',
label: 'Radius Threshold',
placeholder: 'Maximum microcluster radius',
type: 'number'
}
],
o: [
{
example: '{ "clusterCount": 2 }',
label: 'Microclusters',
placeholder: 'Clusters will appear here...',
render: 'textarea',
type: 'text'
}
]
};
export default Tool;
Description
Browse the implementation files for BIRCH Microclustering Demonstrator.