| |
| """Create nested random-sampled structure subsets from SPICE XYZ datasets. |
| |
| Uses random sampling for subset selection (no descriptor-based selection). |
| Smaller subsets are nested within larger ones (strict prefixes). |
| |
| Usage: |
| python sample_nested_subsets_random.py --input data/train_large_neut_no_bad_clean.xyz --percentages 50 20 10 5 1 |
| python sample_nested_subsets_random.py --input data/test_large_neut_all.xyz --percentages 50 20 10 5 1 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import logging |
| import sys |
| 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 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() |
| for _ in range(natoms): |
| f.readline() |
| count += 1 |
| except (ValueError, StopIteration): |
| break |
| return count |
|
|
|
|
| def random_sample_structures( |
| input_path: Path, |
| output_path: Path, |
| num_samples: int, |
| seed: int = 42, |
| ) -> list: |
| """ |
| Randomly sample structures from an XYZ file. |
| |
| Args: |
| input_path: Path to input XYZ file |
| output_path: Path to output XYZ file |
| num_samples: Number of samples to select |
| seed: Random seed for reproducibility |
| |
| Returns: |
| List of sampled ASE Atoms objects |
| """ |
| logging.info(f"Loading structures from {input_path.name}...") |
| all_atoms = read(str(input_path), index=":") |
| total = len(all_atoms) |
| |
| if num_samples > total: |
| logging.warning(f"Requested {num_samples} samples but only {total} available. Using all structures.") |
| num_samples = total |
| |
| |
| np.random.seed(seed) |
| |
| |
| logging.info(f"Randomly sampling {num_samples} structures from {total} total...") |
| indices = np.random.choice(total, size=num_samples, replace=False) |
| indices = np.sort(indices) |
| |
| |
| sampled_atoms = [all_atoms[i] for i in indices] |
| |
| |
| logging.info(f"Writing {len(sampled_atoms)} structures to {output_path.name}...") |
| write(str(output_path), sampled_atoms, format="extxyz") |
| |
| return sampled_atoms |
|
|
|
|
| def create_nested_subsets_from_parent( |
| parent_atoms: list, |
| output_dir: Path, |
| base_name: str, |
| subset_sizes: dict[float, int], |
| ) -> None: |
| """ |
| Create nested subsets from the parent atom list. |
| |
| Args: |
| parent_atoms: List of ASE Atoms objects from the largest subset |
| 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"Creating nested subsets from {len(parent_atoms)} parent structures") |
| |
| |
| 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] |
| |
| write(str(output_path), subset_atoms, format="extxyz") |
| logging.info(f"Wrote {len(subset_atoms)} structures to {output_path.name}") |
|
|
|
|
| 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 'random_subsets' in same dir as input)", |
| ) |
| parser.add_argument( |
| "--prefix", |
| type=str, |
| default=None, |
| help="Output file prefix (defaults to input filename + _random_)", |
| ) |
| 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}") |
| |
| |
| 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") |
| |
| |
| total_structures = count_structures(input_path) |
| logging.info(f"Total structures in dataset: {total_structures}") |
| |
| |
| 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") |
| |
| |
| logging.info("\nPlanned subsets:") |
| for pct in sorted(subset_sizes.keys(), reverse=True): |
| size = subset_sizes[pct] |
| logging.info(f" {pct}% = {size} structures") |
| |
| |
| if args.output_dir: |
| output_dir = Path(args.output_dir).expanduser().resolve() |
| else: |
| output_dir = input_path.parent / "random_subsets" |
| |
| output_dir.mkdir(parents=True, exist_ok=True) |
| logging.info(f"Output directory: {output_dir}") |
| |
| |
| prefix = args.prefix or f"{input_path.stem}_random_" |
| |
| |
| 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 random sampling") |
| logging.info(f"Random seed: {args.seed}") |
| logging.info(f"{'='*60}\n") |
| |
| largest_output = output_dir / f"{prefix}{largest_pct}pct_{largest_size}.xyz" |
| |
| parent_atoms = random_sample_structures( |
| input_path=input_path, |
| output_path=largest_output, |
| num_samples=largest_size, |
| seed=args.seed, |
| ) |
| |
| |
| 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_atoms=parent_atoms, |
| output_dir=output_dir, |
| base_name=prefix, |
| subset_sizes=smaller_sizes, |
| ) |
| |
| logging.info("\n" + "="*60) |
| logging.info("All nested random subsets created successfully!") |
| logging.info(f"Output location: {output_dir}") |
| logging.info("="*60) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|