@gmod/hclust

中文文档
6.0.0发布于 2026/09/16MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2.6万

Hierarchical clustering

原始使用文档
文档目录11 节
  1. Install
  2. Algorithm
  3. Usage
  4. Result
  5. Input
  6. Precomputed distances
  7. Other exports
  8. Progress
  9. Cancellation
  10. References
  11. Note

@gmod/hclust

Fast hierarchical clustering (UPGMA) compiled to WebAssembly with JavaScript/TypeScript bindings.

Install

npm install @gmod/hclust

Algorithm

Agglomerative clustering with average linkage. Computes Euclidean distances, then merges the closest clusters at each step until one cluster remains, producing a dendrogram. Equivalent to R's hclust(method="average").

Roughly O(N²) in time and memory: 3,000 samples cluster in ~0.3s and 10,000 in ~5.5s. Input with many tied distances is much slower, since a tie forces a rescan for a new nearest neighbour: 3,202 rows carrying only 9 distinct values took 27s where 3,202 distinct rows took 0.36s. The wasm heap is 2GB and holds the N×V input beside the N×N distance matrix (400MB at N=10,000), so a matrix the two cannot share is refused up front with both sizes in the message. See docs/optimizations.md for how this got fast.

Usage

import { clusterObject, toNewick, fromNewick } from '@gmod/hclust'

const result = await clusterObject({
  data: {
    'Sample A': [1.0, 2.0, 3.0],
    'Sample B': [1.5, 2.5, 3.5],
    'Sample C': [10.0, 11.0, 12.0],
  },
})

const newick = toNewick(result.tree)
const tree = fromNewick(newick)

clusterData is also available if you have separate arrays:

import { clusterData } from '@gmod/hclust'

const result = await clusterData({
  data: [
    [1.0, 2.0, 3.0],
    [1.5, 2.5, 3.5],
    [10.0, 11.0, 12.0],
  ],
  sampleLabels: ['Sample A', 'Sample B', 'Sample C'],
})

Rows may be plain arrays or typed arrays — anything ArrayLike<number>.

Result

  • tree: ClusterNode — root of the dendrogram. Leaves have height 0 and no children.
  • order: number[] — sample indices in left-to-right leaf order.
  • clustersGivenK: number[][][] — clustersGivenK[k] is the partition into k+1 clusters, each cluster an array of sample indices. It holds every level at once, so it costs O(N²) memory (~330MB at N=3000) and builds on first access rather than up front. Leave it alone if you only need tree and order.

Input

  • At least 2 samples, or clusterData throws.
  • Every row the same length as the first, or clusterData throws naming the row.
  • No NaN or Infinity, or clusterData throws.
  • N×V×4 + N²×4 bytes within the 2GB wasm heap, or clusterData throws before allocating anything. Runs in flight at once share that heap, and one that cannot fit beside the others throws saying how many there are.
  • Without sampleLabels, leaves come back as Sample 0, Sample 1, …

Precomputed distances

Pass distances instead of data to cluster a matrix built elsewhere — on a GPU, or under another metric:

const result = await clusterData({
  distances, // Float32Array, N×N row-major
  sampleLabels,
})

Only the upper triangle (column > row) is read, so a producer may leave the diagonal and the lower half unset. The run skips the distance phase and goes straight to the merge loop, so onProgress reports only init and clustering. A matrix that is not square, or holds a NaN or Infinity, throws. It is clustered in place rather than beside a matrix computed here, so the heap budget is N²×4 bytes alone.

Other exports

  • toNewick(node) / fromNewick(string) — Newick serialization, writing merge heights as : branch lengths ((A:1.5,B:1.5)). fromNewick reads that back into absolute heights, and still accepts the label form v4 wrote ((A,B)1.5000). See docs/newick.md.
  • quoteName(name) — the Newick quoting rule toNewick uses, exported so a caller writing its own Newick escapes names the same way fromNewick expects.
  • treeToJSON(node) — plain-object copy of a tree, dropping empty children.
  • printTree(node) — ASCII dendrogram, for debugging.

Progress

Pass onProgress to observe a run. Reports arrive at most once per 100ms, so a small run may only ever emit the init phase:

clusterData({
  data,
  onProgress: ({ phase, message, current, total }) => {
    // phase: 'init' | 'distance' | 'clustering'
    // 'init' carries no denominator (total === 0) — render it indeterminate
    const label = total
      ? `${message}: ${Math.round((current / total) * 100)}%`
      : message
    console.log(label)
  },
})

message is an unformatted phase label and current/total are raw counts, so a caller can drive a determinate progress bar off them.

Cancellation

Pass an AbortSignal:

const controller = new AbortController()
const run = clusterData({ data, signal: controller.signal })
controller.abort() // run rejects with the signal's reason

The run works in slices of about 50ms and yields a task between them, so an abort lands within about 50ms, including one posted to a web worker as a message, and the run frees everything it held. A signal that has already aborted rejects before any work starts. Two runs in flight at once interleave slice by slice. See docs/cancellation.md for a worker and for how each environment yields.

References

Note

Generated with the help of Claude Code AI, you might be able to tell from the somewhat robotic documentation

版本与发布记录

@gmod/hclust 共发布 33 个版本,首次发布于 2025/11/22;过去 12 个月发布了 33 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.0.0latest2026/09/162 个月前
5.3.02026/09/082 个月前
5.2.02026/09/072 个月前
5.1.02026/08/252 个月前
5.0.02026/08/172 个月前
4.1.12026/08/163 个月前

关于 @gmod/hclust 的常见问题

@gmod/hclust 是什么?

Hierarchical clustering

如何安装 @gmod/hclust?

在项目目录运行 npm install @gmod/hclust,或使用 pnpm add / yarn add / bun add。

@gmod/hclust 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gmod/hclust 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gmod/hclust 可以商用吗?

@gmod/hclust 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gmod/hclust 的下载量有多少?

根据 npm 官方下载统计,@gmod/hclust 在 2026/10/17 – 2026/11/15 这 30 天内被下载 25,759 次,日均约 859 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gmod/hclust 还在维护吗?

最新版本 6.0.0 发布于 2026/09/16(2 个月前);至今共发布 33 个版本,其中过去 12 个月发布了 33 个;首次发布于 2025/11/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。