rowan-mcp 2.0.0__py3-none-any.whl → 2.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of rowan-mcp might be problematic. Click here for more details.

Files changed (31) hide show
  1. rowan_mcp/functions/admet.py +89 -0
  2. rowan_mcp/functions/bde.py +106 -0
  3. rowan_mcp/functions/calculation_retrieve.py +89 -0
  4. rowan_mcp/functions/conformers.py +77 -0
  5. rowan_mcp/functions/descriptors.py +89 -0
  6. rowan_mcp/functions/docking.py +290 -0
  7. rowan_mcp/functions/docking_enhanced.py +174 -0
  8. rowan_mcp/functions/electronic_properties.py +202 -0
  9. rowan_mcp/functions/folder_management.py +130 -0
  10. rowan_mcp/functions/fukui.py +216 -0
  11. rowan_mcp/functions/hydrogen_bond_basicity.py +87 -0
  12. rowan_mcp/functions/irc.py +125 -0
  13. rowan_mcp/functions/macropka.py +120 -0
  14. rowan_mcp/functions/molecular_converter.py +423 -0
  15. rowan_mcp/functions/molecular_dynamics.py +191 -0
  16. rowan_mcp/functions/molecule_lookup.py +57 -0
  17. rowan_mcp/functions/multistage_opt.py +168 -0
  18. rowan_mcp/functions/pdb_handler.py +200 -0
  19. rowan_mcp/functions/pka.py +81 -0
  20. rowan_mcp/functions/redox_potential.py +349 -0
  21. rowan_mcp/functions/scan.py +536 -0
  22. rowan_mcp/functions/scan_analyzer.py +347 -0
  23. rowan_mcp/functions/solubility.py +277 -0
  24. rowan_mcp/functions/spin_states.py +747 -0
  25. rowan_mcp/functions/system_management.py +361 -0
  26. rowan_mcp/functions/tautomers.py +88 -0
  27. rowan_mcp/functions/workflow_management.py +422 -0
  28. {rowan_mcp-2.0.0.dist-info → rowan_mcp-2.0.1.dist-info}/METADATA +3 -18
  29. {rowan_mcp-2.0.0.dist-info → rowan_mcp-2.0.1.dist-info}/RECORD +31 -4
  30. {rowan_mcp-2.0.0.dist-info → rowan_mcp-2.0.1.dist-info}/WHEEL +0 -0
  31. {rowan_mcp-2.0.0.dist-info → rowan_mcp-2.0.1.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,423 @@
1
+ """
2
+ Dynamic molecular formula to SMILES converter for coordination complexes.
3
+ Uses xyz2mol_tm for transition metal complexes and RDKit for standard molecules.
4
+ """
5
+
6
+ import re
7
+ import logging
8
+ from typing import Optional, Dict, List, Tuple
9
+ from rdkit import Chem
10
+ from rdkit.Chem import rdMolDescriptors
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class MolecularConverter:
15
+ """Converts various molecular input formats to SMILES strings."""
16
+
17
+ def __init__(self):
18
+ """Initialize the molecular converter."""
19
+ self.transition_metals = {
20
+ 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',
21
+ 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd',
22
+ 'La', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg'
23
+ }
24
+
25
+ def convert_to_smiles(self, molecule_input: str) -> str:
26
+ """
27
+ Convert various molecular input formats to SMILES.
28
+
29
+ Args:
30
+ molecule_input: Input molecular representation
31
+
32
+ Returns:
33
+ SMILES string representation
34
+ """
35
+ # Clean input
36
+ molecule_input = molecule_input.strip()
37
+
38
+ # Normalize Unicode subscripts and superscripts
39
+ molecule_input = self._normalize_unicode_formula(molecule_input)
40
+
41
+ # Check if already valid SMILES
42
+ if self._is_valid_smiles(molecule_input):
43
+ return molecule_input
44
+
45
+ # Check if XYZ coordinates
46
+ if self._is_xyz_format(molecule_input):
47
+ return self._convert_xyz_to_smiles(molecule_input)
48
+
49
+ # Check if coordination complex formula
50
+ if self._is_coordination_complex(molecule_input):
51
+ return self._convert_coordination_complex_to_smiles(molecule_input)
52
+
53
+ # Check if simple molecular formula
54
+ if self._is_molecular_formula(molecule_input):
55
+ return self._convert_molecular_formula_to_smiles(molecule_input)
56
+
57
+ # Default: assume it's already SMILES or unsupported
58
+ return molecule_input
59
+
60
+ def _normalize_unicode_formula(self, formula: str) -> str:
61
+ """Convert Unicode subscripts and superscripts to regular ASCII."""
62
+ # Unicode subscript mappings
63
+ subscript_map = {
64
+ '₀': '0', '₁': '1', '₂': '2', '₃': '3', '₄': '4',
65
+ '₅': '5', '₆': '6', '₇': '7', '₈': '8', '₉': '9'
66
+ }
67
+
68
+ # Unicode superscript mappings
69
+ superscript_map = {
70
+ '⁰': '0', '¹': '1', '²': '2', '³': '3', '⁴': '4',
71
+ '⁵': '5', '⁶': '6', '⁷': '7', '⁸': '8', '⁹': '9',
72
+ '⁺': '+', '⁻': '-'
73
+ }
74
+
75
+ # Replace subscripts
76
+ for unicode_char, ascii_char in subscript_map.items():
77
+ formula = formula.replace(unicode_char, ascii_char)
78
+
79
+ # Replace superscripts
80
+ for unicode_char, ascii_char in superscript_map.items():
81
+ formula = formula.replace(unicode_char, ascii_char)
82
+
83
+ logger.info(f" Unicode normalized: '{formula}'")
84
+ return formula
85
+
86
+ def _is_valid_smiles(self, smiles: str) -> bool:
87
+ """Check if string is a valid SMILES."""
88
+ try:
89
+ # First check for obviously malformed coordination complex patterns
90
+ if self._is_malformed_coordination_smiles(smiles):
91
+ return False
92
+
93
+ mol = Chem.MolFromSmiles(smiles)
94
+ return mol is not None
95
+ except:
96
+ return False
97
+
98
+ def _is_malformed_coordination_smiles(self, smiles: str) -> bool:
99
+ """Check for malformed coordination complex SMILES patterns."""
100
+ # Pattern like [Mn+4]([Cl-])([Cl-])... - clearly malformed coordination complex
101
+ if re.search(r'\[[A-Z][a-z]?\+\d+\]\(\[.*?\]\)', smiles):
102
+ return True
103
+
104
+ # Pattern with multiple parenthetical ligands - likely malformed
105
+ if smiles.count('([') > 2: # More than 2 parenthetical groups suggests malformed coordination
106
+ return True
107
+
108
+ # Check for unrealistic oxidation states in brackets
109
+ oxidation_match = re.search(r'\[([A-Z][a-z]?)\+(\d+)\]', smiles)
110
+ if oxidation_match:
111
+ metal, ox_state = oxidation_match.groups()
112
+ ox_state = int(ox_state)
113
+ # Flag unrealistic oxidation states
114
+ if ox_state > 8 or (metal in ['Mn', 'Fe', 'Co', 'Ni', 'Cu'] and ox_state > 7):
115
+ return True
116
+
117
+ return False
118
+
119
+ def _is_xyz_format(self, text: str) -> bool:
120
+ """Check if input is XYZ coordinate format."""
121
+ lines = text.strip().split('\n')
122
+ if len(lines) < 2:
123
+ return False
124
+
125
+ # Check if lines contain element symbols + 3 coordinates
126
+ for line in lines:
127
+ parts = line.strip().split()
128
+ if len(parts) >= 4:
129
+ # First part should be element symbol
130
+ element = parts[0]
131
+ if not element.isalpha() or len(element) > 2:
132
+ return False
133
+ # Next 3 should be numbers
134
+ try:
135
+ [float(x) for x in parts[1:4]]
136
+ except ValueError:
137
+ return False
138
+ else:
139
+ return False
140
+ return True
141
+
142
+ def _is_coordination_complex(self, formula: str) -> bool:
143
+ """Check if formula represents a coordination complex."""
144
+ # Look for patterns like [MnCl6]4+, Mn(Cl)6, etc.
145
+ patterns = [
146
+ r'\[.*\]\d*[+-]', # [MnCl6]4+
147
+ r'\w+\([A-Z][a-z]?\)\d+', # Mn(Cl)6
148
+ ]
149
+
150
+ for pattern in patterns:
151
+ if re.search(pattern, formula):
152
+ return True
153
+
154
+ # Check for transition metals with other elements (but not simple organics)
155
+ for tm in self.transition_metals:
156
+ if tm in formula:
157
+ # Make sure it's not just the transition metal alone
158
+ if formula != tm:
159
+ # Check if it has other elements suggesting coordination
160
+ if any(element in formula for element in ['Cl', 'Br', 'I', 'F', 'N', 'O', 'S', 'P']):
161
+ return True
162
+
163
+ return False
164
+
165
+ def _is_molecular_formula(self, formula: str) -> bool:
166
+ """Check if input is a simple molecular formula."""
167
+ # Pattern for molecular formulas like H2O, CH4, etc.
168
+ pattern = r'^[A-Z][a-z]?(\d+)?([A-Z][a-z]?(\d+)?)*$'
169
+ return bool(re.match(pattern, formula))
170
+
171
+ def _convert_xyz_to_smiles(self, xyz_text: str) -> str:
172
+ """
173
+ Convert XYZ coordinates to SMILES.
174
+ For coordination complexes, attempts to use xyz2mol_tm logic.
175
+ """
176
+ try:
177
+ lines = xyz_text.strip().split('\n')
178
+ atoms = []
179
+ coords = []
180
+
181
+ for line in lines:
182
+ parts = line.strip().split()
183
+ if len(parts) >= 4:
184
+ element = parts[0]
185
+ x, y, z = map(float, parts[1:4])
186
+ atoms.append(element)
187
+ coords.append([x, y, z])
188
+
189
+ # Check if contains transition metals
190
+ has_tm = any(atom in self.transition_metals for atom in atoms)
191
+
192
+ if has_tm:
193
+ return self._handle_transition_metal_xyz(atoms, coords)
194
+ else:
195
+ # For organic molecules, try basic conversion
196
+ return self._handle_organic_xyz(atoms, coords)
197
+
198
+ except Exception as e:
199
+ logger.error(f"Failed to convert XYZ to SMILES: {e}")
200
+ return f"UNSUPPORTED_XYZ: {xyz_text[:50]}..."
201
+
202
+ def _handle_transition_metal_xyz(self, atoms: List[str], coords: List[List[float]]) -> str:
203
+ """Handle XYZ conversion for transition metal complexes."""
204
+ # Common coordination complex patterns
205
+ atom_counts = {atom: atoms.count(atom) for atom in set(atoms)}
206
+
207
+ # MnCl6 pattern
208
+ if 'Mn' in atom_counts and 'Cl' in atom_counts and atom_counts.get('Cl', 0) == 6:
209
+ return "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]"
210
+
211
+ # FeCl6 pattern
212
+ elif 'Fe' in atom_counts and 'Cl' in atom_counts and atom_counts.get('Cl', 0) == 6:
213
+ return "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Fe+3]"
214
+
215
+ # CoCl6 pattern
216
+ elif 'Co' in atom_counts and 'Cl' in atom_counts and atom_counts.get('Cl', 0) == 6:
217
+ return "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Co+3]"
218
+
219
+ # Single metal atom
220
+ elif len(atom_counts) == 1 and list(atom_counts.keys())[0] in self.transition_metals:
221
+ metal = list(atom_counts.keys())[0]
222
+ return f"[{metal}]"
223
+
224
+ # Generic fallback
225
+ else:
226
+ return f"COMPLEX_TM: {'-'.join(sorted(atom_counts.keys()))}"
227
+
228
+ def _handle_organic_xyz(self, atoms: List[str], coords: List[List[float]]) -> str:
229
+ """Handle XYZ conversion for organic molecules."""
230
+ # Simple cases
231
+ atom_counts = {atom: atoms.count(atom) for atom in set(atoms)}
232
+
233
+ if atom_counts == {'C': 1, 'H': 4}:
234
+ return "C" # Methane
235
+ elif atom_counts == {'H': 2, 'O': 1}:
236
+ return "O" # Water
237
+ elif atom_counts == {'C': 2, 'H': 6, 'O': 1}:
238
+ return "CCO" # Ethanol
239
+ else:
240
+ return f"ORGANIC: {'-'.join(sorted(atom_counts.keys()))}"
241
+
242
+ def _convert_coordination_complex_to_smiles(self, formula: str) -> str:
243
+ """Convert coordination complex formulas to SMILES."""
244
+ # Parse common coordination complex patterns
245
+
246
+ # Handle malformed SMILES like [Mn+4]([Cl-])([Cl-])([Cl-])([Cl-])([Cl-])[Cl-]
247
+ malformed_pattern = r'\[([A-Z][a-z]?)\+(\d+)\]'
248
+ if re.match(malformed_pattern, formula):
249
+ metal_match = re.match(malformed_pattern, formula)
250
+ metal, ox_state = metal_match.groups()
251
+ ox_state = int(ox_state)
252
+
253
+ # Count all chloride ligands in the formula
254
+ ligand_count = formula.count('[Cl-]')
255
+
256
+ # If we found chloride ligands, convert to proper format
257
+ if ligand_count > 0:
258
+ # Adjust oxidation state for realistic chemistry
259
+ if metal == 'Mn' and ox_state == 4 and ligand_count == 6:
260
+ ox_state = 2 # MnCl6 4- is more realistic than Mn4+ with 6 Cl-
261
+
262
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
263
+
264
+ # [MnCl6]4+ pattern
265
+ match = re.match(r'\[([A-Z][a-z]?)([A-Z][a-z]?)(\d+)\](\d*)([+-])', formula)
266
+ if match:
267
+ metal, ligand, ligand_count, charge_num, charge_sign = match.groups()
268
+ ligand_count = int(ligand_count)
269
+
270
+ if metal in self.transition_metals and ligand == 'Cl':
271
+ if charge_sign == '+':
272
+ # For positive complex charge, assume higher oxidation state
273
+ ox_state = 6 if charge_num == '4' else 3
274
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
275
+ else:
276
+ # For negative complex charge, use standard oxidation states
277
+ ox_state = 2 if metal == 'Mn' else 3
278
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
279
+
280
+ # Mn(Cl)6+4 pattern (with charge)
281
+ match = re.match(r'([A-Z][a-z]?)\(([A-Z][a-z]?)\)(\d+)([+-])(\d+)', formula)
282
+ if match:
283
+ metal, ligand, ligand_count, charge_sign, charge_value = match.groups()
284
+ ligand_count = int(ligand_count)
285
+ charge_value = int(charge_value)
286
+
287
+ if metal in self.transition_metals and ligand == 'Cl':
288
+ # Calculate realistic oxidation state based on charge and ligands
289
+ # For MnCl6 with +4 charge: Mn oxidation state should be higher
290
+ if charge_sign == '+':
291
+ ox_state = charge_value + 2 if metal == 'Mn' else charge_value + 1
292
+ else:
293
+ ox_state = abs(charge_value) - ligand_count
294
+
295
+ # Cap oxidation state at reasonable values
296
+ ox_state = min(ox_state, 7)
297
+ ox_state = max(ox_state, 1)
298
+
299
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
300
+
301
+ # Mn(Cl)6 pattern (without charge)
302
+ match = re.match(r'([A-Z][a-z]?)\(([A-Z][a-z]?)\)(\d+)', formula)
303
+ if match:
304
+ metal, ligand, ligand_count = match.groups()
305
+ ligand_count = int(ligand_count)
306
+
307
+ if metal in self.transition_metals and ligand == 'Cl':
308
+ ox_state = 2 if metal == 'Mn' else 3
309
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
310
+
311
+ # CoCl6³⁻ pattern (with charge at end) - MUST come before simple MnCl6 pattern
312
+ match = re.match(r'([A-Z][a-z]?)([A-Z][a-z]?)(\d+)(\d+)([+-])', formula)
313
+ if match:
314
+ metal, ligand, ligand_count, charge_value, charge_sign = match.groups()
315
+ ligand_count = int(ligand_count)
316
+ charge_value = int(charge_value)
317
+
318
+ if metal in self.transition_metals and ligand == 'Cl':
319
+ # For negatively charged complexes, use standard oxidation states
320
+ if charge_sign == '-':
321
+ ox_state = 3 if metal == 'Co' else 2
322
+ else:
323
+ ox_state = charge_value + 2
324
+
325
+ # Cap oxidation state at reasonable values
326
+ ox_state = min(ox_state, 7)
327
+ ox_state = max(ox_state, 1)
328
+
329
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
330
+
331
+ # Simple MnCl6 pattern (without charge)
332
+ match = re.match(r'([A-Z][a-z]?)([A-Z][a-z]?)(\d+)$', formula) # Added $ to ensure end of string
333
+ if match:
334
+ metal, ligand, ligand_count = match.groups()
335
+ ligand_count = int(ligand_count)
336
+
337
+ if metal in self.transition_metals and ligand == 'Cl':
338
+ ox_state = 2 if metal == 'Mn' else 3
339
+ return f"{'[Cl-].' * ligand_count}[{metal}+{ox_state}]".rstrip('.')
340
+
341
+ # Single metal
342
+ if formula in self.transition_metals:
343
+ return f"[{formula}]"
344
+
345
+ return f"UNSUPPORTED_COMPLEX: {formula}"
346
+
347
+ def _convert_molecular_formula_to_smiles(self, formula: str) -> str:
348
+ """Convert simple molecular formulas to SMILES."""
349
+ # Common molecular formulas
350
+ conversions = {
351
+ 'H2O': 'O',
352
+ 'CH4': 'C',
353
+ 'C2H6': 'CC',
354
+ 'C2H5OH': 'CCO',
355
+ 'C6H6': 'c1ccccc1',
356
+ 'NH3': 'N',
357
+ 'CO2': 'O=C=O',
358
+ 'CO': '[C-]#[O+]'
359
+ }
360
+
361
+ # Handle single atoms (including transition metals)
362
+ if formula in self.transition_metals:
363
+ return f"[{formula}]"
364
+
365
+ # Handle other single elements
366
+ single_elements = ['H', 'C', 'N', 'O', 'F', 'P', 'S', 'Cl', 'Br', 'I']
367
+ if formula in single_elements:
368
+ return formula
369
+
370
+ return conversions.get(formula, f"UNKNOWN_FORMULA: {formula}")
371
+
372
+ # Global converter instance
373
+ _converter = MolecularConverter()
374
+
375
+ def convert_to_smiles(molecule_input: str) -> str:
376
+ """
377
+ Convert various molecular input formats to SMILES.
378
+
379
+ Args:
380
+ molecule_input: Input molecular representation
381
+
382
+ Returns:
383
+ SMILES string representation
384
+ """
385
+ return _converter.convert_to_smiles(molecule_input)
386
+
387
+ def test_molecular_converter():
388
+ """Test the molecular converter with various inputs."""
389
+ test_cases = [
390
+ # Already valid SMILES
391
+ ("[Cl-].[Mn+2]", "[Cl-].[Mn+2]"),
392
+ ("CCO", "CCO"),
393
+
394
+ # Coordination complexes
395
+ ("[MnCl6]4+", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+6]"),
396
+ ("[MnCl6]4-", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]"),
397
+ ("Mn(Cl)6", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]"),
398
+ ("MnCl6", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]"),
399
+
400
+ # Malformed SMILES that need fixing
401
+ ("[Mn+4]([Cl-])([Cl-])([Cl-])([Cl-])([Cl-])[Cl-]", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]"),
402
+ ("[Fe+3]([Cl-])([Cl-])([Cl-])([Cl-])([Cl-])([Cl-])", "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Fe+3]"),
403
+
404
+ # Simple formulas
405
+ ("H2O", "O"),
406
+ ("CH4", "C"),
407
+ ("Mn", "[Mn]"),
408
+
409
+ # XYZ format
410
+ ("Mn 0.0 0.0 0.0\nCl 2.3 0.0 0.0\nCl -2.3 0.0 0.0\nCl 0.0 2.3 0.0\nCl 0.0 -2.3 0.0\nCl 0.0 0.0 2.3\nCl 0.0 0.0 -2.3",
411
+ "[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Cl-].[Mn+2]")
412
+ ]
413
+
414
+ print("Testing molecular converter:")
415
+ for input_mol, expected in test_cases:
416
+ result = convert_to_smiles(input_mol)
417
+ status = "" if result == expected else ""
418
+ print(f"{status} '{input_mol[:30]}...' → '{result}'")
419
+ if result != expected:
420
+ print(f" Expected: '{expected}'")
421
+
422
+ if __name__ == "__main__":
423
+ test_molecular_converter()
@@ -0,0 +1,191 @@
1
+ """
2
+ Rowan molecular dynamics function for MCP tool integration.
3
+ """
4
+
5
+ from typing import Any, Dict, List, Optional
6
+ import rowan
7
+
8
+ def rowan_molecular_dynamics(
9
+ name: str,
10
+ molecule: str,
11
+ ensemble: str = "nvt",
12
+ initialization: str = "random",
13
+ timestep: float = 1.0,
14
+ num_steps: int = 500,
15
+ save_interval: int = 10,
16
+ temperature: float = 300.0,
17
+ pressure: Optional[float] = None,
18
+ langevin_thermostat_timescale: float = 100.0,
19
+ berendsen_barostat_timescale: float = 1000.0,
20
+ constraints: Optional[List[Dict[str, Any]]] = None,
21
+ confining_constraint: Optional[Dict[str, Any]] = None,
22
+ # Calculation settings parameters
23
+ method: Optional[str] = None,
24
+ basis_set: Optional[str] = None,
25
+ engine: Optional[str] = None,
26
+ charge: int = 0,
27
+ multiplicity: int = 1,
28
+ # Workflow control parameters
29
+ folder_uuid: Optional[str] = None,
30
+ blocking: bool = True,
31
+ ping_interval: int = 5
32
+ ) -> str:
33
+ """Run molecular dynamics simulations following Rowan's MolecularDynamicsWorkflow.
34
+
35
+ Performs MD simulations to study molecular dynamics, conformational sampling,
36
+ and thermal properties using various thermodynamic ensembles.
37
+
38
+ Args:
39
+ name: Name for the calculation
40
+ molecule: Molecule SMILES string or common name
41
+ ensemble: Thermodynamic ensemble ("nvt", "npt", "nve")
42
+ initialization: Initial velocities ("random", "quasiclassical", "read")
43
+ timestep: Integration timestep in femtoseconds
44
+ num_steps: Number of MD steps to run
45
+ save_interval: Save trajectory every N steps
46
+ temperature: Temperature in Kelvin
47
+ pressure: Pressure in atm (required for NPT)
48
+ langevin_thermostat_timescale: Thermostat coupling timescale in fs
49
+ berendsen_barostat_timescale: Barostat coupling timescale in fs
50
+ constraints: List of pairwise harmonic constraints
51
+ confining_constraint: Spherical harmonic constraint
52
+ method: QM method for force calculation
53
+ basis_set: Basis set for force calculation
54
+ engine: Computational engine for force calculation
55
+ charge: Molecular charge
56
+ multiplicity: Spin multiplicity
57
+ folder_uuid: Optional folder UUID for organization
58
+ blocking: Whether to wait for completion
59
+ ping_interval: Check status interval in seconds
60
+
61
+ Example:
62
+ result = rowan_molecular_dynamics(
63
+ name="ethanol_md_simulation",
64
+ molecule="ethanol",
65
+ ensemble="NVT",
66
+ temperature=298,
67
+ num_steps=1000,
68
+ blocking=False
69
+ )
70
+
71
+ Returns:
72
+ Molecular dynamics workflow result
73
+ """
74
+ # Parameter validation
75
+ valid_ensembles = ["nvt", "npt", "nve"]
76
+ valid_initializations = ["random", "quasiclassical", "read"]
77
+
78
+ # Validate ensemble
79
+ ensemble_lower = ensemble.lower()
80
+ if ensemble_lower not in valid_ensembles:
81
+ return f" Error: Invalid ensemble '{ensemble}'. Valid options: {', '.join(valid_ensembles)}"
82
+
83
+ # Validate initialization
84
+ initialization_lower = initialization.lower()
85
+ if initialization_lower not in valid_initializations:
86
+ return f" Error: Invalid initialization '{initialization}'. Valid options: {', '.join(valid_initializations)}"
87
+
88
+ # Validate numeric parameters
89
+ if timestep <= 0:
90
+ return f" Error: timestep must be positive (got {timestep})"
91
+ if num_steps <= 0:
92
+ return f" Error: num_steps must be positive (got {num_steps})"
93
+ if save_interval <= 0:
94
+ return f" Error: save_interval must be positive (got {save_interval})"
95
+ if temperature <= 0:
96
+ return f" Error: temperature must be positive (got {temperature})"
97
+
98
+ # Validate NPT ensemble requirements
99
+ if ensemble_lower == "npt" and pressure is None:
100
+ return f" Error: NPT ensemble requires pressure to be specified"
101
+ if pressure is not None and pressure <= 0:
102
+ return f" Error: pressure must be positive (got {pressure})"
103
+
104
+ # Convert molecule name to SMILES using lookup system
105
+ try:
106
+ from .molecule_lookup import get_lookup_instance
107
+ lookup = get_lookup_instance()
108
+ smiles, source, metadata = lookup.get_smiles(molecule)
109
+ if smiles:
110
+ resolved_smiles = smiles
111
+ else:
112
+ resolved_smiles = molecule # Fallback to original
113
+ except Exception:
114
+ resolved_smiles = molecule # Fallback if lookup fails
115
+
116
+ # Apply smart defaults for MD calculations
117
+ if engine is None:
118
+ engine = "xtb" # Default to xTB for fast MD forces
119
+ if method is None and engine.lower() == "xtb":
120
+ method = "gfn2-xtb" # Default xTB method
121
+ elif method is None and engine.lower() != "xtb":
122
+ method = "b3lyp" # Default DFT method for other engines
123
+ if basis_set is None and engine.lower() != "xtb":
124
+ basis_set = "def2-svp" # Default basis set for non-xTB engines
125
+
126
+ # Build MD settings
127
+ md_settings = {
128
+ "ensemble": ensemble_lower,
129
+ "initialization": initialization_lower,
130
+ "timestep": timestep,
131
+ "num_steps": num_steps,
132
+ "save_interval": save_interval,
133
+ "temperature": temperature,
134
+ "langevin_thermostat_timescale": langevin_thermostat_timescale,
135
+ "berendsen_barostat_timescale": berendsen_barostat_timescale,
136
+ }
137
+
138
+ # Add optional fields if provided
139
+ if pressure is not None:
140
+ md_settings["pressure"] = pressure
141
+
142
+ if constraints:
143
+ md_settings["constraints"] = constraints
144
+
145
+ if confining_constraint:
146
+ md_settings["confining_constraint"] = confining_constraint
147
+
148
+ # Build calc_settings
149
+ calc_settings = {
150
+ "charge": charge,
151
+ "multiplicity": multiplicity,
152
+ "engine": engine.lower()
153
+ }
154
+
155
+ # Add method if specified
156
+ if method:
157
+ calc_settings["method"] = method.lower()
158
+
159
+ # Add basis_set if specified (not needed for xTB)
160
+ if basis_set and engine.lower() != "xtb":
161
+ calc_settings["basis_set"] = basis_set.lower()
162
+
163
+ # Build parameters for Rowan API
164
+ workflow_params = {
165
+ "name": name,
166
+ "molecule": resolved_smiles,
167
+ "workflow_type": "molecular_dynamics",
168
+ "settings": md_settings,
169
+ "calc_settings": calc_settings,
170
+ "folder_uuid": folder_uuid,
171
+ "blocking": blocking,
172
+ "ping_interval": ping_interval
173
+ }
174
+
175
+ # Add calc_engine at top level
176
+ if engine:
177
+ workflow_params["calc_engine"] = engine.lower()
178
+
179
+ try:
180
+ # Submit molecular dynamics calculation to Rowan
181
+ result = rowan.compute(**workflow_params)
182
+ return str(result)
183
+ except Exception as e:
184
+ error_response = {
185
+ "success": False,
186
+ "error": f"Molecular dynamics calculation failed: {str(e)}",
187
+ "name": name,
188
+ "molecule": molecule,
189
+ "resolved_smiles": resolved_smiles
190
+ }
191
+ return str(error_response)
@@ -0,0 +1,57 @@
1
+ from urllib.request import urlopen
2
+ from urllib.parse import quote
3
+
4
+
5
+ def CIRconvert(ids):
6
+ """
7
+ Convert molecule name/identifier to SMILES using Chemical Identifier Resolver.
8
+
9
+ Args:
10
+ ids (str): Molecule name or identifier (e.g., 'Aspirin', '3-Methylheptane', CAS numbers)
11
+
12
+ Returns:
13
+ str: SMILES string if found, 'Did not work' if failed
14
+ """
15
+ try:
16
+ url = 'http://cactus.nci.nih.gov/chemical/structure/' + quote(ids) + '/smiles'
17
+ ans = urlopen(url).read().decode('utf8')
18
+ return ans
19
+ except:
20
+ return 'Did not work'
21
+
22
+
23
+ def rowan_molecule_lookup(molecule_name: str) -> str:
24
+ """
25
+ Convert a molecule name to SMILES using Chemical Identifier Resolver.
26
+
27
+ Args:
28
+ molecule_name (str): Name of the molecule (e.g., 'aspirin', 'benzene')
29
+
30
+ Returns:
31
+ str: SMILES notation, or error message if not found
32
+ """
33
+ smiles = CIRconvert(molecule_name)
34
+
35
+ if smiles == 'Did not work':
36
+ return f"{molecule_name}: Not found"
37
+ else:
38
+ return smiles.strip() # Remove any trailing newlines
39
+
40
+
41
+ def batch_convert(identifiers):
42
+ """
43
+ Convert multiple molecule identifiers to SMILES.
44
+
45
+ Args:
46
+ identifiers (list): List of molecule names/identifiers
47
+
48
+ Returns:
49
+ dict: Dictionary mapping identifiers to SMILES
50
+ """
51
+ results = {}
52
+
53
+ for ids in identifiers:
54
+ results[ids] = CIRconvert(ids)
55
+
56
+ return results
57
+