Metadata-Version: 2.4
Name: rowmatch
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Dist: pytest>=8 ; extra == 'dev'
Requires-Dist: ruff>=0.6 ; extra == 'dev'
Provides-Extra: dev
License-File: LICENSE
Summary: Find the rows that describe the same real-world thing: fast, explainable entity resolution
Keywords: entity resolution,record linkage,deduplication,fuzzy matching,data quality
Author: Alex Geblea
License: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/GebleaAlex/rowmatch

# rowmatch

[![CI](https://github.com/GebleaAlex/rowmatch/actions/workflows/ci.yml/badge.svg)](https://github.com/GebleaAlex/rowmatch/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Find the rows that describe the same real-world thing.

`SC Alfa Construct SRL`, `Alfa Construct` and `ALFA CONSTRUCT S.R.L.` are one company written three
ways. rowmatch finds groups like that in a table, without labelled examples, and tells you why it
decided each one. It does entity resolution, also called record linkage, deduplication or fuzzy
matching. The engine is written in Rust; you use it from Python or from the command line.

```python
import rowmatch as rm

model = rm.Model(
    rm.field("name", "jaro_winkler", normalize="company"),
    rm.field("city", "exact"),
    rm.field("tax_id", "exact", normalize="digits"),
)
result = model.dedupe(df)       # a pandas or Polars DataFrame, a pyarrow Table,
                                # a dict of lists, or a list of dicts

result.cluster_ids              # one id per row; rows with the same id are the same entity
result.clusters()               # the duplicates, as lists of row indices
print(result.explain(14, 10532))
```

```console
$ rowmatch dedupe companies.csv -f name:jaro_winkler:company -f city:exact -f tax_id:exact:digits --out clusters.csv
16243 rows, 1151781 candidate pairs out of 131909403 possible
9893 matched pairs, 10157 entities, 3084 of them with duplicates (9170 rows), largest cluster 5
done in 0.12 s
```

> **Status: early.** Version 0.1 deduplicates one table. The Python package is on PyPI:
> `pip install rowmatch`. The command line is not on crates.io yet, so for now it is
> [built from source](#building-from-source). The [measured results](#measured-results)
> and the [limits](#limits) say plainly what it does well and what is missing.

## Every decision can be explained

Three records of one company from the test data: a typo in two of the names, the city missing in
one and the tax id missing in another.

| row | name | city | tax_id |
|---|---|---|---|
| 14 | EXPERT SOLUTIOPS SRL | | RO 805505 |
| 10532 | Expert Solutions S.R.L. | giurgiu | RO805505 |
| 12419 | Expert bolutions SRL | giurgiu | |

```console
$ rowmatch explain companies.csv --config examples/companies.toml --rows 10532,12419
rows 10532 and 12419: match
probability 0.9340 (threshold 0.9)

    bits  field        evidence
  -13.66  (prior)      how rare matches are among all pairs of rows
  +12.17  name         similarity at least 0.94 (0.975): "Expert Solutions S.R.L." vs "Expert bolutions SRL"
   +5.32  city         equal, on a value many rows share: "giurgiu" vs "giurgiu"
   +0.00  tax_id       missing: "RO805505" vs ""
   +3.82  total
```

Evidence is measured in bits and simply adds up. Each bit doubles the odds. Two rows picked at
random are almost never the same company, so every pair starts 13.66 bits down: odds of about one
in 13,000. Names this similar are about 4,600 times more common among matches than among other
pairs, the shared city about 40 times, and a missing value says nothing either way. Rows 14 and
10532 share a tax id, which alone is worth 29 bits, because no two different companies in the table
share one.

Rows 14 and 12419 have only the similar names in common, which is not enough: on their own they
reach a probability of 0.26. They still end up together, because each matches row 10532:

```console
rows 14 and 12419: not a direct match, but in the same cluster through other rows
```

The explanation also says when two rows would match but were never compared, and when they match
but their clusters were kept apart, so "why were these not merged?" has an answer too.

## How it works

1. **Normalize.** Lowercase, strip diacritics and punctuation, and optionally drop legal forms
   (`SRL`, `Ltd`, `GmbH`) or keep only digits. `Cluj-Napoca` and `CLUJ NAPOCA` become equal.
2. **Block.** A million rows have half a trillion pairs. Blocking keeps only pairs that share a
   key: an exact value, a prefix, a word, or similar spelling found with MinHash and
   locality-sensitive hashing. In the run above it removed 99% of the comparisons.
3. **Compare and score.** Each surviving pair is compared field by field (Jaro-Winkler,
   Levenshtein, shared words or exact equality) and scored with a
   [Fellegi-Sunter](https://en.wikipedia.org/wiki/Record_linkage#Probabilistic_record_linkage)
   model. Its parameters are estimated from your data by expectation-maximization, so no labelled
   pairs are needed.
4. **Cluster.** Matching pairs are followed strongest first. Two groups of rows become one
   cluster only if enough of the pairs between them match (three in ten by default), so one wrong
   match cannot merge two groups of several rows, and a few cannot chain many.

Three choices in steps 3 and 4 matter more than the rest:

* **The model describes every pair of rows, not just the compared ones.** How often a field
  agrees by chance is measured on the whole table, and pairs that blocking left out count as
  non-matches. That anchors the estimate: a table without duplicates stays unmerged. What a
  match looks like is learned from selective blocks only, so a rule that proposes everyone
  called William cannot drown the rest.
* **A value that many rows share is not evidence like a rare one.** Two rows that both say
  `Unknown`, or carry the placeholder tax id `0000000000`, agree by chance. Equal values shared
  by more than twenty rows are a comparison level of their own, so they neither pass for an
  identifier nor cheapen the agreement of rare values.
* **Clusters need cohesion.** The simple rule joins everything a chain of matches connects. With
  ten records per entity, a handful of wrong matches then ruins the result; the
  [benchmark](#public-datasets-next-to-splink-and-dedupe) below shows how much.

The similarity measures, the MinHash blocking, the EM estimation and the clustering are all
implemented in this repository, in [`crates/rowmatch-core`](crates/rowmatch-core/src). Each module
starts with a description of what it does.

## Measured results

### Public datasets, next to Splink and dedupe

Person records with a known answer. Every tool gets the same rows, columns and threshold (0.9)
and is scored by the same function. [`benchmarks/`](benchmarks) has all five datasets, the method,
what was and was not equal between the tools, and the script that reproduces it.

**FEBRL 4** (10,000 synthetic person records with a social security id): everyone gets it right,
and rowmatch is the fastest.

| tool | time | precision | recall | F1 |
|---|---:|---:|---:|---:|
| **rowmatch** | 0.45 s | 1.000 | 1.000 | 1.000 |
| Splink | 2.27 s | 1.000 | 1.000 | 1.000 |
| dedupe, trained on the true pairs | over an hour, training included | 0.999 | 1.000 | 1.000 |

The other three FEBRL sets give the same picture: F1 of 0.999 or 1.000 for rowmatch and Splink,
with rowmatch 5 to 26 times faster across the four.

**historical_50k** (50,578 records of historical people from Wikidata, about ten per person, no
identifier, many missing values): the hard one, and the one to read carefully.

| model | pairs compared | clusters | precision | recall | F1 |
|---|---|---|---:|---:|---:|
| **rowmatch** | its own blocking | cohesion | 0.980 | 0.888 | 0.932 |
| rowmatch | its own blocking | any chain of matches | 0.314 | 0.926 | 0.469 |
| rowmatch | Splink's blocking rules | cohesion | 0.979 | 0.885 | 0.930 |
| rowmatch | Splink's blocking rules | any chain of matches | 0.176 | 0.925 | 0.296 |
| Splink, same comparisons | Splink's blocking rules | any chain of matches | 0.398 | 0.850 | 0.542 |
| Splink, same comparisons | Splink's blocking rules | rowmatch's cohesion rule | 0.983 | 0.798 | 0.881 |
| Splink, as in its tutorial | its tutorial's rules | any chain of matches | 0.893 | 0.766 | 0.824 |

What this shows, and what it does not:

* **rowmatch's default, the first row, is the best result in the table**, in 2.2 s. Given
  Splink's blocking rules instead of its own, it scores the same (0.930).
* **The clustering rule is what makes the difference.** Different people from the same place
  share a birthplace and almost the same postcode, and a few thousand such wrong matches chain
  clusters of hundreds of rows. Asking two groups to hold together before joining them removes
  the chains, for Splink's matches as well: 0.542 becomes 0.881.
* **Pair for pair, Splink is the more careful matcher.** On the same pairs and comparisons it
  matches 201,139 pairs and gets 3,207 wrong; rowmatch matches 234,338 and gets 6,292 wrong. It
  finds more of the true pairs and makes twice the mistakes. Clustered by plain chains at a
  threshold of 0.9, where every mistake is multiplied, that puts Splink ahead: 0.542 against
  0.296.
* **Everywhere else in this comparison rowmatch is ahead**: with the cohesion rule on both
  sides (0.930 against 0.881), and at a threshold of 0.99 with either clustering (0.882 against
  0.854 with plain chains, 0.899 against 0.815 with the rule).
* **Two defaults were settled with this dataset in view**: the cohesion of 0.3 (values from 0.2
  to 0.5 give the same result within 0.002) and the line between common and rare values. And it
  is one dataset. [`benchmarks/`](benchmarks) has what else limits the conclusion.

### Synthetic company lists

Made by `rowmatch synth`, with a known answer: about 30% of the companies appear two to four times,
with typos, reformatted names and tax ids, and missing values. Measured with
`examples/companies.toml` on a 20-thread Intel Core i5-14600K, release build.

| rows | time | precision | recall | F1 |
|---:|---:|---:|---:|---:|
| 16,243 | 0.11 s | 0.999 | 0.964 | 0.981 |
| 159,451 | 3.3 s | 0.997 | 0.917 | 0.955 |
| 1,599,683 | 1 to 2.5 minutes | 1.000 | 0.799 | 0.888 |

Precision is the share of predicted pairs that are truly the same company; recall is the share of
true pairs that were found. Times are for the deduplication itself, without reading the CSV; the
largest run took 65 s and 150 s in two sessions on a desktop that was also doing other things.

Read these numbers for what they are:

* **The data is synthetic.** The generator and the matcher were written together, so this shows
  that the pipeline works and how it scales, not how it does on your data. The public datasets
  above are the fairer test.
* **Recall falls as the table grows, and that is the model being careful.** The generator builds
  names from a small vocabulary. In 16,000 rows a nearly identical name in the same city is enough
  to call two rows the same company. In 1.6 million rows so many unrelated companies share both
  that it no longer is, and only pairs confirmed by a tax id are matched: precision 1.000, and
  recall equal to the share of duplicate pairs that kept their tax id.
* **A table with no duplicates stays unmerged.** Across 26 generated tables of 100 to 20,000
  companies with nothing to find, no rows were merged. This is part of the test suite, as are
  tables with hundreds of placeholder rows, which leave the result for the other rows unchanged.

Reproduce:

```console
$ rowmatch synth --entities 100000 --out companies.csv
$ rowmatch dedupe companies.csv --config examples/companies.toml --truth entity_id --out clusters.csv
```

## Configuration

From the command line, fields can be given as `--field column[:metric[:normalizer]]`, or everything
can go in a TOML file. This is [`examples/companies.toml`](examples/companies.toml) without its
comments:

```toml
threshold = 0.9

[[fields]]
column = "name"
compare = "jaro_winkler"
normalize = "company"

[[fields]]
column = "city"
compare = "exact"

[[fields]]
column = "tax_id"
compare = "exact"
normalize = "digits"

[[blocking]]
minhash = "name"

[[blocking]]
keys = [{ column = "tax_id" }]
```

| | values |
|---|---|
| `compare` | `jaro_winkler` (names; the default), `levenshtein` (codes), `token_set` (reordered words), `exact` |
| `normalize` | `text` (the default), `company`, `digits`, `none` |
| `thresholds` | similarity cut-offs between comparison levels, for example `[0.88, 0.94]` |
| blocking | `keys` (columns that must agree, optionally only a `prefix`), `tokens` (a shared word), `minhash` (similar spelling) |
| `threshold` | probability at or above which two rows match; default `0.9` |
| `cohesion` | share of the pairs between two groups that must match for them to become one cluster; default `0.3`, and `0` joins on a single match |
| `max_block_size` | blocks with more rows than this are skipped; default `500`. Raised above 500, the larger blocks are compared but the model does not learn from them |
| `seed` | makes runs reproducible; the same input and seed always give the same clusters |

Without a `blocking` section, rules are derived from the fields. A field is used when a value is
shared by at most 20 rows on average: fuzzy fields then get MinHash and `exact` fields a key. A
category such as a city is left out, because it would propose every pair of rows in the same city.
Rule sets that cover the same duplicates give nearly the same result: identical on the synthetic
data, and 0.932 against 0.930 on `historical_50k` with two entirely different sets.

**Cohesion in practice.** With the default, a row joins a group of ten when it matches at least
three of them, and a chain A-B-C where A and C do not match still forms one cluster, since one
pair of two is enough. Matched pairs that were not followed are counted in the run statistics.
In Python, `rm.cluster(rows, links)` applies the same rule to links from any source.

**One field.** A single field has nothing to corroborate it, so no model can be learned. Rows are
then matched when that field is equal after normalization, and on nothing else. The same holds
when the other fields are empty, the same on every row, or filled in for fewer than about one
row in seven.

The command line reads CSV files separated by commas, semicolons or tabs (`--delimiter` when the
guess is wrong) and writes the input rows back with a `cluster_id` column (`--cluster-column` to
name it differently). Files must be UTF-8.

## Limits

* **One table.** Linking two tables, and adding new rows to an already resolved set, are not built yet.
* **Fields are assumed independent** given whether two rows match. Strongly related fields (city
  and postcode) are double-counted, so rows of different entities that resemble each other for a
  reason, such as people from the same town or branches of a company, can be matched. The
  cohesion rule keeps such matches from merging groups, but two single rows that match wrongly
  are still merged.
* **Values are common or rare, nothing in between.** A value shared by more than twenty rows
  counts for less; among the rest, sharing a name that appears twice is treated like sharing one
  that appears twenty times. There is no finer term-frequency adjustment.
* **Text comparisons only.** A date one day apart and a date one character apart are not told
  apart; there are no date or numeric comparisons.
* **Identical rows are not merged just for being identical.** The model has to find that
  agreeing is rarer than chance. Two rows that say only `Popescu, București` stay apart.
* **Large groups are skipped by blocking.** A key shared by more than `max_block_size` rows
  proposes no pairs, so a value repeated thousands of times is not deduplicated through that rule.
  The command line reports how many blocks were skipped.
* **The order of the rows can matter a little.** Matches of equal strength are followed in row
  order, so the same rows in another order may be clustered slightly differently where groups
  are loosely connected.
* **It needs data to learn from.** The model is statistical. On a few dozen rows the estimates are
  rough; from a few hundred rows up they settle.
* **Text only, read through Python lists or CSV.** There is no Arrow or Parquet input yet, so large
  DataFrames are copied on the way in. A million rows need about 10 GB of memory for the
  candidate pairs.

## Roadmap

1. Finer term frequencies and date comparisons, the two things a tuned Splink has and rowmatch
   lacks.
2. Fewer wrong matches pair for pair, where the benchmark shows Splink ahead.
3. Benchmarks on company, product and bibliographic data, and a sweep of the threshold instead of
   one value.
4. The command line and the engine on crates.io.
5. Less memory per candidate pair, Arrow input, and linking two tables.

## Building from source

Needs [Rust](https://rustup.rs) 1.88 or newer and, for the Python package, Python 3.9 or newer.

```console
$ cargo build --release                 # the rowmatch binary, in target/release
$ cargo test --release                  # unit, property and end-to-end tests

$ python -m venv .venv                  # then activate it
$ pip install maturin pytest
$ maturin develop --release             # builds the extension into the virtual environment
$ pytest
```

The repository is a Cargo workspace:

| crate | what it is |
|---|---|
| [`crates/rowmatch-core`](crates/rowmatch-core) | the engine, a plain Rust library |
| [`crates/rowmatch-cli`](crates/rowmatch-cli) | the `rowmatch` command |
| [`crates/rowmatch-py`](crates/rowmatch-py) | the native half of the Python package in [`python/rowmatch`](python/rowmatch) |

[CONTRIBUTING.md](CONTRIBUTING.md) says how to report a problem and what a change needs.

## License

MIT. See [LICENSE](LICENSE).

