Skip to main content

sphncs

Licensed under Apache-2.0.

sphncs is the Similarity-Preserving Hierarchical Nonparametric Clustering System. It clusters any objects with a well-defined, non-negative distance metric by embedding on-demand distances with FastMap and finding density separations with KDEpy.FFTKDE.

It supports a lightweight single-dimension mode and an optional spectral-consensus mode that combines KDE cluster assignments from several FastMap dimensions. An optional first KDE can partition objects with any user-supplied scalar feature. In spectral-consensus mode, automatic k is the median number of clusters observed by the per-dimension KDE fits, rather than the number of embeddings. Set consensus_n_clusters to "min", "mean", "median", or "max" to select another reduction of those observed counts; an explicit integer remains available when a fixed target is required. extrema_prominence_fraction controls how deep a KDE valley must be relative to that KDE's density range (the default is 0.05); smaller fractions preserve more candidate modes. The estimator uses three FastMap pivot-refinement passes. Configure the number of passes with fastmap_iters.

from dataclasses import dataclass

from sphncs import SphncsClusterer


@dataclass
class Point:
    x: float


def distance(left: Point, right: Point) -> float:
    return abs(left.x - right.x)

model = SphncsClusterer(metric=distance)
labels = model.fit_predict([Point(0.0), Point(0.2), Point(10.0), Point(10.2)])
print(model.representatives_)

For optional first-stage partitioning, provide a scalar feature. Partitioning is hard routing: objects in different feature intervals are clustered separately.

model = SphncsClusterer(
    metric=distance,
    partitioning=True,
    partitioning_feature=lambda point: point.x,
)

String distances such as normalized_levenshtein and char_ngram_jaccard remain available in sphncs.distances. They are conveniences, not a restriction on the estimator's input type.

Log clustering

LogSPHNCS is the log-specific adapter. Its log_filters replace selected fields with filter-specific, fixed-width masks before embedding and clustering. The optional initial partitioner uses filtered strings by default; pass partitioning_before_transform=True to derive its feature from the original raw strings first. It uses length by default; set partitioning_feature="entropy" for character Shannon entropy or "normalized_entropy" for character-use evenness. Every marker is four characters long: timestamps use <#T>, severity uses <#S>, UUIDs use <#U>, IPs use <#I>, hex values use <#H>, numbers use <#N>, paths use <#P>, quoted values use <#Q>, and identifiers use <#D>. Choose individual filters (timestamp, severity, uuid, ip, hex, number, path, quoted, and identifier), use variable for all value-masking filters, or use all for every filter.

The hex filter recognizes 0x-prefixed values. Short bare hexadecimal sequence fields such as 0000000e are normalized by the number filter, so they match their decimal-only counterparts without masking longer component IDs.

representatives_ contains the filtered form by default. The original training lines remain available in the position-aligned raw_strings_, through get_raw_string(index), and as raw_representatives_ for the cluster representatives.

model = LogSPHNCS(
    log_filters=["timestamp", "severity", "variable"],
)

LogSPHNCS

LogSPHNCS defaults to all log filters, 4-gram Jaccard, length partitioning, 10-dimensional spectral consensus, and exact filtered-template compression. Raw records remain aligned in raw_strings_ and raw_representatives_.

from sphncs import LogSPHNCS

model = LogSPHNCS().fit(log_lines)

Model persistence

Fitted models can be saved to a versioned, integrity-checked .sphncs archive and loaded later. The archive preserves prediction and transformation state. Each FastMap projection is persisted with FastMapy’s native versioned format.

model.save("logs.sphncs")
restored = LogSPHNCS.load("logs.sphncs")
assert restored.predict(log_lines).tolist() == model.predict(log_lines).tolist()

Archives use Python pickle to support arbitrary input objects and user-supplied metrics or transformers. Only load archives from sources you trust. Callables must be importable functions (rather than lambdas or nested functions) to save reliably. Format version 2 is validated on load; unsupported future formats are rejected rather than loaded incorrectly.

fastmapy is included as the vendor/fastmapy Git submodule and isolated behind an embedding adapter. It is used for all FastMap fits, including its fit_many API for spectral-consensus embeddings; no pairwise string-distance matrix is created or retained.

Development

git submodule update --init --recursive
python -m pip install -e vendor/fastmapy
python -m pip install -e '.[dev]'
python -m pytest

Metadata

Release files for sphncs 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sphncs 0.3.1
File Size Uploaded
sphncs-0.3.1.tar.gz 27.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sphncs 0.3.1
File Interpreter ABI Platform
sphncs-0.3.1-py3-none-any.whl Python 3 none any Details

Total release size: 52.1 kB

Release files / sphncs-0.3.1.tar.gz

Download URL sphncs-0.3.1.tar.gz
Size 27.5 kB
Tags Source
SHA-256 checksum
How to use checksums
22720b2922dc8b3dbd9ee08f05f720e7dccb3d54d232d96186ec8581660b9ef7
BLAKE2b-256 checksum
How to use checksums
d5d0d276ac15b4d67526ebb1c68ed52350fba4ca02eb0d5755f5956d06cca123
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.

Transparency log

Release files / sphncs-0.3.1-py3-none-any.whl

Download URL sphncs-0.3.1-py3-none-any.whl
Size 24.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a3d1d3e9fa7059d9101b0ad52c7d3778ac9b46c89b1b21e652a49d1ff3f812eb
BLAKE2b-256 checksum
How to use checksums
e446e557e39f8dc7eed3ff065d526d5f1f1362ecf1d54871cb9dffdce286b06f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.3.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page