File size: 8,111 Bytes
2e05cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
"""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()  # Skip comment
                for _ in range(natoms):
                    f.readline()  # Skip atom lines
                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
    
    # Set random seed for reproducibility
    np.random.seed(seed)
    
    # Generate random indices
    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)  # Sort to maintain some order
    
    # Select structures
    sampled_atoms = [all_atoms[i] for i in indices]
    
    # Write to file
    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")
    
    # 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]
        
        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}")
    
    # 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 - use 'random_subsets' folder by default
    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}")
    
    # Use '_random_' prefix by default
    prefix = args.prefix or f"{input_path.stem}_random_"
    
    # Get largest subset size and create it using random sampling
    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,
    )
    
    # 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_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()