Metadata-Version: 2.4
Name: rsetsim
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Software Development :: Libraries
Requires-Dist: pytest ; extra == 'dev'
Requires-Dist: hypothesis ; extra == 'dev'
Requires-Dist: setsimilaritysearch ; extra == 'dev'
Requires-Dist: ruff==0.15.21 ; extra == 'dev'
Provides-Extra: dev
License-File: LICENSE
Summary: Rust-powered exact set similarity search and all-pairs similarity join (Jaccard, cosine, containment) for Python
Keywords: set similarity,jaccard,similarity join,all pairs,deduplication,entity resolution,ppjoin
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/f4hy/rsetsim
Project-URL: Issues, https://github.com/f4hy/rsetsim/issues
Project-URL: Repository, https://github.com/f4hy/rsetsim

# rsetsim

**Exact** set similarity search and all-pairs similarity join for Python,
implemented in Rust via [PyO3](https://pyo3.rs). It is a fast, multi-threaded,
API-compatible replacement for
[`SetSimilaritySearch`](https://github.com/ekzhu/SetSimilaritySearch).

```python
from rsetsim import all_pairs, SearchIndex

sets = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"], ["a", "b", "c", "e"]]

# Every pair with Jaccard >= 0.5: [(x, y, similarity), ...] with x > y
all_pairs(sets, similarity_func_name="jaccard", similarity_threshold=0.5)
# [(1, 0, 0.5), (3, 0, 0.75)]

index = SearchIndex(sets, similarity_func_name="jaccard", similarity_threshold=0.5)
index.query(["a", "b", "c"])        # [(0, 1.0), (3, 0.75), (1, 0.5)]
index.query_batch([q1, q2, ...])    # parallel, GIL released
```

## Why

Finding near-duplicate records, documents (as shingle sets), users with
similar histories, or matching entities is a *set similarity join*. The
practical exact algorithms (AllPairs, Bayardo et al. 2007; PPJoin, Xiao et
al. 2008) are well known. In Python, the only implementation is
`SetSimilaritySearch`, which is pure Python + numpy, and its README directs
users to a Go port for performance. MinHash LSH (`datasketch`, `rensa`) is
the usual alternative, but it is *approximate*: it misses some pairs and
needs tuning. `rsetsim` gives exact answers, fast.

## Install

```sh
pip install rsetsim
```

Prebuilt `abi3` wheels (Linux/macOS/Windows, Python 3.11+).

## Benchmarks

Synthetic Zipf-distributed token sets (5–50 tokens from a 50k vocabulary,
20% planted near-duplicates), Jaccard ≥ 0.5, 8 threads. Source:
[`benchmarks/bench.py`](./benchmarks/bench.py).

| task | n sets | rsetsim | SetSimilaritySearch | speedup |
|---|---|---|---|---|
| `all_pairs` | 10,000 | 0.046s | 5.75s | **126x** |
| `all_pairs` | 100,000 | 1.13s | 629s | **~560x** |
| build `SearchIndex` | 100,000 | 0.22s | 1.69s | 8x |
| 10k × `query()` | 100,000 | 1.52s | 117s | **77x** |
| 10k queries via `query_batch()` | 100,000 | 0.28s | 117s | **~410x** |
| `all_pairs` | 1,000,000 | 150s (1.1M pairs) | (not run) | |
| 10k queries via `query_batch()` | 1,000,000 | 7.3s | (not run) | |

The pure-Python reference was not run at 1M sets. Results were checked to
be identical to `SetSimilaritySearch` (same pairs, same similarities)
wherever both ran.

## API

`all_pairs(sets, similarity_func_name="jaccard", similarity_threshold=0.5)`
returns a list of `(x, y, similarity)` with `x > y` (indices into `sets`),
sorted by `(x, y)`. It supports the symmetric measures `jaccard`, `cosine`,
and `containment_min`.

`SearchIndex(sets, similarity_func_name="jaccard", similarity_threshold=0.5)`
has the following methods:

- `.query(s)` returns `[(index, similarity), ...]`, sorted by similarity
  (highest first), then by index.
- `.query_batch(queries)` runs many queries in parallel (the GIL is
  released).
- `len(index)`, `.similarity_func_name`, `.similarity_threshold`.

Sets can be any iterables of hashable tokens (`str`, `int`, tuples, ...).

| measure | definition |
|---|---|
| `jaccard` | \|A∩B\| / \|A∪B\| |
| `cosine` | \|A∩B\| / √(\|A\|·\|B\|) |
| `containment` (query only) | \|Q∩S\| / \|Q\| |
| `containment_min` | \|A∩B\| / max(\|A\|,\|B\|), i.e. the smaller of the two containments |

### Semantics

- **Exact**: there are no false positives or false negatives. Every
  candidate is verified with a full intersection, and all filters are
  provable bounds, rounded toward the safe side.
- Pairs that share no token are never reported, even at threshold 0
  (same as the reference).
- Duplicate tokens within a set are ignored (the reference requires unique
  tokens and gives wrong answers otherwise).
- In `query`, tokens the index has never seen count toward the query's
  size (same as the reference).
- Thread count is controlled by `RAYON_NUM_THREADS` (default: all cores).

> [!NOTE]
> **Compatibility with `SetSimilaritySearch`**
>
> Same function and class names, argument names, defaults, and result
> tuples. Differences:
> - `all_pairs` returns a sorted list instead of a generator.
> - `query` results are sorted.
> - Empty input lists are allowed instead of raising `ValueError`.
> - `query_batch` is new.

## How it works

1. **Frequency ordering**: tokens are re-labelled by global frequency,
   rarest first, so set prefixes contain rare tokens.
2. **Prefix filter**: if two sets need overlap ≥ α, their first `|s|-α+1`
   tokens must intersect, so only prefixes are indexed and probed. Separate
   probe-side and index-side bounds are derived for each measure.
3. **Size filter**: partners whose size makes the threshold unreachable are
   skipped by binary search, because posting lists are ordered by set size.
4. **Positional filter (PPJoin)**: during the all-pairs probe and queries, a
   candidate is dropped as soon as its matched count plus the remaining
   tokens can't reach α.
5. **Verification**: a sorted-merge intersection on `u32` ranks.

Python tokens are mapped to dense `u32` ids through a `dict` (so equality
and hashing follow Python semantics). Everything after that runs in Rust,
with the GIL released, in parallel across rayon threads.

## Development

```sh
cargo test --no-default-features          # includes brute-force equivalence tests
pip install -e '.[dev]' && maturin develop --release
pytest                                    # Hypothesis tests vs brute force + vs SetSimilaritySearch
python benchmarks/bench.py                # slow: the reference takes ~10 min at 100k
```

