File size: 2,912 Bytes
5237fbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Data augmentation for the training set: each training structure gets K extra
text variants from a random site permutation plus a random rigid translation
(physically the same crystal). Validation and test rows are left untouched."""
import os, sys, csv, signal, json, time
os.environ.setdefault("CUDA_VISIBLE_DEVICES", ""); os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")
for v in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): os.environ.setdefault(v, "1")
import warnings; warnings.filterwarnings("ignore")
from multiprocessing import Pool
ROOT, BASE, OUT = sys.argv[1], sys.argv[2], sys.argv[3]
class TO(Exception): pass
def _alarm(*a): raise TO()
def resolve(rel):
    d, f = rel.split("/", 1)
    for pre in ("P-", "N-", ""):
        p = os.path.join(ROOT, pre + d, f)
        if os.path.exists(p): return p
    return None
NPROC = int(sys.argv[4]); K = int(sys.argv[5])
REPS = ["cif_p1", "cif_symmetrized", "slices", "zmatrix", "atom_sequences_plusplus"]

def work(row):
    import numpy as np
    from pymatgen.core import Structure
    from xtal2txt.core import TextRep
    out = []
    try: s0 = Structure.from_file(resolve(row["cif_path"]))
    except Exception: return out
    signal.signal(signal.SIGALRM, _alarm)
    rng = np.random.default_rng(abs(hash(row["id"])) % (2**32))
    for k in range(1, K + 1):
        perm = rng.permutation(len(s0)); shift = rng.random(3)
        s = Structure(s0.lattice, [s0[i].species for i in perm], [(s0[i].frac_coords + shift) % 1.0 for i in perm])
        r = dict(id=f"{row['id']}#a{k}", label=int(row["label"]), set="train", source_dir=row["source_dir"])
        try: tr = TextRep.from_input(s)
        except Exception: continue
        for rep in REPS:
            signal.alarm(180 if rep == "slices" else 60)
            try:
                v = tr.get_requested_text_reps([rep])[rep]; r[rep] = v if isinstance(v, str) and v else None
            except Exception: r[rep] = None
            finally: signal.alarm(0)
        out.append(r)
    return out

if __name__ == "__main__":
    import pandas as pd
    rows = [r for r in csv.DictReader(open(os.path.join(ROOT, "dataset_划分.csv"), encoding="utf-8-sig")) if r["set"] == "train"]
    t0 = time.time(); res = []
    with Pool(NPROC, maxtasksperchild=200) as pool:
        for i, r in enumerate(pool.imap_unordered(work, rows, chunksize=4)):
            res.extend(r)
            if (i + 1) % 1000 == 0: print(f"{i+1}/{len(rows)} {time.time()-t0:.0f}s", flush=True)
    aug = pd.DataFrame(res); base = pd.read_parquet(BASE)
    df = pd.concat([base, aug], ignore_index=True); df.to_parquet(OUT)
    print("aug rows", len(aug), "total", len(df), f"{time.time()-t0:.0f}s")
    for rep in REPS: print(rep, "aug ok", int(aug[rep].notna().sum()), "changed vs original:", float((aug[rep].values != aug.id.str.split("#").str[0].map(base.set_index("id")[rep]).values).mean().round(3)))