File size: 9,824 Bytes
db32e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Tool functions for Spec-Agent: Chemical validation and mass calculation.
These tools are called by the LLM agent during the ReAct loop.
"""

from typing import Dict, Optional, Tuple
from rdkit import Chem
from rdkit.Chem import Descriptors

try:
    import selfies as sf
    SELFIES_AVAILABLE = True
except ImportError:
    SELFIES_AVAILABLE = False
    sf = None


def validate_smiles(smiles: str) -> Dict[str, str]:
    """
    Validate a SMILES string and return detailed error information if invalid.
    
    Args:
        smiles: SMILES string to validate
        
    Returns:
        Dictionary with:
        - "valid": "True" or "False"
        - "message": Detailed error message if invalid, "Valid SMILES" if valid
        - "error_type": Type of error (e.g., "Unclosed ring", "Invalid atom", etc.)
    """
    if not smiles or not isinstance(smiles, str):
        return {
            "valid": "False",
            "message": f"Invalid input: expected string, got {type(smiles)}",
            "error_type": "TypeError"
        }
    
    # Try to parse SMILES
    mol = Chem.MolFromSmiles(smiles)
    
    if mol is None:
        # Try to get more detailed error information
        try:
            # Attempt to sanitize to get specific error
            mol = Chem.MolFromSmiles(smiles, sanitize=False)
            if mol is None:
                return {
                    "valid": "False",
                    "message": f"SMILES '{smiles}' cannot be parsed. Check for syntax errors (unmatched brackets, invalid characters).",
                    "error_type": "ParseError"
                }
            
            # Try sanitization to get specific error
            try:
                Chem.SanitizeMol(mol)
            except Exception as e:
                error_msg = str(e)
                if "Unclosed ring" in error_msg or "ring" in error_msg.lower():
                    return {
                        "valid": "False",
                        "message": f"Unclosed ring detected in SMILES '{smiles}'. Check ring closure numbers.",
                        "error_type": "RingError"
                    }
                elif "valence" in error_msg.lower():
                    return {
                        "valid": "False",
                        "message": f"Valence error in SMILES '{smiles}'. Atom has incorrect number of bonds.",
                        "error_type": "ValenceError"
                    }
                else:
                    return {
                        "valid": "False",
                        "message": f"Sanitization error: {error_msg}",
                        "error_type": "SanitizationError"
                    }
        except Exception as e:
            return {
                "valid": "False",
                "message": f"Cannot parse SMILES '{smiles}': {str(e)}",
                "error_type": "ParseError"
            }
    
    # SMILES is valid
    return {
        "valid": "True",
        "message": "Valid SMILES",
        "error_type": "None"
    }


def calculate_mass_error(smiles: str, target_mass: float, tolerance_ppm: float = 10.0) -> Dict[str, str]:
    """
    Calculate the mass error between a SMILES molecule and target mass.
    
    Args:
        smiles: SMILES string
        target_mass: Target molecular mass (Da)
        tolerance_ppm: Mass tolerance in parts per million (default: 10 ppm)
        
    Returns:
        Dictionary with:
        - "matches": "True" or "False"
        - "predicted_mass": Calculated mass
        - "target_mass": Target mass
        - "error_da": Absolute error in Da
        - "error_ppm": Error in ppm
        - "message": Human-readable message with suggestions
    """
    # First validate SMILES
    validation = validate_smiles(smiles)
    if validation["valid"] == "False":
        return {
            "matches": "False",
            "predicted_mass": "0.0",
            "target_mass": str(target_mass),
            "error_da": "N/A",
            "error_ppm": "N/A",
            "message": f"Cannot calculate mass: {validation['message']}"
        }
    
    # Calculate exact mass
    mol = Chem.MolFromSmiles(smiles)
    predicted_mass = Descriptors.ExactMolWt(mol)
    
    # Calculate errors
    error_da = abs(predicted_mass - target_mass)
    error_ppm = (error_da / target_mass) * 1e6 if target_mass > 0 else float('inf')
    
    # Check if within tolerance
    matches = error_ppm <= tolerance_ppm
    
    # Generate helpful message
    if matches:
        message = f"Mass matches! Predicted: {predicted_mass:.4f} Da, Target: {target_mass:.4f} Da (Error: {error_ppm:.2f} ppm)"
    else:
        diff = predicted_mass - target_mass
        suggestions = []
        
        # Common mass differences and their meanings
        common_diffs = {
            1.0078: "Missing H+ (protonation)",
            -1.0078: "Extra H+",
            15.9949: "Missing O (oxygen)",
            -15.9949: "Extra O",
            14.0157: "Missing CH2 (methylene)",
            -14.0157: "Extra CH2",
            18.0106: "Missing H2O (water)",
            -18.0106: "Extra H2O",
            28.0313: "Missing C2H4 (ethylene)",
            -28.0313: "Extra C2H4",
        }
        
        # Find closest common difference
        for common_diff, meaning in common_diffs.items():
            if abs(diff - common_diff) < 0.1:
                suggestions.append(meaning)
        
        if not suggestions:
            if diff > 0:
                if abs(diff) > 200:
                    suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Remove significant structural elements (rings, large functional groups).")
                elif abs(diff) > 50:
                    suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Remove multiple atoms or simplify rings.")
                else:
                    suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Consider removing atoms or groups.")
            else:
                if abs(diff) > 200:
                    suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Add significant structural elements (rings, peptide bonds, large functional groups). Use reference molecules as templates.")
                elif abs(diff) > 50:
                    suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Add multiple atoms or rings. The molecule needs to be larger and more complex.")
                else:
                    suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Consider adding atoms or groups.")
        
        message = (
            f"Mass mismatch! Predicted: {predicted_mass:.4f} Da, Target: {target_mass:.4f} Da. "
            f"Error: {error_ppm:.2f} ppm (tolerance: {tolerance_ppm} ppm). "
            f"Suggestions: {', '.join(suggestions)}"
        )
    
    return {
        "matches": "True" if matches else "False",
        "predicted_mass": f"{predicted_mass:.4f}",
        "target_mass": f"{target_mass:.4f}",
        "error_da": f"{error_da:.4f}",
        "error_ppm": f"{error_ppm:.2f}",
        "message": message
    }


def selfies_to_smiles(selfies_str: str) -> Tuple[bool, str]:
    """
    Convert SELFIES string to SMILES. SELFIES guarantees validity.
    
    Args:
        selfies_str: SELFIES string
        
    Returns:
        Tuple of (success: bool, smiles: str)
    """
    if not SELFIES_AVAILABLE:
        return False, "SELFIES library not available"
    
    try:
        smiles = sf.decoder(selfies_str)
        return True, smiles
    except Exception as e:
        return False, f"SELFIES decode error: {str(e)}"


def smiles_to_selfies(smiles: str) -> Tuple[bool, str]:
    """
    Convert SMILES string to SELFIES.
    
    Args:
        smiles: SMILES string
        
    Returns:
        Tuple of (success: bool, selfies: str)
    """
    if not SELFIES_AVAILABLE:
        return False, "SELFIES library not available"
    
    try:
        # First validate SMILES
        mol = Chem.MolFromSmiles(smiles)
        if mol is None:
            return False, "Invalid SMILES"
        selfies_str = sf.encoder(smiles)
        return True, selfies_str
    except Exception as e:
        return False, f"SELFIES encode error: {str(e)}"


def get_tool_descriptions() -> str:
    """
    Get formatted tool descriptions for LLM prompt.
    
    Returns:
        String describing available tools and their usage
    """
    desc = """
Available Tools:

1. validate_smiles(smiles: str) -> dict
   Validates a SMILES string and returns detailed error information.
   Returns: {"valid": "True"/"False", "message": str, "error_type": str}
   
2. calculate_mass_error(smiles: str, target_mass: float, tolerance_ppm: float = 10.0) -> dict
   Calculates mass error between predicted and target mass.
   Returns: {"matches": "True"/"False", "predicted_mass": str, "target_mass": str, 
            "error_da": str, "error_ppm": str, "message": str}
"""
    
    if SELFIES_AVAILABLE:
        desc += """
3. selfies_to_smiles(selfies: str) -> tuple
   Converts SELFIES string to SMILES. SELFIES guarantees validity.
   Returns: (success: bool, smiles: str)

IMPORTANT: Use SELFIES format for generation! SELFIES guarantees valid molecular structures.
Any SELFIES string can be converted to valid SMILES. Example: [C][C][O] for ethanol.
"""
    else:
        desc += """
Note: SELFIES support not available. Install with: pip install selfies
"""
    
    desc += """
Usage Example:
  validation = validate_smiles("CCO")
  if validation["valid"] == "False":
      # Fix the error based on validation["message"]
  
  mass_check = calculate_mass_error("CCO", 46.0419, tolerance_ppm=10.0)
  if mass_check["matches"] == "False":
      # Adjust structure based on mass_check["message"]
"""
    return desc