"""Convert every structure in dataset_划分.csv to MatText text representations. Run inside venv-rep. Output: reps.parquet with one row per structure. Light representations and SLICES are computed separately so a SLICES failure does not lose the others. Each structure gets a wall-clock limit. """ import os, sys, csv, signal, time, json 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", "TF_NUM_INTRAOP_THREADS", "TF_NUM_INTEROP_THREADS"): os.environ.setdefault(v, "1") import warnings; warnings.filterwarnings("ignore") from multiprocessing import Pool ROOT = sys.argv[1] OUT = sys.argv[2] NPROC = int(sys.argv[3]) if len(sys.argv) > 3 else 32 LIGHT = ["composition", "cif_symmetrized", "cif_p1", "atom_sequences", "atom_sequences_plusplus", "crystal_text_llm", "zmatrix"] HEAVY = ["slices", "local_env"] LIMIT = {"slices": 180, "local_env": 120} 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 def work(row): from pymatgen.core import Structure from xtal2txt.core import TextRep out = dict(id=row["id"], label=int(row["label"]), set=row["set"], source_dir=row["source_dir"]) err = {} p = resolve(row["cif_path"]) try: s = Structure.from_file(p) out.update(formula=s.composition.reduced_formula, nsites=len(s), nelements=len(s.composition.elements), is_ordered=bool(s.is_ordered)) try: out["spacegroup"] = int(s.get_space_group_info(symprec=0.1)[1]) except Exception: out["spacegroup"] = None tr = TextRep.from_input(s) except Exception as e: out["error"] = json.dumps({"load": repr(e)[:200]}); return out signal.signal(signal.SIGALRM, _alarm) for rep in LIGHT + HEAVY: signal.alarm(LIMIT.get(rep, 60)) try: v = tr.get_requested_text_reps([rep])[rep] out[rep] = v if isinstance(v, str) and v else None if out[rep] is None: err[rep] = "empty" except TO: out[rep] = None; err[rep] = "timeout" except Exception as e: out[rep] = None; err[rep] = repr(e)[:200] finally: signal.alarm(0) out["error"] = json.dumps(err) if err else None return out if __name__ == "__main__": rows = list(csv.DictReader(open(os.path.join(ROOT, "dataset_划分.csv"), encoding="utf-8-sig"))) if len(sys.argv) > 4: rows = rows[: int(sys.argv[4])] t0 = time.time(); res = [] with Pool(NPROC, maxtasksperchild=200) as pool: for i, r in enumerate(pool.imap_unordered(work, rows, chunksize=4)): res.append(r) if (i + 1) % 500 == 0: print(f"{i+1}/{len(rows)} {time.time()-t0:.0f}s", flush=True) import pandas as pd df = pd.DataFrame(res) order = {r["id"]: i for i, r in enumerate(rows)} df = df.sort_values("id", key=lambda c: c.map(order)).reset_index(drop=True) df.to_parquet(OUT) print("rows", len(df), "time", f"{time.time()-t0:.0f}s") for rep in LIGHT + HEAVY: if rep in df: print(f"{rep:26s} ok={df[rep].notna().sum()} missing={df[rep].isna().sum()}")