MACE_finetuning_supplementary / spice /data /scripts /sample_one_per_molecule.py
ev-tlt's picture
Add files using upload-large-folder tool
3507a47 verified
Raw
History Blame
5.17 kB
#!/usr/bin/env python3
"""Sample one random configuration per molecule from SPICE XYZ dataset.
Groups configurations by molecule (using SMILES string), then randomly selects
one configuration per molecule.
Usage:
python sample_one_per_molecule.py --input data/train_large_neut_no_bad_clean.xyz
python sample_one_per_molecule.py --input data/train_large_neut_no_bad_clean.xyz --seed 123
"""
from __future__ import annotations
import argparse
import logging
import sys
from collections import defaultdict
from pathlib import Path
import numpy as np
from ase.io import read, write
def setup_logging() -> None:
"""Configure logging to stdout."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
stream=sys.stdout,
)
def get_molecule_id(atoms) -> str:
"""Extract molecule identifier from ASE Atoms object.
Uses SMILES string if available, otherwise falls back to sorted
chemical formula + total_charge.
"""
info = atoms.info
# Try SMILES first (most reliable molecular identifier)
if "smiles" in info:
return info["smiles"]
# Fallback: use chemical formula + charge
formula = atoms.get_chemical_formula(mode="hill")
charge = info.get("total_charge", 0)
return f"{formula}_charge{charge}"
def sample_one_per_molecule(
input_path: Path,
output_path: Path,
seed: int = 42,
) -> tuple[int, int]:
"""
Sample one random configuration per molecule from XYZ file.
Args:
input_path: Path to input XYZ file
output_path: Path to output XYZ file
seed: Random seed for reproducibility
Returns:
Tuple of (number of molecules, total original configurations)
"""
logging.info(f"Loading structures from {input_path.name}...")
all_atoms = read(str(input_path), index=":")
total_configs = len(all_atoms)
logging.info(f"Loaded {total_configs} configurations")
# Group by molecule
logging.info("Grouping configurations by molecule...")
molecule_groups = defaultdict(list)
for idx, atoms in enumerate(all_atoms):
mol_id = get_molecule_id(atoms)
molecule_groups[mol_id].append(idx)
num_molecules = len(molecule_groups)
logging.info(f"Found {num_molecules} unique molecules")
# Log distribution statistics
group_sizes = [len(indices) for indices in molecule_groups.values()]
logging.info(f"Configs per molecule: min={min(group_sizes)}, max={max(group_sizes)}, "
f"mean={np.mean(group_sizes):.1f}, median={np.median(group_sizes):.1f}")
# Randomly sample one configuration per molecule
logging.info(f"Sampling one configuration per molecule (seed={seed})...")
np.random.seed(seed)
sampled_indices = []
for mol_id, indices in molecule_groups.items():
chosen_idx = np.random.choice(indices)
sampled_indices.append(chosen_idx)
# Sort indices to maintain some order
sampled_indices = sorted(sampled_indices)
# Extract sampled structures
sampled_atoms = [all_atoms[i] for i in sampled_indices]
# Write output
logging.info(f"Writing {len(sampled_atoms)} structures to {output_path.name}...")
write(str(output_path), sampled_atoms, format="extxyz")
return num_molecules, total_configs
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--input",
type=str,
required=True,
help="Path to input XYZ file",
)
parser.add_argument(
"--output",
type=str,
default=None,
help="Path to output XYZ file (defaults to input_one_per_mol.xyz)",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed for reproducibility (default: 42)",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
setup_logging()
input_path = Path(args.input).expanduser().resolve()
if not input_path.is_file():
raise FileNotFoundError(f"Input file not found: {input_path}")
# Setup output path
if args.output:
output_path = Path(args.output).expanduser().resolve()
else:
output_path = input_path.parent / f"{input_path.stem}_one_per_mol.xyz"
output_path.parent.mkdir(parents=True, exist_ok=True)
logging.info(f"Input: {input_path}")
logging.info(f"Output: {output_path}")
logging.info(f"Random seed: {args.seed}")
logging.info("=" * 60)
num_molecules, total_configs = sample_one_per_molecule(
input_path=input_path,
output_path=output_path,
seed=args.seed,
)
logging.info("=" * 60)
logging.info(f"Done! Sampled {num_molecules} configurations from {total_configs} total")
logging.info(f"Reduction: {total_configs} -> {num_molecules} ({100*num_molecules/total_configs:.1f}%)")
logging.info(f"Output: {output_path}")
if __name__ == "__main__":
main()