#!/usr/bin/env python3 """Create nested FPS-based structure subsets from SPICE XYZ datasets. Uses MACE's fine_tuning_select utility with FPS for diverse subset selection. Smaller subsets are nested within larger ones (strict prefixes). Usage: python sample_nested_subsets.py --input data/train_large_neut_no_bad_clean.xyz --percentages 50 20 10 5 1 python sample_nested_subsets.py --input data/test_large_neut_all.xyz --percentages 50 20 10 5 1 """ from __future__ import annotations import argparse import logging import subprocess import sys from pathlib import Path import numpy as np from ase.io import read def setup_logging() -> None: """Configure logging to stdout.""" logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s", stream=sys.stdout, ) def count_structures(filepath: Path) -> int: """Count the number of structures in an XYZ file efficiently.""" logging.info(f"Counting structures in {filepath.name}...") count = 0 with open(filepath, "r") as f: while True: line = f.readline() if not line: break try: natoms = int(line.strip()) f.readline() # Skip comment for _ in range(natoms): f.readline() # Skip atom lines count += 1 except (ValueError, StopIteration): break return count def run_mace_fps_selection( input_path: Path, output_path: Path, num_samples: int, model: str = "/home/s5f/ev333.s5f/work/mace-omat-0-medium.model", device: str = "cpu", seed: int = 42, ) -> None: """ Run MACE's fine_tuning_select tool with FPS sampling. Args: input_path: Path to input XYZ file output_path: Path to output XYZ file num_samples: Number of samples to select model: MACE model to use for descriptor computation device: Device to use (cpu or cuda) seed: Random seed """ cmd = [ "python", "-m", "mace.cli.fine_tuning_select", "--configs_pt", str(input_path), "--output", str(output_path), "--num_samples", str(num_samples), "--subselect", "fps", "--model", model, "--device", device, "--seed", str(seed), "--filtering_type", "none", "--disallow_random_padding", ] logging.info(f"Running FPS selection for {num_samples} samples...") logging.debug(f"Command: {' '.join(cmd)}") result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: logging.error(f"FPS selection failed: {result.stderr}") raise RuntimeError(f"MACE fine_tuning_select failed with code {result.returncode}") logging.info(f"FPS selection completed successfully") def create_nested_subsets_from_parent( parent_file: Path, output_dir: Path, base_name: str, subset_sizes: dict[float, int], ) -> None: """ Create nested subsets by reading from the largest parent file. Args: parent_file: Path to the largest subset file output_dir: Directory for output files base_name: Base name for output files subset_sizes: Dict mapping percentages to counts (excluding the largest) """ logging.info(f"Loading parent file: {parent_file}") parent_atoms = read(str(parent_file), index=":") logging.info(f"Loaded {len(parent_atoms)} structures from parent") # Create smaller nested subsets for pct in sorted(subset_sizes.keys(), reverse=True): size = subset_sizes[pct] output_path = output_dir / f"{base_name}{pct}pct_{size}.xyz" logging.info(f"Creating {pct}% subset ({size} structures)...") subset_atoms = parent_atoms[:size] from ase.io import write write(str(output_path), subset_atoms, format="extxyz") logging.info(f"Wrote {len(subset_atoms)} structures to {output_path}") 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( "--percentages", nargs="+", type=float, required=True, help="Subset percentages (e.g., 50 20 10 5 1 for 50%%, 20%%, etc.)", ) parser.add_argument( "--output-dir", type=str, default=None, help="Output directory (defaults to same as input)", ) parser.add_argument( "--prefix", type=str, default=None, help="Output file prefix (defaults to input filename + _subset_)", ) parser.add_argument( "--model", type=str, default="/home/s5f/ev333.s5f/work/mace-omat-0-medium.model", help="MACE model for descriptor computation (default: /home/s5f/ev333.s5f/work/mace-omat-0-medium.model)", ) parser.add_argument( "--device", type=str, default="cpu", choices=["cpu", "cuda"], help="Device to use (default: cpu)", ) 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}") # Validate and sort percentages percentages = sorted([p for p in args.percentages if p > 0], reverse=True) if not percentages: raise ValueError("At least one positive percentage must be provided") if any(p > 100 for p in percentages): raise ValueError("Percentages must be <= 100") # Count total structures total_structures = count_structures(input_path) logging.info(f"Total structures in dataset: {total_structures}") # Calculate subset sizes subset_sizes = {} for pct in percentages: size = int(np.round(total_structures * pct / 100)) if size == 0: logging.warning(f"Percentage {pct}% results in 0 structures, skipping") continue subset_sizes[pct] = size if not subset_sizes: raise ValueError("No valid subset sizes after conversion") # Log planned subsets logging.info("\nPlanned subsets:") for pct in sorted(subset_sizes.keys(), reverse=True): size = subset_sizes[pct] logging.info(f" {pct}% = {size} structures") # Setup output output_dir = Path(args.output_dir).expanduser().resolve() if args.output_dir else input_path.parent output_dir.mkdir(parents=True, exist_ok=True) prefix = args.prefix or f"{input_path.stem}_subset_" # Get largest subset size and create it using MACE FPS largest_pct = max(subset_sizes.keys()) largest_size = subset_sizes[largest_pct] logging.info(f"\n{'='*60}") logging.info(f"Creating largest subset ({largest_pct}% = {largest_size} structures) using MACE FPS") logging.info(f"{'='*60}\n") largest_output = output_dir / f"{prefix}{largest_pct}pct_{largest_size}.xyz" run_mace_fps_selection( input_path=input_path, output_path=largest_output, num_samples=largest_size, model=args.model, device=args.device, seed=args.seed, ) # Create smaller nested subsets from the largest one if len(subset_sizes) > 1: logging.info(f"\n{'='*60}") logging.info("Creating nested smaller subsets from largest subset") logging.info(f"{'='*60}\n") smaller_sizes = {pct: size for pct, size in subset_sizes.items() if pct < largest_pct} create_nested_subsets_from_parent( parent_file=largest_output, output_dir=output_dir, base_name=prefix, subset_sizes=smaller_sizes, ) logging.info("\n" + "="*60) logging.info("All nested subsets created successfully!") logging.info("="*60) if __name__ == "__main__": main()