File size: 8,376 Bytes
b01d243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
256
257
258
259
260
261
262
263
264
#!/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()