File size: 4,054 Bytes
16231ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
#!/usr/bin/env python3
"""Combine datasets from several training revisions into one revision + one fold table.

Each revision named with --add was built on the same base revision and extended the same base folds
(extend_cv_folds.py), so a pair keeps the same fold everywhere; this is checked. The base rows of the listed --drop
datasets are removed (--drop).
Exclusion lists (--train-exclude) are merged into one file for --train-exclude-views (training only; every pair is
still scored).

  python scripts/data_preparation/assemble/combine_revisions.py --base <rev> --add <rev>_<name>:<dataset> ...
         --drop <dataset> --train-exclude a.csv b.csv --name <rev>_all_new
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]

import argparse
from pathlib import Path

import pandas as pd

ROOT = Path("runs_main_all_datasets/direct_aq_dataset_gain")
RUNS = Path("runs_main_all_datasets/photo_aqnet")


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--base", required=True, help="base revision name")
    p.add_argument("--base-folds", required=True, type=Path, help="fold table of the base revision (cv_folds.csv)")
    p.add_argument("--add", nargs="+", required=True, metavar="REVISION:DATASET:FOLDS",
                   help="revision name, its training_dataset to take, and its fold file (in that revision folder)")
    p.add_argument("--drop", nargs="*", default=[], help="base datasets to remove")
    p.add_argument("--train-exclude", nargs="*", type=Path, default=[], help="exclusion lists to merge")
    p.add_argument("--name", required=True, help="new revision name")
    a = p.parse_args()
    base = pd.read_csv(ROOT / a.base / "metadata_manifest.csv", low_memory=False)
    folds = pd.read_csv(a.base_folds)
    drop = base.training_dataset.astype(str).isin(a.drop)
    print(f"base {a.base}: {len(base)} rows; dropping {int(drop.sum())} rows of {a.drop}")
    parts, fparts = [base[~drop]], [folds[~folds.dataset.astype(str).isin(a.drop)]]
    ref = dict(zip(folds.view_id.astype(str), folds.fold))
    for spec in a.add:
        rev, ds, ff = spec.split(":")
        m = pd.read_csv(ROOT / rev / "metadata_manifest.csv", low_memory=False)
        f = pd.read_csv(ROOT / rev / ff)
        shared = f[f.view_id.astype(str).isin(ref)]
        clash = (shared.fold.to_numpy() != shared.view_id.astype(str).map(ref).to_numpy()).sum()
        if clash:
            raise SystemExit(f"{rev}: {clash} base pairs have a different fold than in the base fold table")
        rows, frows = m[m.training_dataset.astype(str).eq(ds)], f[f.dataset.astype(str).eq(ds)]
        print(f"+ {ds} from {rev}: {len(rows)} rows, {len(frows)} in folds ({int(frows.trainable_pair.sum())} trainable)")
        parts.append(rows); fparts.append(frows)
    out = pd.concat(parts, ignore_index=True, sort=False)
    fout = pd.concat(fparts, ignore_index=True, sort=False)
    if out.view_id.astype(str).duplicated().any() or fout.view_id.astype(str).duplicated().any():
        raise SystemExit("duplicate view_id after combining")
    d = ROOT / a.name
    d.mkdir(parents=True, exist_ok=True)
    out.to_csv(d / "metadata_manifest.csv", index=False)
    fout.to_csv(d / "cv_folds_combined.csv", index=False)
    if a.train_exclude:
        ex = pd.concat([pd.read_csv(x)[["view_id"]] for x in a.train_exclude]).drop_duplicates()
        ex.to_csv(d / "train_exclude_combined.csv", index=False)
        print(f"exclusion list: {len(ex)} views")
    print(f"-> {d}: {len(out)} rows, {len(fout)} pairs in folds; by dataset:")
    print(fout.groupby("dataset").agg(pairs=("view_id", "size"), trainable=("trainable_pair", "sum")).to_string())


if __name__ == "__main__":
    main()