File size: 5,173 Bytes
3507a47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()