File size: 18,133 Bytes
24407a9 | 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | """
MOFTransformer Preprocessor — LMDB Edition
Prepares raw MOF dataset for training by processing CIF files and packing
the results into three LMDB files (train / val / test), one file per split.
All numeric target columns from id_prop.csv are stored in the LMDB.
The target variable to predict is chosen at training time, not here.
LMDB schema per file:
b'__metadata__' → pickle dict {target_columns: [...], n_samples: int}
b'__keys__' → pickle list [cif_id, ...]
b'__targets__' → pickle dict {cif_id: {col: float_or_nan, ...}}
b'{cif_id}' → pickle dict {cif_id,
atom_num, nbr_idx, nbr_dist,
uni_idx, uni_count,
grid_header, griddata16}
Author: MOFTransformer Team
Date: 2026-03-16
"""
import os
import sys
import json
import shutil
import pickle
import argparse
from pathlib import Path
from typing import Optional, Tuple, List
import pandas as pd
import numpy as np
import lmdb
# Use the pip-installed moftransformer for preprocessing (has compiled GRIDAY).
# The local MOFTransformer copy is only used by trainer.py (patched modules).
from moftransformer.utils.prepare_data import prepare_data
from moftransformer.utils.install_griday import install_griday
# Dummy downstream name used internally for prepare_data splitting.
_DUMMY_DOWNSTREAM = "lmdb_split"
# ---------------------------------------------------------------------------
# GRIDAY helpers
# ---------------------------------------------------------------------------
def verify_griday_installation() -> None:
"""Verify that GRIDAY is installed, install if necessary."""
try:
from moftransformer import __root_dir__
griday_path = os.path.join(__root_dir__, "libs/GRIDAY/scripts/grid_gen")
if not os.path.exists(griday_path):
print("GRIDAY not found. Installing GRIDAY...")
install_griday()
except ImportError as e:
print(f"Error importing GRIDAY: {e}")
print("Attempting to install GRIDAY...")
install_griday()
# ---------------------------------------------------------------------------
# CSV / CIF validation helpers
# ---------------------------------------------------------------------------
def load_all_targets(data_dir: Path) -> Tuple[pd.DataFrame, List[str]]:
"""
Load id_prop.csv and return a DataFrame with all numeric target columns.
Returns
-------
Tuple[pd.DataFrame, List[str]]
DataFrame with columns [cif_id, col1, col2, ...] and list of target
column names. Values may be NaN where data is missing.
"""
id_prop_path = data_dir / "id_prop.csv"
if not id_prop_path.exists():
raise FileNotFoundError(f"id_prop.csv not found at {id_prop_path}")
df = pd.read_csv(id_prop_path)
if df.empty:
raise ValueError("id_prop.csv is empty")
if df.shape[1] < 2:
raise ValueError(
f"id_prop.csv must have at least 2 columns. Found {df.shape[1]}."
)
cif_id_col = df.columns[0]
# Detect numeric columns (excluding the cif_id column)
numeric_cols = []
for col in df.columns[1:]:
converted = pd.to_numeric(df[col], errors="coerce")
if converted.notna().sum() > 0:
numeric_cols.append(col)
df[col] = converted # ensure numeric dtype
if not numeric_cols:
raise ValueError("No numeric target columns found in id_prop.csv")
result = df[[cif_id_col] + numeric_cols].copy()
result = result.rename(columns={cif_id_col: "cif_id"})
result["cif_id"] = result["cif_id"].astype(str)
result = result.set_index("cif_id")
print(f"Loaded {len(result)} rows from id_prop.csv")
print(f"Found {len(numeric_cols)} numeric target columns:")
for col in numeric_cols:
n_valid = result[col].notna().sum()
print(f" {col:50s} {n_valid}/{len(result)} non-NaN")
return result, numeric_cols
def verify_cif_files(data_dir: Path, df: pd.DataFrame) -> pd.DataFrame:
"""Drop rows whose CIF file is missing; return updated DataFrame."""
raw_dir = data_dir / "raw"
if not raw_dir.exists():
raise FileNotFoundError(f"Raw CIF directory not found at {raw_dir}")
cif_files = {f.stem for f in raw_dir.glob("*.cif")}
print(f"\nFound {len(cif_files)} CIF files in raw/")
valid_ids = set(df.index) & cif_files
missing = set(df.index) - cif_files
if missing:
print(f"Warning: {len(missing)} entries have no CIF file and will be skipped")
filtered = df.loc[list(valid_ids)].copy()
print(f"Valid samples: {len(filtered)}")
if len(filtered) == 0:
raise ValueError("No valid samples found after CIF verification.")
return filtered
def create_dummy_raw_json(df: pd.DataFrame, raw_dir: Path) -> None:
"""
Write raw_{DUMMY}.json (cif_id → 0.0) so prepare_data can split the data.
All CIF IDs present in the DataFrame are included.
"""
dummy_data = {cif_id: 0.0 for cif_id in df.index}
json_path = raw_dir / f"raw_{_DUMMY_DOWNSTREAM}.json"
with open(json_path, "w") as f:
json.dump(dummy_data, f, indent=2)
print(f"Created dummy split JSON: {json_path} ({len(dummy_data)} entries)")
def create_filtered_id_prop(df: pd.DataFrame, raw_dir: Path) -> None:
"""Write a minimal id_prop.csv (cif_id, dummy_target) for prepare_data."""
csv_df = pd.DataFrame({"cif_id": df.index, _DUMMY_DOWNSTREAM: 0.0})
csv_path = raw_dir / "id_prop.csv"
csv_df.to_csv(csv_path, index=False)
print(f"Created {csv_path}")
# ---------------------------------------------------------------------------
# Data preparation (calls MOFTransformer's prepare_data)
# ---------------------------------------------------------------------------
def run_data_preparation(
raw_dir: Path,
processed_dir: Path,
train_fraction: float,
test_fraction: float,
seed: int,
) -> None:
"""Run MOFTransformer's prepare_data to build graph / grid embeddings."""
print("\nStarting data preparation with MOFTransformer utilities...")
print(f" Raw directory : {raw_dir}")
print(f" Processed dir : {processed_dir}")
print(f" Downstream : {_DUMMY_DOWNSTREAM}")
prepare_data(
root_cifs=raw_dir,
root_dataset=processed_dir,
downstream=_DUMMY_DOWNSTREAM,
train_fraction=train_fraction,
test_fraction=test_fraction,
seed=seed,
)
expected = [
processed_dir / f"train_{_DUMMY_DOWNSTREAM}.json",
processed_dir / f"val_{_DUMMY_DOWNSTREAM}.json",
processed_dir / f"test_{_DUMMY_DOWNSTREAM}.json",
]
print("\nVerifying processed split files...")
for p in expected:
if p.exists() and p.stat().st_size > 0:
print(f" OK {p.name}")
else:
raise RuntimeError(
f"Data preparation did not produce expected file: {p}"
)
print("Data preparation completed!")
# ---------------------------------------------------------------------------
# LMDB packing
# ---------------------------------------------------------------------------
def _estimate_map_size(split_dir: Path, cif_ids: list) -> int:
"""Estimate LMDB map_size from file sizes × 4 safety margin (virtual mem)."""
total = 0
for cif_id in cif_ids:
for ext in (".graphdata", ".griddata16", ".grid"):
f = split_dir / f"{cif_id}{ext}"
if f.exists():
total += f.stat().st_size
return max(int(total * 4), 1 << 30)
def pack_split_to_lmdb(
processed_dir: Path,
split: str,
targets_df: pd.DataFrame,
target_columns: List[str],
output_path: Path,
) -> None:
"""
Pack one split into an LMDB file.
Parameters
----------
processed_dir : Path
Directory produced by prepare_data.
split : str
'train', 'val', or 'test'.
targets_df : pd.DataFrame
Index = cif_id, columns = all numeric target columns (may contain NaN).
target_columns : List[str]
Ordered list of target column names to store.
output_path : Path
Destination LMDB file path.
"""
json_path = processed_dir / f"{split}_{_DUMMY_DOWNSTREAM}.json"
if not json_path.exists():
raise FileNotFoundError(f"Split JSON not found: {json_path}")
with open(json_path) as f:
split_cif_ids: list = list(json.load(f).keys())
split_dir = processed_dir / split
if not split_dir.exists():
raise FileNotFoundError(f"Split directory not found: {split_dir}")
n = len(split_cif_ids)
print(f"\n Packing '{split}' split → {output_path.name}")
print(f" Samples in split: {n}")
# Build targets lookup: {cif_id: {col: float_or_nan}}
all_targets: dict = {}
for cif_id in split_cif_ids:
if cif_id in targets_df.index:
row = targets_df.loc[cif_id]
all_targets[cif_id] = {
col: float(row[col]) if pd.notna(row[col]) else float("nan")
for col in target_columns
}
else:
all_targets[cif_id] = {col: float("nan") for col in target_columns}
# Coverage stats
for col in target_columns[:5]:
n_valid = sum(1 for v in all_targets.values() if not np.isnan(v[col]))
print(f" {col[:50]:50s} {n_valid}/{n} non-NaN")
if len(target_columns) > 5:
print(f" ... ({len(target_columns) - 5} more columns)")
map_size = _estimate_map_size(split_dir, split_cif_ids)
print(f" LMDB map_size : {map_size / 1e9:.2f} GB (virtual)")
metadata = {
"target_columns": target_columns,
"n_samples": n,
}
env = lmdb.open(
str(output_path),
map_size=map_size,
subdir=False,
readonly=False,
meminit=False,
map_async=True,
)
missing_files = []
written = 0
with env.begin(write=True) as txn:
txn.put(b"__metadata__", pickle.dumps(metadata, protocol=4))
txn.put(b"__keys__", pickle.dumps(split_cif_ids, protocol=4))
txn.put(b"__targets__", pickle.dumps(all_targets, protocol=4))
for cif_id in split_cif_ids:
graph_path = split_dir / f"{cif_id}.graphdata"
grid_path = split_dir / f"{cif_id}.grid"
griddata_path = split_dir / f"{cif_id}.griddata16"
missing = [p for p in (graph_path, grid_path, griddata_path) if not p.exists()]
if missing:
missing_files.extend(str(p) for p in missing)
continue
with open(graph_path, "rb") as fh:
graphdata = pickle.load(fh)
grid_header = grid_path.read_text()
with open(griddata_path, "rb") as fh:
griddata16 = pickle.load(fh)
sample = {
"cif_id": cif_id,
"atom_num": graphdata[1],
"nbr_idx": graphdata[2],
"nbr_dist": graphdata[3],
"uni_idx": graphdata[4],
"uni_count": graphdata[5],
"grid_header": grid_header,
"griddata16": griddata16,
}
txn.put(cif_id.encode(), pickle.dumps(sample, protocol=4))
written += 1
env.sync()
env.close()
if missing_files:
print(f" WARNING: {len(missing_files)} files missing, samples skipped:")
for mf in missing_files[:10]:
print(f" {mf}")
lmdb_size_mb = output_path.stat().st_size / 1e6
print(f" Written {written}/{n} samples ({lmdb_size_mb:.1f} MB on disk)")
def pack_all_splits_to_lmdb(
processed_dir: Path,
targets_df: pd.DataFrame,
target_columns: List[str],
output_prefix: str,
) -> dict:
"""Pack train / val / test into separate LMDB files."""
prefix = Path(output_prefix)
prefix.parent.mkdir(parents=True, exist_ok=True)
paths = {}
for split in ("train", "val", "test"):
out = prefix.parent / f"{prefix.name}_{split}.lmdb"
pack_split_to_lmdb(processed_dir, split, targets_df, target_columns, out)
paths[split] = out
return paths
# ---------------------------------------------------------------------------
# Main preprocessing pipeline
# ---------------------------------------------------------------------------
def preprocess_dataset(
data_dir: str,
output_prefix: str,
train_fraction: float = 0.8,
test_fraction: float = 0.1,
seed: int = 42,
) -> dict:
"""
Main preprocessing function.
Reads ALL numeric columns from id_prop.csv and stores them in the LMDB.
The target variable is chosen at training time via --target-column.
Produces:
{output_prefix}_train.lmdb
{output_prefix}_val.lmdb
{output_prefix}_test.lmdb
"""
print("=" * 60)
print("MOFTransformer Preprocessor — LMDB Edition")
print("=" * 60)
data_dir = Path(data_dir).resolve()
output_prefix = str(Path(output_prefix).resolve())
print(f"\nData directory : {data_dir}")
print(f"Output prefix : {output_prefix}")
print(f"Train / Test : {train_fraction} / {test_fraction} seed={seed}")
# Step 1
print("\nStep 1: Verifying GRIDAY installation...")
verify_griday_installation()
# Step 2
print("\nStep 2: Loading all numeric targets from id_prop.csv...")
targets_df, target_columns = load_all_targets(data_dir)
# Step 3
print("\nStep 3: Verifying CIF files...")
targets_df = verify_cif_files(data_dir, targets_df)
# Step 4
print("\nStep 4: Setting up working directory...")
work_dir = data_dir / "preprocessed_work"
raw_dir = work_dir / "raw"
processed_dir = work_dir / "processed"
if work_dir.exists():
shutil.rmtree(work_dir)
for d in (work_dir, raw_dir, processed_dir):
d.mkdir(parents=True, exist_ok=True)
source_raw = data_dir / "raw"
for cif_id in targets_df.index:
shutil.copy2(source_raw / f"{cif_id}.cif", raw_dir / f"{cif_id}.cif")
print(f"Copied {len(targets_df)} CIF files")
# Step 5
print("\nStep 5: Creating dummy split JSON for prepare_data...")
create_dummy_raw_json(targets_df, raw_dir)
create_filtered_id_prop(targets_df, raw_dir)
# Step 6
print("\nStep 6: Running data preparation (graph + grid embeddings)...")
run_data_preparation(
raw_dir=raw_dir,
processed_dir=processed_dir,
train_fraction=train_fraction,
test_fraction=test_fraction,
seed=seed,
)
# Step 7
print("\nStep 7: Packing into LMDB files...")
lmdb_paths = pack_all_splits_to_lmdb(
processed_dir=processed_dir,
targets_df=targets_df,
target_columns=target_columns,
output_prefix=output_prefix,
)
# Step 8
print("\nStep 8: Cleaning up working directory...")
shutil.rmtree(work_dir)
print("Working directory removed")
print("\n" + "=" * 60)
print("Preprocessing completed!")
print(f"Stored {len(target_columns)} target columns:")
for col in target_columns:
print(f" {col}")
print("\nOutput LMDB files:")
for split, path in lmdb_paths.items():
size_mb = path.stat().st_size / 1e6
print(f" {split:5s}: {path} ({size_mb:.1f} MB)")
print("=" * 60)
return lmdb_paths
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Preprocess MOF dataset and store ALL numeric targets in LMDB files. "
"The target variable to predict is chosen at training time."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python preprocessor.py \\
--data-dir ./qmof_cif/ \\
--output-prefix ./output/qmof_pmt_lmdb \\
--train-fraction 0.8 --test-fraction 0.1
# Produces:
# ./output/qmof_pmt_lmdb_train.lmdb
# ./output/qmof_pmt_lmdb_val.lmdb
# ./output/qmof_pmt_lmdb_test.lmdb
#
# Each LMDB stores ALL numeric columns from id_prop.csv.
# Choose which target to train on via --target-column in trainer.py.
""",
)
parser.add_argument(
"--data-dir", type=str, required=True,
help="Dataset directory with id_prop.csv and raw/ folder",
)
parser.add_argument(
"--output-prefix", type=str, required=True,
help="Base path prefix for output LMDB files (no extension)",
)
parser.add_argument(
"--train-fraction", type=float, default=0.8,
help="Fraction for training (default: 0.8)",
)
parser.add_argument(
"--test-fraction", type=float, default=0.1,
help="Fraction for testing (default: 0.1)",
)
parser.add_argument(
"--seed", type=int, default=42,
help="Random seed (default: 42)",
)
return parser.parse_args()
def main():
args = parse_arguments()
try:
preprocess_dataset(
data_dir=args.data_dir,
output_prefix=args.output_prefix,
train_fraction=args.train_fraction,
test_fraction=args.test_fraction,
seed=args.seed,
)
except Exception as e:
print(f"\nERROR: Preprocessing failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()
|