AhmedElTaher commited on
Commit
7b998cb
Β·
verified Β·
1 Parent(s): 3a2bb24

Upload 43 files

Browse files
app.py CHANGED
@@ -157,22 +157,22 @@ class AbMeltPipeline:
157
 
158
  # Step 1: Generate structure (10% progress)
159
  if progress_callback:
160
- progress_callback(10, "Generating antibody structure with ImmuneBuilder...")
161
 
162
  structure_path = self.structure_gen.generate_structure(
163
  heavy_chain, light_chain
164
  )
165
 
 
 
 
166
  # Copy structure file to persistent location before cleanup
167
- if structure_path and os.path.exists(structure_path):
168
- persistent_dir = os.path.join(os.getcwd(), "outputs")
169
- os.makedirs(persistent_dir, exist_ok=True)
170
- persistent_structure = os.path.join(persistent_dir, f"structure_{job_id}.pdb")
171
- shutil.copy2(structure_path, persistent_structure)
172
- results['intermediate_files']['structure'] = persistent_structure
173
- logger.info(f"Structure copied to persistent location: {persistent_structure}")
174
- else:
175
- results['intermediate_files']['structure'] = structure_path
176
 
177
  results['logs'].append("βœ“ Structure generation completed")
178
 
@@ -262,6 +262,10 @@ class AbMeltPipeline:
262
  results['error'] = error_msg
263
  results['logs'].append(f"βœ— {error_msg}")
264
  logger.error(error_msg)
 
 
 
 
265
 
266
  finally:
267
  # Cleanup MD pipeline
@@ -270,7 +274,7 @@ class AbMeltPipeline:
270
  except:
271
  pass
272
 
273
- except Exception as e:
274
  error_msg = f"Pipeline error: {str(e)}"
275
  results['error'] = error_msg
276
  results['logs'].append(f"βœ— {error_msg}")
 
157
 
158
  # Step 1: Generate structure (10% progress)
159
  if progress_callback:
160
+ progress_callback(10, "Generating antibody structure...")
161
 
162
  structure_path = self.structure_gen.generate_structure(
163
  heavy_chain, light_chain
164
  )
165
 
166
+ if not structure_path or not os.path.exists(structure_path):
167
+ raise FileNotFoundError("Structure generation failed. PDB file not created.")
168
+
169
  # Copy structure file to persistent location before cleanup
170
+ persistent_dir = os.path.join(os.getcwd(), "outputs")
171
+ os.makedirs(persistent_dir, exist_ok=True)
172
+ persistent_structure = os.path.join(persistent_dir, f"structure_{job_id}.pdb")
173
+ shutil.copy2(structure_path, persistent_structure)
174
+ results['intermediate_files']['structure'] = persistent_structure
175
+ logger.info(f"Structure copied to persistent location: {persistent_structure}")
 
 
 
176
 
177
  results['logs'].append("βœ“ Structure generation completed")
178
 
 
262
  results['error'] = error_msg
263
  results['logs'].append(f"βœ— {error_msg}")
264
  logger.error(error_msg)
265
+ # Add specific check for NaN coordinate error
266
+ if "NaN" in str(e) or "invalid coordinates" in str(e):
267
+ results['logs'].append(" Hint: This error is often caused by problems in the fallback "
268
+ "structure generator. Check sequence validity.")
269
 
270
  finally:
271
  # Cleanup MD pipeline
 
274
  except:
275
  pass
276
 
277
+ except (Exception, GromacsError) as e:
278
  error_msg = f"Pipeline error: {str(e)}"
279
  results['error'] = error_msg
280
  results['logs'].append(f"βœ— {error_msg}")
requirements.txt CHANGED
@@ -30,7 +30,6 @@ optuna
30
 
31
  # System utilities (auto-update - rarely break compatibility)
32
  psutil
33
-
34
  tqdm
35
 
36
  # File handling (auto-update - stable API)
 
30
 
31
  # System utilities (auto-update - rarely break compatibility)
32
  psutil
 
33
  tqdm
34
 
35
  # File handling (auto-update - stable API)
src/__pycache__/gromacs_pipeline.cpython-313.pyc CHANGED
Binary files a/src/__pycache__/gromacs_pipeline.cpython-313.pyc and b/src/__pycache__/gromacs_pipeline.cpython-313.pyc differ
 
src/__pycache__/structure_generator.cpython-313.pyc CHANGED
Binary files a/src/__pycache__/structure_generator.cpython-313.pyc and b/src/__pycache__/structure_generator.cpython-313.pyc differ
 
src/gromacs_pipeline.py CHANGED
@@ -143,7 +143,7 @@ class GromacsPipeline:
143
  def _pdb2gmx(self, pdb_file, force_field, water):
144
  """Convert PDB to GROMACS topology"""
145
  try:
146
- # First, let's check the PDB file content for debugging
147
  logger.info(f"Processing PDB file: {pdb_file}")
148
  if os.path.exists(pdb_file):
149
  file_size = os.path.getsize(pdb_file)
@@ -153,6 +153,9 @@ class GromacsPipeline:
153
  if not os.access(pdb_file, os.R_OK):
154
  raise PermissionError(f"Cannot read PDB file: {pdb_file}")
155
 
 
 
 
156
  # Check for histidine residues that might cause issues
157
  with open(pdb_file, 'r') as f:
158
  content = f.read()
@@ -268,6 +271,9 @@ class GromacsPipeline:
268
  raise ValueError(f"Invalid atom count in line 2: {lines[1].strip()}")
269
 
270
  # Check coordinate lines
 
 
 
271
  for i, line in enumerate(lines[2:2+num_atoms], 3):
272
  if len(line.strip()) == 0:
273
  continue
@@ -280,26 +286,134 @@ class GromacsPipeline:
280
  raise ValueError(f"Line {i}: insufficient columns: {line.strip()}")
281
 
282
  # Check coordinates (columns 4, 5, 6 in 0-indexed)
283
- x, y, z = float(parts[3]), float(parts[4]), float(parts[5])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
  # Check if coordinates contain decimal points in string representation
286
- if '.' not in parts[3] or '.' not in parts[4] or '.' not in parts[5]:
287
- logger.warning(f"Line {i}: coordinates may lack decimal points: {parts[3]} {parts[4]} {parts[5]}")
288
 
289
  except (ValueError, IndexError) as e:
290
- raise ValueError(f"Line {i}: invalid coordinate format: {line.strip()} - {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
  logger.info(f"GRO file {gro_file} validation passed")
293
 
294
  except Exception as e:
295
  logger.error(f"GRO file validation failed for {gro_file}: {e}")
296
  # Show first few lines for debugging
297
- with open(file_path, 'r') as f:
298
- first_lines = f.readlines()[:10]
299
- logger.error(f"First 10 lines of {gro_file}:")
300
- for i, line in enumerate(first_lines, 1):
301
- logger.error(f" {i:2d}: {line.rstrip()}")
 
 
 
302
  raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
  def _solvate_system(self):
305
  """Add water molecules"""
 
143
  def _pdb2gmx(self, pdb_file, force_field, water):
144
  """Convert PDB to GROMACS topology"""
145
  try:
146
+ # First, let's validate the PDB file for NaN coordinates
147
  logger.info(f"Processing PDB file: {pdb_file}")
148
  if os.path.exists(pdb_file):
149
  file_size = os.path.getsize(pdb_file)
 
153
  if not os.access(pdb_file, os.R_OK):
154
  raise PermissionError(f"Cannot read PDB file: {pdb_file}")
155
 
156
+ # Validate PDB coordinates before processing
157
+ self._validate_pdb_coordinates(pdb_file)
158
+
159
  # Check for histidine residues that might cause issues
160
  with open(pdb_file, 'r') as f:
161
  content = f.read()
 
271
  raise ValueError(f"Invalid atom count in line 2: {lines[1].strip()}")
272
 
273
  # Check coordinate lines
274
+ nan_detected = False
275
+ invalid_coords = []
276
+
277
  for i, line in enumerate(lines[2:2+num_atoms], 3):
278
  if len(line.strip()) == 0:
279
  continue
 
286
  raise ValueError(f"Line {i}: insufficient columns: {line.strip()}")
287
 
288
  # Check coordinates (columns 4, 5, 6 in 0-indexed)
289
+ x_str, y_str, z_str = parts[3], parts[4], parts[5]
290
+
291
+ # Check for NaN values in string form first
292
+ if any('nan' in coord.lower() for coord in [x_str, y_str, z_str]):
293
+ nan_detected = True
294
+ invalid_coords.append(f"Line {i}: NaN coordinates detected: {x_str} {y_str} {z_str}")
295
+ continue
296
+
297
+ # Convert to float and check for NaN/inf values
298
+ x, y, z = float(x_str), float(y_str), float(z_str)
299
+
300
+ # Use math module to check for NaN and inf
301
+ import math
302
+ if math.isnan(x) or math.isnan(y) or math.isnan(z):
303
+ nan_detected = True
304
+ invalid_coords.append(f"Line {i}: NaN coordinates after float conversion: {x} {y} {z}")
305
+ continue
306
+
307
+ if math.isinf(x) or math.isinf(y) or math.isinf(z):
308
+ invalid_coords.append(f"Line {i}: Infinite coordinates detected: {x} {y} {z}")
309
+ continue
310
 
311
  # Check if coordinates contain decimal points in string representation
312
+ if '.' not in x_str or '.' not in y_str or '.' not in z_str:
313
+ logger.warning(f"Line {i}: coordinates may lack decimal points: {x_str} {y_str} {z_str}")
314
 
315
  except (ValueError, IndexError) as e:
316
+ invalid_coords.append(f"Line {i}: invalid coordinate format: {line.strip()} - {e}")
317
+
318
+ # Report any coordinate issues
319
+ if nan_detected or invalid_coords:
320
+ error_msg = f"Coordinate validation failed for {gro_file}:\n"
321
+ for error in invalid_coords[:10]: # Show first 10 errors
322
+ error_msg += f" {error}\n"
323
+ if len(invalid_coords) > 10:
324
+ error_msg += f" ... and {len(invalid_coords) - 10} more errors\n"
325
+
326
+ logger.error(error_msg)
327
+
328
+ # Show file content for debugging
329
+ with open(file_path, 'r') as f:
330
+ content_lines = f.readlines()[:20]
331
+ logger.error(f"First 20 lines of {gro_file}:")
332
+ for i, line in enumerate(content_lines, 1):
333
+ logger.error(f" {i:2d}: {line.rstrip()}")
334
+
335
+ if nan_detected:
336
+ raise GromacsError(f"NaN coordinates detected in {gro_file}. This indicates a problem with structure generation. "
337
+ f"The fallback structure generator may have produced invalid coordinates.")
338
+ else:
339
+ raise ValueError(f"Invalid coordinate format in {gro_file}")
340
 
341
  logger.info(f"GRO file {gro_file} validation passed")
342
 
343
  except Exception as e:
344
  logger.error(f"GRO file validation failed for {gro_file}: {e}")
345
  # Show first few lines for debugging
346
+ try:
347
+ with open(file_path, 'r') as f:
348
+ first_lines = f.readlines()[:10]
349
+ logger.error(f"First 10 lines of {gro_file}:")
350
+ for i, line in enumerate(first_lines, 1):
351
+ logger.error(f" {i:2d}: {line.rstrip()}")
352
+ except Exception as debug_e:
353
+ logger.error(f"Could not read file for debugging: {debug_e}")
354
  raise
355
+
356
+ def _validate_pdb_coordinates(self, pdb_file):
357
+ """Validate PDB file coordinates before processing with GROMACS"""
358
+ logger.info(f"Validating PDB coordinates: {pdb_file}")
359
+
360
+ try:
361
+ with open(pdb_file, 'r') as f:
362
+ lines = f.readlines()
363
+
364
+ invalid_coords = []
365
+ atom_count = 0
366
+
367
+ for i, line in enumerate(lines, 1):
368
+ if line.startswith('ATOM') or line.startswith('HETATM'):
369
+ atom_count += 1
370
+ try:
371
+ # PDB format: columns 31-38 (x), 39-46 (y), 47-54 (z)
372
+ x_str = line[30:38].strip()
373
+ y_str = line[38:46].strip()
374
+ z_str = line[46:54].strip()
375
+
376
+ # Check for NaN values in string form
377
+ if any('nan' in coord.lower() for coord in [x_str, y_str, z_str]):
378
+ invalid_coords.append(f"Line {i}: NaN coordinates detected in PDB: {x_str} {y_str} {z_str}")
379
+ continue
380
+
381
+ # Try to convert to float and check for NaN/inf
382
+ x, y, z = float(x_str), float(y_str), float(z_str)
383
+
384
+ import math
385
+ if math.isnan(x) or math.isnan(y) or math.isnan(z):
386
+ invalid_coords.append(f"Line {i}: NaN coordinates after conversion: {x} {y} {z}")
387
+ continue
388
+
389
+ if math.isinf(x) or math.isinf(y) or math.isinf(z):
390
+ invalid_coords.append(f"Line {i}: Infinite coordinates: {x} {y} {z}")
391
+ continue
392
+
393
+ except (ValueError, IndexError) as e:
394
+ invalid_coords.append(f"Line {i}: Could not parse coordinates: {e}")
395
+
396
+ logger.info(f"Validated {atom_count} atoms in PDB file")
397
+
398
+ if invalid_coords:
399
+ error_msg = f"Invalid coordinates found in PDB file {pdb_file}:\n"
400
+ for error in invalid_coords[:10]: # Show first 10 errors
401
+ error_msg += f" {error}\n"
402
+ if len(invalid_coords) > 10:
403
+ error_msg += f" ... and {len(invalid_coords) - 10} more errors\n"
404
+
405
+ logger.error(error_msg)
406
+ raise GromacsError(f"Invalid coordinates in PDB file {pdb_file}. "
407
+ f"The structure generator produced NaN or invalid coordinates. "
408
+ f"This will cause GROMACS to fail with 'coordinate does not contain a \".\"' error.")
409
+
410
+ logger.info(f"PDB coordinate validation passed for {pdb_file}")
411
+
412
+ except Exception as e:
413
+ if isinstance(e, GromacsError):
414
+ raise # Re-raise our custom error
415
+ logger.error(f"PDB coordinate validation failed: {e}")
416
+ raise GromacsError(f"Could not validate PDB coordinates: {e}")
417
 
418
  def _solvate_system(self):
419
  """Add water molecules"""
src/structure_generator.py CHANGED
@@ -35,26 +35,34 @@ class StructureGenerator:
35
  logger.info(f"Using system temp directory: {self.temp_dir}")
36
  return self.temp_dir
37
 
38
- def generate_structure(self, heavy_chain, light_chain, output_path=None):
39
  """
40
- Generate antibody structure from sequences using ImmuneBuilder
41
 
42
  Args:
43
- heavy_chain (str): Heavy chain variable region sequence
44
- light_chain (str): Light chain variable region sequence
45
- output_path (str): Output PDB file path
46
-
47
  Returns:
48
- str: Path to generated PDB file
49
  """
50
- try:
51
- from ImmuneBuilder import ABodyBuilder2
52
- logger.info("ImmuneBuilder available - using for structure generation")
53
- return self._generate_with_immunebuilder(heavy_chain, light_chain, output_path)
54
- except ImportError as e:
55
- logger.warning(f"ImmuneBuilder not available ({e})")
56
- logger.info("Using fallback structure generation method")
57
- return self._generate_fallback_structure(heavy_chain, light_chain, output_path)
 
 
 
 
 
 
 
 
58
 
59
  def _generate_with_immunebuilder(self, heavy_chain, light_chain, output_path):
60
  """Generate structure using ImmuneBuilder (when available)"""
@@ -147,9 +155,15 @@ class StructureGenerator:
147
 
148
  # Add heavy chain atoms with complete side chains
149
  for i, aa in enumerate(heavy_chain, 1):
150
- x = float(i * 3.8) # Simple linear chain
151
- y = 0.0
152
- z = 0.0
 
 
 
 
 
 
153
 
154
  three_letter = self._aa_three_letter(aa)
155
 
@@ -160,9 +174,15 @@ class StructureGenerator:
160
 
161
  # Add light chain atoms with complete side chains
162
  for i, aa in enumerate(light_chain, 1):
163
- x = float(i * 3.8)
164
- y = 15.0 # Offset from heavy chain
165
- z = 0.0
 
 
 
 
 
 
166
 
167
  three_letter = self._aa_three_letter(aa)
168
 
@@ -178,20 +198,31 @@ class StructureGenerator:
178
  def _add_complete_residue(self, pdb_lines, atom_counter, three_letter, res_id, x, y, z):
179
  """Add a complete amino acid residue with all required atoms"""
180
 
181
- # Backbone atoms (required for all residues)
 
 
 
 
 
182
  backbone_atoms = [
183
- ("N", x-1.0, y, z, "N"),
184
- ("CA", x, y, z, "C"),
185
- ("C", x+1.0, y, z, "C"),
186
- ("O", x+1.0, y+1.0, z, "O")
187
  ]
188
 
189
  # Add side chain atoms based on residue type
190
  side_chain_atoms = self._get_side_chain_atoms(three_letter, x, y, z)
191
 
192
- # Combine all atoms
193
  all_atoms = backbone_atoms + side_chain_atoms
194
 
 
 
 
 
 
 
195
  # Write atoms to PDB
196
  for atom_name, ax, ay, az, element in all_atoms:
197
  pdb_line = f"ATOM {atom_counter:5d} {atom_name:<3} {three_letter} {res_id} {ax:8.3f}{ay:8.3f}{az:8.3f} 1.00 20.00 {element}"
@@ -203,127 +234,148 @@ class StructureGenerator:
203
  def _get_side_chain_atoms(self, three_letter, x, y, z):
204
  """Get side chain atoms for a specific amino acid"""
205
 
206
- # Define side chain atoms for each amino acid type
 
 
 
 
 
207
  side_chains = {
208
- 'ALA': [("CB", x+0.5, y-0.5, z+0.5, "C")],
209
  'ARG': [
210
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
211
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
212
- ("CD", x+1.5, y-1.5, z+1.5, "C"),
213
- ("NE", x+2.0, y-2.0, z+2.0, "N"),
214
- ("CZ", x+2.5, y-2.5, z+2.5, "C"),
215
- ("NH1", x+3.0, y-3.0, z+3.0, "N"),
216
- ("NH2", x+3.0, y-3.0, z+2.0, "N")
217
  ],
218
  'ASN': [
219
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
220
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
221
- ("OD1", x+1.5, y-1.5, z+1.5, "O"),
222
- ("ND2", x+1.5, y-1.0, z+0.5, "N")
223
  ],
224
  'ASP': [
225
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
226
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
227
- ("OD1", x+1.5, y-1.5, z+1.5, "O"),
228
- ("OD2", x+1.5, y-1.0, z+0.5, "O")
229
  ],
230
- 'CYS': [("CB", x+0.5, y-0.5, z+0.5, "C"), ("SG", x+1.0, y-1.0, z+1.0, "S")],
231
  'GLN': [
232
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
233
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
234
- ("CD", x+1.5, y-1.5, z+1.5, "C"),
235
- ("OE1", x+2.0, y-2.0, z+2.0, "O"),
236
- ("NE2", x+2.0, y-1.5, z+1.0, "N")
237
  ],
238
  'GLU': [
239
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
240
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
241
- ("CD", x+1.5, y-1.5, z+1.5, "C"),
242
- ("OE1", x+2.0, y-2.0, z+2.0, "O"),
243
- ("OE2", x+2.0, y-1.5, z+1.0, "O")
244
  ],
245
  'GLY': [], # Glycine has no side chain
 
 
 
 
 
 
 
 
246
  'ILE': [
247
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
248
- ("CG1", x+1.0, y-1.0, z+1.0, "C"),
249
- ("CG2", x+1.0, y-0.5, z+0.0, "C"),
250
- ("CD1", x+1.5, y-1.5, z+1.5, "C")
251
  ],
252
  'LEU': [
253
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
254
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
255
- ("CD1", x+1.5, y-1.5, z+1.5, "C"),
256
- ("CD2", x+1.5, y-0.5, z+0.5, "C")
257
  ],
258
  'LYS': [
259
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
260
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
261
- ("CD", x+1.5, y-1.5, z+1.5, "C"),
262
- ("CE", x+2.0, y-2.0, z+2.0, "C"),
263
- ("NZ", x+2.5, y-2.5, z+2.5, "N")
264
  ],
265
  'MET': [
266
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
267
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
268
- ("SD", x+1.5, y-1.5, z+1.5, "S"),
269
- ("CE", x+2.0, y-2.0, z+2.0, "C")
270
  ],
271
  'PHE': [
272
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
273
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
274
- ("CD1", x+1.5, y-1.5, z+1.5, "C"),
275
- ("CD2", x+1.5, y-0.5, z+0.5, "C"),
276
- ("CE1", x+2.0, y-2.0, z+2.0, "C"),
277
- ("CE2", x+2.0, y+0.0, z+0.0, "C"),
278
- ("CZ", x+2.5, y-1.0, z+1.0, "C")
279
  ],
280
  'PRO': [
281
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
282
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
283
- ("CD", x+0.0, y-1.0, z+1.0, "C")
284
  ],
285
- 'SER': [("CB", x+0.5, y-0.5, z+0.5, "C"), ("OG", x+1.0, y-1.0, z+1.0, "O")],
286
  'THR': [
287
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
288
- ("OG1", x+1.0, y-1.0, z+1.0, "O"),
289
- ("CG2", x+1.0, y+0.0, z+0.0, "C")
290
  ],
291
  'TRP': [
292
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
293
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
294
- ("CD1", x+1.5, y-1.5, z+1.5, "C"),
295
- ("CD2", x+1.5, y-0.5, z+0.5, "C"),
296
- ("NE1", x+2.0, y-1.0, z+1.0, "N"),
297
- ("CE2", x+2.0, y-0.5, z+0.5, "C"),
298
- ("CE3", x+2.0, y+0.5, z-0.5, "C"),
299
- ("CZ2", x+2.5, y+0.0, z+0.0, "C"),
300
- ("CZ3", x+2.5, y+1.0, z-1.0, "C"),
301
- ("CH2", x+3.0, y+0.5, z-0.5, "C")
302
  ],
303
  'TYR': [
304
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
305
- ("CG", x+1.0, y-1.0, z+1.0, "C"),
306
- ("CD1", x+1.5, y-1.5, z+1.5, "C"),
307
- ("CD2", x+1.5, y-0.5, z+0.5, "C"),
308
- ("CE1", x+2.0, y-2.0, z+2.0, "C"),
309
- ("CE2", x+2.0, y+0.0, z+0.0, "C"),
310
- ("CZ", x+2.5, y-1.0, z+1.0, "C"),
311
- ("OH", x+3.0, y-1.0, z+1.0, "O")
312
  ],
313
  'VAL': [
314
- ("CB", x+0.5, y-0.5, z+0.5, "C"),
315
- ("CG1", x+1.0, y-1.0, z+1.0, "C"),
316
- ("CG2", x+1.0, y+0.0, z+0.0, "C")
317
  ]
318
  }
319
 
320
- return side_chains.get(three_letter, [("CB", x+0.5, y-0.5, z+0.5, "C")]) # Default CB for unknown
 
 
 
 
 
 
 
 
321
 
322
  def _aa_three_letter(self, one_letter):
323
  """Convert one-letter amino acid code to three-letter"""
324
  aa_map = {
325
  'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'C': 'CYS',
326
- 'Q': 'GLN', 'E': 'GLU', 'G': 'GLY', 'H': 'ALA', 'I': 'ILE', # H->ALA to avoid HIS ring issues
327
  'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO',
328
  'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL'
329
  }
@@ -341,6 +393,32 @@ class StructureGenerator:
341
  # Check if all characters are valid amino acids
342
  return all(aa in valid_aa for aa in sequence_clean)
343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  def energy_minimize_structure(self, pdb_path):
345
  """
346
  Perform basic energy minimization on structure
 
35
  logger.info(f"Using system temp directory: {self.temp_dir}")
36
  return self.temp_dir
37
 
38
+ def generate_structure(self, heavy_chain, light_chain, force_fallback=False):
39
  """
40
+ Generate antibody structure using ImmuneBuilder or a basic fallback.
41
 
42
  Args:
43
+ heavy_chain (str): Heavy chain sequence.
44
+ light_chain (str): Light chain sequence.
45
+ force_fallback (bool): If True, forces the use of the basic fallback generator for testing.
46
+
47
  Returns:
48
+ str: Path to the generated PDB file.
49
  """
50
+ if not self.immune_builder_available or force_fallback:
51
+ logger.warning(
52
+ "ImmuneBuilder not found or fallback forced. Using basic structure generator. "
53
+ "This is a simplified model and may not be accurate."
54
+ )
55
+ try:
56
+ pdb_file = self._create_basic_pdb_structure(heavy_chain, light_chain)
57
+ if not os.path.exists(pdb_file):
58
+ raise FileNotFoundError("Fallback structure generator failed to create a PDB file.")
59
+ logger.info(f"Fallback PDB file created: {pdb_file}")
60
+ return pdb_file
61
+ except Exception as e:
62
+ logger.error(f"Fallback structure generator failed: {e}")
63
+ raise
64
+
65
+ logger.info("Attempting to generate structure with ImmuneBuilder...")
66
 
67
  def _generate_with_immunebuilder(self, heavy_chain, light_chain, output_path):
68
  """Generate structure using ImmuneBuilder (when available)"""
 
155
 
156
  # Add heavy chain atoms with complete side chains
157
  for i, aa in enumerate(heavy_chain, 1):
158
+ # Ensure coordinates are proper floats to prevent NaN
159
+ x = self._safe_float(i * 3.8) # Simple linear chain
160
+ y = self._safe_float(0.0)
161
+ z = self._safe_float(0.0)
162
+
163
+ # Validate coordinates before proceeding
164
+ if not self._validate_coordinates(x, y, z):
165
+ logger.error(f"Invalid coordinates generated for heavy chain residue {i}: {x}, {y}, {z}")
166
+ raise ValueError(f"NaN coordinates detected for heavy chain residue {i}")
167
 
168
  three_letter = self._aa_three_letter(aa)
169
 
 
174
 
175
  # Add light chain atoms with complete side chains
176
  for i, aa in enumerate(light_chain, 1):
177
+ # Ensure coordinates are proper floats to prevent NaN
178
+ x = self._safe_float(i * 3.8)
179
+ y = self._safe_float(15.0) # Offset from heavy chain
180
+ z = self._safe_float(0.0)
181
+
182
+ # Validate coordinates before proceeding
183
+ if not self._validate_coordinates(x, y, z):
184
+ logger.error(f"Invalid coordinates generated for light chain residue {i}: {x}, {y}, {z}")
185
+ raise ValueError(f"NaN coordinates detected for light chain residue {i}")
186
 
187
  three_letter = self._aa_three_letter(aa)
188
 
 
198
  def _add_complete_residue(self, pdb_lines, atom_counter, three_letter, res_id, x, y, z):
199
  """Add a complete amino acid residue with all required atoms"""
200
 
201
+ # Validate input coordinates
202
+ if not self._validate_coordinates(x, y, z):
203
+ logger.error(f"Invalid coordinates passed to _add_complete_residue: {x}, {y}, {z}")
204
+ raise ValueError(f"NaN coordinates detected for residue {res_id}")
205
+
206
+ # Backbone atoms (required for all residues) - ensure all are valid floats
207
  backbone_atoms = [
208
+ ("N", self._safe_float(x-1.0), self._safe_float(y), self._safe_float(z), "N"),
209
+ ("CA", self._safe_float(x), self._safe_float(y), self._safe_float(z), "C"),
210
+ ("C", self._safe_float(x+1.0), self._safe_float(y), self._safe_float(z), "C"),
211
+ ("O", self._safe_float(x+1.0), self._safe_float(y+1.0), self._safe_float(z), "O")
212
  ]
213
 
214
  # Add side chain atoms based on residue type
215
  side_chain_atoms = self._get_side_chain_atoms(three_letter, x, y, z)
216
 
217
+ # Combine all atoms and validate each coordinate
218
  all_atoms = backbone_atoms + side_chain_atoms
219
 
220
+ # Validate all atom coordinates before writing
221
+ for atom_name, ax, ay, az, element in all_atoms:
222
+ if not self._validate_coordinates(ax, ay, az):
223
+ logger.error(f"Invalid atom coordinates for {atom_name} in {res_id}: {ax}, {ay}, {az}")
224
+ raise ValueError(f"NaN coordinates detected for atom {atom_name} in residue {res_id}")
225
+
226
  # Write atoms to PDB
227
  for atom_name, ax, ay, az, element in all_atoms:
228
  pdb_line = f"ATOM {atom_counter:5d} {atom_name:<3} {three_letter} {res_id} {ax:8.3f}{ay:8.3f}{az:8.3f} 1.00 20.00 {element}"
 
234
  def _get_side_chain_atoms(self, three_letter, x, y, z):
235
  """Get side chain atoms for a specific amino acid"""
236
 
237
+ # Ensure base coordinates are valid
238
+ if not self._validate_coordinates(x, y, z):
239
+ logger.error(f"Invalid base coordinates for side chain generation: {x}, {y}, {z}")
240
+ raise ValueError(f"NaN coordinates detected for side chain base coordinates")
241
+
242
+ # Define side chain atoms for each amino acid type with safe coordinate calculation
243
  side_chains = {
244
+ 'ALA': [("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C")],
245
  'ARG': [
246
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
247
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
248
+ ("CD", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
249
+ ("NE", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "N"),
250
+ ("CZ", self._safe_float(x+2.5), self._safe_float(y-2.5), self._safe_float(z+2.5), "C"),
251
+ ("NH1", self._safe_float(x+3.0), self._safe_float(y-3.0), self._safe_float(z+3.0), "N"),
252
+ ("NH2", self._safe_float(x+3.0), self._safe_float(y-3.0), self._safe_float(z+2.0), "N")
253
  ],
254
  'ASN': [
255
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
256
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
257
+ ("OD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "O"),
258
+ ("ND2", self._safe_float(x+1.5), self._safe_float(y-1.0), self._safe_float(z+0.5), "N")
259
  ],
260
  'ASP': [
261
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
262
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
263
+ ("OD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "O"),
264
+ ("OD2", self._safe_float(x+1.5), self._safe_float(y-1.0), self._safe_float(z+0.5), "O")
265
  ],
266
+ 'CYS': [("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"), ("SG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "S")],
267
  'GLN': [
268
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
269
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
270
+ ("CD", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
271
+ ("OE1", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "O"),
272
+ ("NE2", self._safe_float(x+2.0), self._safe_float(y-1.5), self._safe_float(z+1.0), "N")
273
  ],
274
  'GLU': [
275
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
276
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
277
+ ("CD", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
278
+ ("OE1", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "O"),
279
+ ("OE2", self._safe_float(x+2.0), self._safe_float(y-1.5), self._safe_float(z+1.0), "O")
280
  ],
281
  'GLY': [], # Glycine has no side chain
282
+ 'HIS': [ # Fixed: Use proper histidine instead of mapping to ALA
283
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
284
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
285
+ ("ND1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "N"),
286
+ ("CD2", self._safe_float(x+1.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
287
+ ("CE1", self._safe_float(x+2.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
288
+ ("NE2", self._safe_float(x+2.0), self._safe_float(y-0.5), self._safe_float(z+0.5), "N")
289
+ ],
290
  'ILE': [
291
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
292
+ ("CG1", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
293
+ ("CG2", self._safe_float(x+1.0), self._safe_float(y-0.5), self._safe_float(z+0.0), "C"),
294
+ ("CD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C")
295
  ],
296
  'LEU': [
297
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
298
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
299
+ ("CD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
300
+ ("CD2", self._safe_float(x+1.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C")
301
  ],
302
  'LYS': [
303
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
304
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
305
+ ("CD", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
306
+ ("CE", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "C"),
307
+ ("NZ", self._safe_float(x+2.5), self._safe_float(y-2.5), self._safe_float(z+2.5), "N")
308
  ],
309
  'MET': [
310
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
311
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
312
+ ("SD", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "S"),
313
+ ("CE", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "C")
314
  ],
315
  'PHE': [
316
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
317
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
318
+ ("CD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
319
+ ("CD2", self._safe_float(x+1.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
320
+ ("CE1", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "C"),
321
+ ("CE2", self._safe_float(x+2.0), self._safe_float(y+0.0), self._safe_float(z+0.0), "C"),
322
+ ("CZ", self._safe_float(x+2.5), self._safe_float(y-1.0), self._safe_float(z+1.0), "C")
323
  ],
324
  'PRO': [
325
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
326
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
327
+ ("CD", self._safe_float(x+0.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C")
328
  ],
329
+ 'SER': [("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"), ("OG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "O")],
330
  'THR': [
331
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
332
+ ("OG1", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "O"),
333
+ ("CG2", self._safe_float(x+1.0), self._safe_float(y+0.0), self._safe_float(z+0.0), "C")
334
  ],
335
  'TRP': [
336
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
337
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
338
+ ("CD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
339
+ ("CD2", self._safe_float(x+1.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
340
+ ("NE1", self._safe_float(x+2.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "N"),
341
+ ("CE2", self._safe_float(x+2.0), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
342
+ ("CE3", self._safe_float(x+2.0), self._safe_float(y+0.5), self._safe_float(z-0.5), "C"),
343
+ ("CZ2", self._safe_float(x+2.5), self._safe_float(y+0.0), self._safe_float(z+0.0), "C"),
344
+ ("CZ3", self._safe_float(x+2.5), self._safe_float(y+1.0), self._safe_float(z-1.0), "C"),
345
+ ("CH2", self._safe_float(x+3.0), self._safe_float(y+0.5), self._safe_float(z-0.5), "C")
346
  ],
347
  'TYR': [
348
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
349
+ ("CG", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
350
+ ("CD1", self._safe_float(x+1.5), self._safe_float(y-1.5), self._safe_float(z+1.5), "C"),
351
+ ("CD2", self._safe_float(x+1.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
352
+ ("CE1", self._safe_float(x+2.0), self._safe_float(y-2.0), self._safe_float(z+2.0), "C"),
353
+ ("CE2", self._safe_float(x+2.0), self._safe_float(y+0.0), self._safe_float(z+0.0), "C"),
354
+ ("CZ", self._safe_float(x+2.5), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
355
+ ("OH", self._safe_float(x+3.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "O")
356
  ],
357
  'VAL': [
358
+ ("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C"),
359
+ ("CG1", self._safe_float(x+1.0), self._safe_float(y-1.0), self._safe_float(z+1.0), "C"),
360
+ ("CG2", self._safe_float(x+1.0), self._safe_float(y+0.0), self._safe_float(z+0.0), "C")
361
  ]
362
  }
363
 
364
+ side_chain = side_chains.get(three_letter, [("CB", self._safe_float(x+0.5), self._safe_float(y-0.5), self._safe_float(z+0.5), "C")]) # Default CB for unknown
365
+
366
+ # Validate all side chain atom coordinates
367
+ for atom_name, ax, ay, az, element in side_chain:
368
+ if not self._validate_coordinates(ax, ay, az):
369
+ logger.error(f"Invalid side chain coordinates for {atom_name} in {three_letter}: {ax}, {ay}, {az}")
370
+ raise ValueError(f"NaN coordinates detected for side chain atom {atom_name}")
371
+
372
+ return side_chain
373
 
374
  def _aa_three_letter(self, one_letter):
375
  """Convert one-letter amino acid code to three-letter"""
376
  aa_map = {
377
  'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'C': 'CYS',
378
+ 'Q': 'GLN', 'E': 'GLU', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE', # Fixed: H->HIS instead of ALA
379
  'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO',
380
  'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL'
381
  }
 
393
  # Check if all characters are valid amino acids
394
  return all(aa in valid_aa for aa in sequence_clean)
395
 
396
+ def _safe_float(self, value):
397
+ """Safely convert value to float, ensuring no NaN or inf"""
398
+ try:
399
+ result = float(value)
400
+ if not self._is_valid_number(result):
401
+ logger.error(f"Invalid number detected: {value} -> {result}")
402
+ raise ValueError(f"Invalid coordinate value: {value}")
403
+ return result
404
+ except (TypeError, ValueError) as e:
405
+ logger.error(f"Could not convert to float: {value}, error: {e}")
406
+ raise ValueError(f"Could not convert coordinate to float: {value}")
407
+
408
+ def _is_valid_number(self, value):
409
+ """Check if a number is valid (not NaN, not inf)"""
410
+ import math
411
+ return not (math.isnan(value) or math.isinf(value))
412
+
413
+ def _validate_coordinates(self, x, y, z):
414
+ """Validate that coordinates are proper finite numbers"""
415
+ try:
416
+ return (self._is_valid_number(x) and
417
+ self._is_valid_number(y) and
418
+ self._is_valid_number(z))
419
+ except:
420
+ return False
421
+
422
  def energy_minimize_structure(self, pdb_path):
423
  """
424
  Perform basic energy minimization on structure
test_pipeline.py CHANGED
@@ -22,9 +22,17 @@ from mdp_manager import MDPManager
22
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
23
  logger = logging.getLogger(__name__)
24
 
25
- def test_structure_generation():
26
- """Test antibody structure generation"""
27
- logger.info("Testing structure generation...")
 
 
 
 
 
 
 
 
28
 
29
  # Test sequences (example antibody variable regions)
30
  heavy_chain = "QVQLVQSGAEVKKPGASVKVSCKASGYTFTSYYMHWVRQAPGQGLEWMGIINPSGGSTNYAQKFQGRVTMTRDTSASTAYMELSSLRSEDTAVYYCARSTYYGGDWYFDVWGQGTLVTVSS"
@@ -34,26 +42,37 @@ def test_structure_generation():
34
  generator = StructureGenerator()
35
 
36
  # Generate structure
37
- structure_path = generator.generate_structure(heavy_chain, light_chain)
38
 
39
  # Verify structure file exists
40
- if os.path.exists(structure_path):
41
  logger.info(f"βœ“ Structure generated successfully: {structure_path}")
42
 
43
  # Check file size
44
  file_size = os.path.getsize(structure_path)
45
  if file_size > 1000: # Should be at least 1KB
46
  logger.info(f"βœ“ Structure file size reasonable: {file_size} bytes")
 
 
 
 
 
 
 
 
 
47
  return True, structure_path
48
  else:
49
  logger.error(f"βœ— Structure file too small: {file_size} bytes")
50
  return False, None
51
  else:
52
- logger.error("βœ— Structure file not generated")
53
  return False, None
54
 
55
  except Exception as e:
56
  logger.error(f"βœ— Structure generation failed: {e}")
 
 
57
  return False, None
58
  finally:
59
  try:
@@ -214,8 +233,11 @@ def run_all_tests():
214
  # Test 1: MDP templates
215
  results['mdp_templates'] = test_mdp_templates()
216
 
217
- # Test 2: Structure generation
218
- results['structure_generation'] = test_structure_generation()[0]
 
 
 
219
 
220
  # Test 3: GROMACS installation
221
  results['gromacs_installation'] = test_gromacs_installation()
@@ -224,7 +246,7 @@ def run_all_tests():
224
  results['ml_models'] = test_ml_models()
225
 
226
  # Test 5: Quick pipeline
227
- if all([results['mdp_templates'], results['structure_generation'], results['gromacs_installation']]):
228
  results['quick_pipeline'] = test_quick_pipeline()
229
  else:
230
  results['quick_pipeline'] = False
 
22
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
23
  logger = logging.getLogger(__name__)
24
 
25
+ def test_structure_generation(force_fallback=False):
26
+ """
27
+ Test antibody structure generation.
28
+
29
+ Args:
30
+ force_fallback (bool): If True, forces the use of the basic fallback generator.
31
+ """
32
+ if force_fallback:
33
+ logger.info("Testing structure generation (FORCING FALLBACK)...")
34
+ else:
35
+ logger.info("Testing structure generation (ImmuneBuilder if available)...")
36
 
37
  # Test sequences (example antibody variable regions)
38
  heavy_chain = "QVQLVQSGAEVKKPGASVKVSCKASGYTFTSYYMHWVRQAPGQGLEWMGIINPSGGSTNYAQKFQGRVTMTRDTSASTAYMELSSLRSEDTAVYYCARSTYYGGDWYFDVWGQGTLVTVSS"
 
42
  generator = StructureGenerator()
43
 
44
  # Generate structure
45
+ structure_path = generator.generate_structure(heavy_chain, light_chain, force_fallback=force_fallback)
46
 
47
  # Verify structure file exists
48
+ if structure_path and os.path.exists(structure_path):
49
  logger.info(f"βœ“ Structure generated successfully: {structure_path}")
50
 
51
  # Check file size
52
  file_size = os.path.getsize(structure_path)
53
  if file_size > 1000: # Should be at least 1KB
54
  logger.info(f"βœ“ Structure file size reasonable: {file_size} bytes")
55
+
56
+ # Add validation for NaN coordinates
57
+ with open(structure_path, 'r') as f:
58
+ for line in f:
59
+ if "NaN" in line:
60
+ logger.error(f"βœ— NaN detected in generated structure file: {line.strip()}")
61
+ return False, None
62
+
63
+ logger.info("βœ“ No NaN coordinates found in structure file.")
64
  return True, structure_path
65
  else:
66
  logger.error(f"βœ— Structure file too small: {file_size} bytes")
67
  return False, None
68
  else:
69
+ logger.error("βœ— Structure file not generated or path is None")
70
  return False, None
71
 
72
  except Exception as e:
73
  logger.error(f"βœ— Structure generation failed: {e}")
74
+ import traceback
75
+ traceback.print_exc()
76
  return False, None
77
  finally:
78
  try:
 
233
  # Test 1: MDP templates
234
  results['mdp_templates'] = test_mdp_templates()
235
 
236
+ # Test 2: Structure generation with ImmuneBuilder (if available)
237
+ results['structure_generation_immune_builder'] = test_structure_generation(force_fallback=False)[0]
238
+
239
+ # Test 2.1: Structure generation with fallback generator
240
+ results['structure_generation_fallback'] = test_structure_generation(force_fallback=True)[0]
241
 
242
  # Test 3: GROMACS installation
243
  results['gromacs_installation'] = test_gromacs_installation()
 
246
  results['ml_models'] = test_ml_models()
247
 
248
  # Test 5: Quick pipeline
249
+ if all([results['mdp_templates'], results['structure_generation_fallback'], results['gromacs_installation']]):
250
  results['quick_pipeline'] = test_quick_pipeline()
251
  else:
252
  results['quick_pipeline'] = False