""" 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