File size: 3,483 Bytes
0dd5490 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | """Convert a blocking candidates parquet into the challenge `candidate_pairs.tsv`.
One row per Source-1 id of the S1 file, in file order; candidate ids comma-joined,
deduplicated, S2-/S3- ids only, empty when the entity has no candidates. Only the columns
s1_id and cand_id are read, so any later-stage parquet (e.g. a filtered candidate set, which
is what the rules require: the set actually fed to the matcher) works as input.
python -m src.make_candidate_tsv --candidates cands.parquet \
--s1 dataset/test/test_source1.tsv --out output/candidate_pairs.tsv [--order-by sim_nameaddr]
"""
from __future__ import annotations
import argparse
import sys
import polars as pl
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--candidates", required=True, help="parquet with columns s1_id, cand_id")
ap.add_argument("--s1", required=True, help="Source-1 TSV (or parquet with entity_id) defining the rows")
ap.add_argument("--out", required=True)
ap.add_argument("--order-by", default=None, help="optional score column; lists sorted by it descending")
a = ap.parse_args(argv)
cols = ["s1_id", "cand_id"] + ([a.order_by] if a.order_by else [])
c = (
pl.scan_parquet(a.candidates)
.select(cols)
.filter(pl.col("cand_id").str.starts_with("S2-") | pl.col("cand_id").str.starts_with("S3-"))
)
if a.order_by:
c = c.group_by(["s1_id", "cand_id"]).agg(pl.col(a.order_by).max()).sort(
["s1_id", a.order_by, "cand_id"], descending=[False, True, False], nulls_last=True
)
else:
c = c.unique(["s1_id", "cand_id"]).sort(["s1_id", "cand_id"])
grouped = c.group_by("s1_id", maintain_order=True).agg(pl.col("cand_id")).collect()
grouped = grouped.with_columns(pl.col("cand_id").list.unique(maintain_order=True).list.join(",").alias("candidate_entity_ids"))
if a.s1.endswith(".parquet"):
s1 = pl.read_parquet(a.s1, columns=["entity_id"]).with_columns(pl.col("entity_id").cast(pl.Utf8))
else:
s1 = pl.read_csv(a.s1, separator="\t", quote_char=None, infer_schema_length=0, columns=["entity_id"])
s1 = s1.with_columns(pl.col("entity_id").str.strip_chars()).with_row_index("_r")
n_dup = s1.height - s1.get_column("entity_id").n_unique()
if n_dup:
print(f"WARNING: {n_dup} duplicate entity_id rows in {a.s1}; keeping the first", file=sys.stderr)
s1 = s1.unique("entity_id", keep="first", maintain_order=True)
out = (
s1.join(grouped.select("s1_id", "candidate_entity_ids"), left_on="entity_id", right_on="s1_id", how="left")
.sort("_r")
.select(pl.col("entity_id").alias("source1_entity_id"), pl.col("candidate_entity_ids").fill_null(""))
)
unknown = grouped.filter(~pl.col("s1_id").is_in(s1.get_column("entity_id"))).height
if unknown:
print(f"WARNING: {unknown} candidate s1_ids are not in {a.s1}; dropped", file=sys.stderr)
out.write_csv(a.out, separator="\t", quote_style="never", include_header=True)
n_c = out.get_column("candidate_entity_ids").str.split(",").list.len()
has = out.get_column("candidate_entity_ids") != ""
print(
f"wrote {a.out}: {out.height:,} S1 rows, {int(n_c.filter(has).sum()):,} candidate ids, "
f"{int((~has).sum()):,} rows without candidates, mean {float(n_c.filter(has).sum()) / max(out.height, 1):.2f} per S1"
)
if __name__ == "__main__":
main()
|