Spaces:
Sleeping

File size: 12,895 Bytes
01d09b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""
CIF Parser Module
Parses CIF files and extracts structural information for LLM processing.
"""
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass, field
import numpy as np

try:
    from pymatgen.core import Structure
    from pymatgen.io.cif import CifParser as PMGCifParser
    from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
    from pymatgen.analysis.local_env import CrystalNN
    PYMATGEN_AVAILABLE = True
except ImportError:
    PYMATGEN_AVAILABLE = False


@dataclass
class AtomSite:
    """Represents an atomic site in the crystal structure."""
    species: str
    wyckoff: Optional[str]
    frac_coords: Tuple[float, float, float]
    oxidation_state: Optional[int] = None
    coordination_number: Optional[int] = None
    coordination_env: Optional[str] = None  # e.g., "octahedral", "tetrahedral"


@dataclass
class LatticeParams:
    """Lattice parameters of the crystal."""
    a: float
    b: float
    c: float
    alpha: float
    beta: float
    gamma: float
    volume: float


@dataclass
class ParsedCIF:
    """Complete parsed CIF data structure."""
    # Basic info
    formula: str
    reduced_formula: str

    # Lattice
    lattice: LatticeParams

    # Symmetry
    space_group_symbol: str
    space_group_number: int
    crystal_system: str

    # Atoms
    atoms: List[AtomSite]
    n_atoms: int
    z_value: int  # Formula units per cell

    # Derived features
    density: float
    composition: Dict[str, float]  # Element: fraction
    oxidation_states: Optional[Dict[str, int]] = None
    structural_motifs: List[str] = field(default_factory=list)

    # Raw structure for further analysis
    _structure: Any = None


class CIFParser:
    """
    Parser for CIF files that extracts structural information
    suitable for LLM processing.
    """

    def __init__(self, analyze_coordination: bool = True):
        """
        Initialize the CIF parser.

        Args:
            analyze_coordination: Whether to analyze coordination environments
                                 (slower but provides more info)
        """
        if not PYMATGEN_AVAILABLE:
            raise ImportError(
                "pymatgen is required for CIF parsing. "
                "Install with: pip install pymatgen"
            )
        self.analyze_coordination = analyze_coordination

    def parse(self, cif_path: str | Path) -> ParsedCIF:
        """
        Parse a CIF file and extract structural information.

        Args:
            cif_path: Path to the CIF file

        Returns:
            ParsedCIF object containing all extracted information
        """
        cif_path = Path(cif_path)
        if not cif_path.exists():
            raise FileNotFoundError(f"CIF file not found: {cif_path}")

        # Parse with pymatgen
        parser = PMGCifParser(str(cif_path))
        structure = parser.get_structures()[0]

        return self.parse_structure(structure)

    def parse_from_string(self, cif_string: str) -> ParsedCIF:
        """
        Parse a CIF from string content.

        Args:
            cif_string: CIF file content as string

        Returns:
            ParsedCIF object
        """
        # Write to temp file and parse
        import tempfile
        import sys
        with tempfile.NamedTemporaryFile(mode='w', suffix='.cif', delete=False) as f:
            f.write(cif_string)
            temp_path = f.name

        try:
            return self.parse(temp_path)
        finally:
            try:
                Path(temp_path).unlink()
            except Exception as e:
                # Windows may have PermissionError if file handle not fully released
                print(f"[CIFParser] Warning: failed to delete temp CIF ({e})",
                      file=sys.stderr)

    def parse_structure(self, structure: "Structure") -> ParsedCIF:
        """
        Parse a pymatgen Structure object.

        Args:
            structure: pymatgen Structure object

        Returns:
            ParsedCIF object
        """
        import sys

        # --- Symmetry analysis (robust with P1 fallback) ---
        try:
            # Use relaxed tolerances for large/complex structures
            sga = SpacegroupAnalyzer(structure, symprec=1e-2, angle_tolerance=5.0)
            symmetrized = sga.get_symmetrized_structure()

            # Try to get Wyckoff symbols with length matching structure
            try:
                dataset = sga.get_symmetry_dataset()
                wyckoff_symbols = list(dataset["wyckoffs"])
                if len(wyckoff_symbols) != len(structure):
                    # Length mismatch - use symmetrized structure's symbols with padding
                    wyckoff_symbols = (
                        list(symmetrized.wyckoff_symbols) +
                        [None] * (len(structure) - len(symmetrized.wyckoff_symbols))
                    )[:len(structure)]
            except Exception:
                wyckoff_symbols = list(symmetrized.wyckoff_symbols)
                if len(wyckoff_symbols) != len(structure):
                    wyckoff_symbols = (
                        wyckoff_symbols +
                        [None] * (len(structure) - len(wyckoff_symbols))
                    )[:len(structure)]

            space_group_symbol = sga.get_space_group_symbol()
            space_group_number = sga.get_space_group_number()
            crystal_system = sga.get_crystal_system()

        except Exception as e:
            # Large/disordered structures may fail symmetry analysis - fallback to P1
            print(
                f"[CIFParser] Warning: symmetry analysis failed ({e}); "
                f"falling back to P1.",
                file=sys.stderr
            )
            sga = None
            wyckoff_symbols = [None] * len(structure)
            space_group_symbol = "P1"
            space_group_number = 1
            crystal_system = "triclinic"

        # Lattice parameters
        lattice = structure.lattice
        lattice_params = LatticeParams(
            a=lattice.a,
            b=lattice.b,
            c=lattice.c,
            alpha=lattice.alpha,
            beta=lattice.beta,
            gamma=lattice.gamma,
            volume=lattice.volume
        )

        # Coordination analysis (skip for large structures to avoid bottleneck)
        coord_info = {}
        n_atoms = len(structure)
        if self.analyze_coordination:
            if n_atoms > 150:
                print(
                    f"[CIFParser] Skipping CrystalNN analysis for large structure "
                    f"(n_atoms={n_atoms} > 150)",
                    file=sys.stderr
                )
            else:
                coord_info = self._analyze_coordination(structure)

        # Build atom list
        atoms = []
        for i, site in enumerate(structure):
            species = str(site.specie)

            # Get coordination info if available
            cn = coord_info.get(i, {}).get('cn')
            coord_env = coord_info.get(i, {}).get('env')

            atom = AtomSite(
                species=species,
                wyckoff=wyckoff_symbols[i] if i < len(wyckoff_symbols) else None,
                frac_coords=tuple(site.frac_coords),
                coordination_number=cn,
                coordination_env=coord_env
            )
            atoms.append(atom)

        # Composition
        comp = structure.composition
        comp_dict = {str(el): frac for el, frac in comp.fractional_composition.items()}

        # Oxidation states (skip for large structures - can be slow)
        if n_atoms > 150:
            print(
                f"[CIFParser] Skipping oxidation state guessing for large structure "
                f"(n_atoms={n_atoms} > 150)",
                file=sys.stderr
            )
            oxidation_states = None
        else:
            oxidation_states = self._guess_oxidation_states(structure)

        # Structural motifs
        motifs = self._identify_motifs(structure, coord_info)

        # Z value (formula units per cell)
        z_value = int(round(comp.num_atoms / comp.reduced_composition.num_atoms))

        return ParsedCIF(
            formula=comp.formula,
            reduced_formula=comp.reduced_formula,
            lattice=lattice_params,
            space_group_symbol=space_group_symbol,
            space_group_number=space_group_number,
            crystal_system=crystal_system,
            atoms=atoms,
            n_atoms=len(atoms),
            z_value=z_value,
            density=structure.density,
            composition=comp_dict,
            oxidation_states=oxidation_states,
            structural_motifs=motifs,
            _structure=structure
        )

    def _analyze_coordination(self, structure: "Structure") -> Dict[int, Dict]:
        """Analyze coordination environments for each site."""
        coord_info = {}

        try:
            cnn = CrystalNN()
            for i, site in enumerate(structure):
                try:
                    cn_info = cnn.get_cn_dict(structure, i)
                    total_cn = sum(cn_info.values())

                    # Determine coordination environment
                    env = self._classify_coordination(total_cn)

                    coord_info[i] = {
                        'cn': total_cn,
                        'env': env,
                        'neighbors': cn_info
                    }
                except Exception:
                    coord_info[i] = {'cn': None, 'env': None}
        except Exception:
            pass

        return coord_info

    def _classify_coordination(self, cn: float) -> str:
        """Classify coordination number to environment type."""
        cn = round(cn)
        env_map = {
            2: "linear",
            3: "trigonal planar",
            4: "tetrahedral",
            5: "trigonal bipyramidal",
            6: "octahedral",
            8: "cubic",
            12: "cuboctahedral"
        }
        return env_map.get(cn, f"{cn}-coordinated")

    def _guess_oxidation_states(self, structure: "Structure") -> Optional[Dict[str, int]]:
        """Attempt to guess oxidation states based on composition."""
        try:
            structure_with_ox = structure.copy()
            structure_with_ox.add_oxidation_state_by_guess()

            ox_states = {}
            for site in structure_with_ox:
                species = site.specie
                if hasattr(species, 'oxi_state'):
                    el = str(species.element)
                    ox_states[el] = int(species.oxi_state)

            return ox_states if ox_states else None
        except Exception:
            return None

    def _identify_motifs(
        self,
        structure: "Structure",
        coord_info: Dict
    ) -> List[str]:
        """Identify structural motifs based on coordination analysis."""
        motifs = []

        # Get unique coordination environments
        envs = {}
        for i, info in coord_info.items():
            species = str(structure[i].specie)
            env = info.get('env')
            if env:
                if species not in envs:
                    envs[species] = []
                if env not in envs[species]:
                    envs[species].append(env)

        # Generate motif descriptions
        for species, env_list in envs.items():
            for env in env_list:
                if 'octahedral' in env:
                    motifs.append(f"{species}O6 octahedra")
                elif 'tetrahedral' in env:
                    motifs.append(f"{species}O4 tetrahedra")

        # Check for common structural types
        formula = structure.composition.reduced_formula

        # Simple pattern matching for common structures
        if self._check_perovskite_like(structure):
            motifs.append("perovskite-like network")

        if self._check_layered(structure):
            motifs.append("layered structure")

        return motifs

    def _check_perovskite_like(self, structure: "Structure") -> bool:
        """Check if structure is perovskite-like (ABX3)."""
        comp = structure.composition.reduced_composition
        elements = list(comp.as_dict().keys())
        amounts = list(comp.as_dict().values())

        # ABX3 pattern: 1:1:3 ratio with 3 elements
        if len(elements) == 3:
            amounts_sorted = sorted(amounts)
            if amounts_sorted == [1, 1, 3]:
                return True
        return False

    def _check_layered(self, structure: "Structure") -> bool:
        """Check if structure appears layered based on lattice."""
        a, b, c = structure.lattice.a, structure.lattice.b, structure.lattice.c

        # Simple heuristic: one axis significantly larger
        lengths = sorted([a, b, c])
        if lengths[2] > 1.5 * lengths[1]:
            return True
        return False