File size: 3,702 Bytes
39ea985
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""Draw a uniform random subset of OMol25 calculations and check they exist on m5250.

The population is the 4M-split path list shipped with the release (`4m_paths.txt`, 3,986,753 rows).
Sampling is uniform over that list with a fixed seed, so the subset keeps the collection's natural
dataset proportions and is exactly reproducible.

Writes:
  subset_<n>.txt        one relative path per line, present on m5250, shuffled
  subset_<n>_missing.txt paths sampled but not found locally
  subset_<n>_counts.tsv per-dataset counts, sampled vs population
"""
import argparse, os, random, sys
from collections import Counter

M5250 = "/global/cfs/projectdirs/m5250/OMol_elec"
PATHS = ("/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/gbw_pilot/"
         "source_root/4m_paths.txt")
OUTDIR = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/subsets"


def dataset_of(rel):
    """Top-level dataset name; the omol/ tree is grouped by its second and third component."""
    parts = rel.split("/")
    if parts[0] == "omol" and len(parts) > 2:
        return "/".join(parts[:3])
    return parts[0]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("-n", type=int, default=100_000)
    ap.add_argument("--seed", type=int, default=20260903)
    ap.add_argument("--paths", default=PATHS)
    ap.add_argument("--outdir", default=OUTDIR)
    ap.add_argument("--check", type=int, default=5000,
                    help="how many sampled paths to stat for a miss-rate estimate (0 = none)")
    args = ap.parse_args()

    with open(args.paths) as fh:
        pop = [l.strip() for l in fh if l.strip()]
    print(f"population: {len(pop):,} paths", flush=True)

    rng = random.Random(args.seed)
    n = min(args.n, len(pop))
    sample = rng.sample(pop, n)
    print(f"sampled uniformly: {n:,} (seed {args.seed})", flush=True)

    os.makedirs(args.outdir, exist_ok=True)
    # Stat-ing every path is slow on CFS (huge directories), and Pass A detects a missing archive
    # for free, so only a subsample is checked here to estimate the miss rate.
    missing = []
    ncheck = min(args.check, n)
    for i, rel in enumerate(sample[:ncheck]):
        if not os.path.exists(os.path.join(M5250, rel, "orca.tar.zst")):
            missing.append(rel)
        if (i + 1) % 1000 == 0:
            print(f"  checked {i+1:,}/{ncheck:,}: {len(missing):,} missing", flush=True)
    present = sample
    rng.shuffle(present)
    base = os.path.join(args.outdir, f"subset_{n//1000}k")
    with open(base + ".txt", "w") as fh:
        fh.write("\n".join(present) + "\n")
    with open(base + "_missing.txt", "w") as fh:
        fh.write("\n".join(missing) + ("\n" if missing else ""))

    pop_counts = Counter(dataset_of(p) for p in pop)
    got_counts = Counter(dataset_of(p) for p in present)
    with open(base + "_counts.tsv", "w") as fh:
        fh.write("dataset\tpopulation\tsampled\tpct_of_dataset\n")
        for ds in sorted(pop_counts, key=lambda d: -pop_counts[d]):
            fh.write(f"{ds}\t{pop_counts[ds]}\t{got_counts.get(ds,0)}\t"
                     f"{100*got_counts.get(ds,0)/pop_counts[ds]:.3f}\n")

    rate = (100 * len(missing) / ncheck) if ncheck else float("nan")
    print(f"\nsubset {len(present):,} paths; miss rate on {ncheck:,} checked: "
          f"{len(missing):,} ({rate:.2f}%)")
    print(f"datasets covered: {len(got_counts)}/{len(pop_counts)}")
    zero = [d for d in pop_counts if d not in got_counts]
    if zero:
        print("datasets with no sampled member:")
        for d in zero:
            print(f"   {d}  (population {pop_counts[d]:,})")
    print(f"\nwrote {base}.txt / _missing.txt / _counts.tsv")


if __name__ == "__main__":
    main()