| """
|
| 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
|
|
|
|
|
|
|
| from moftransformer.utils.prepare_data import prepare_data
|
| from moftransformer.utils.install_griday import install_griday
|
|
|
|
|
| _DUMMY_DOWNSTREAM = "lmdb_split"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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]
|
|
|
|
|
| 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
|
|
|
| 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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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}")
|
|
|
|
|
| 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}
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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}")
|
|
|
|
|
| print("\nStep 1: Verifying GRIDAY installation...")
|
| verify_griday_installation()
|
|
|
|
|
| print("\nStep 2: Loading all numeric targets from id_prop.csv...")
|
| targets_df, target_columns = load_all_targets(data_dir)
|
|
|
|
|
| print("\nStep 3: Verifying CIF files...")
|
| targets_df = verify_cif_files(data_dir, targets_df)
|
|
|
|
|
| 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")
|
|
|
|
|
| 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)
|
|
|
|
|
| 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,
|
| )
|
|
|
|
|
| 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,
|
| )
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
|
|