419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682 | class Structure:
"""Represents a complete protein structure composed of multiple chains."""
def __init__(self, chains: list[Chain], id: Optional[str] = None):
"""Initializes a Structure object.
Args:
chains: A list of Chain objects representing the chains in the structure.
id: An optional identifier for the structure (e.g., PDB ID or filename stem).
"""
self.__chains = {chain.id: chain for chain in chains}
self.id = id or "unknown_structure" # Assign ID or a default
# Pre-calculate total coordinates for validation if needed
self._total_coordinates = sum(
len(chain.coordinates) if chain.coordinates is not None else 0
for chain in self.values()
)
def __getitem__(self, chain_id: str) -> Chain:
"""Get a chain by its ID."""
return self.__chains[chain_id]
def __contains__(self, chain_id: str | ResidueCoordinate) -> bool:
"""Check if a chain ID or ResidueCoordinate exists in the structure."""
if isinstance(chain_id, str):
return chain_id in self.__chains
elif isinstance(chain_id, ResidueCoordinate):
return (
chain_id.chain_id in self.__chains
and chain_id.residue_index in self.__chains[chain_id.chain_id]
)
return False
def __iter__(self) -> Iterator[tuple[str, Chain]]:
"""Iterate over chain IDs and Chain objects."""
return iter(self.__chains.items())
def items(self) -> Iterator[tuple[str, Chain]]:
"""Return an iterator over chain ID / Chain pairs."""
return self.__chains.items()
def values(self) -> Iterator[Chain]:
"""Return an iterator over Chain objects."""
return self.__chains.values()
def __len__(self) -> int:
"""Return the number of chains in the structure."""
return len(self.__chains)
@property
def residues(self) -> list[ResidueType]:
"""Get a flattened list of all residues across all chains."""
all_residues = []
for chain in self.__chains.values():
all_residues.extend(chain.residues)
return all_residues
@property
def coordinates(self) -> Optional[np.ndarray]:
"""Get a concatenated array of all coordinates across all chains, or None if empty."""
all_coords = [
chain.coordinates
for chain in self.__chains.values()
if chain.coordinates is not None and chain.coordinates.size > 0
]
if not all_coords:
return None
return np.vstack(all_coords)
def __str__(self) -> str:
return f"Structure(ID: {self.id}, Chains: {list(self.__chains.keys())})"
def apply_vectorized_transformation(
self, transformer_func: Callable[[np.ndarray], np.ndarray]
) -> "Structure":
"""Applies a transformation function to all coordinates and returns a new Structure.
Args:
transformer_func: A function that takes an (N, 3) coordinate array
and returns a transformed (N, 3) array.
Returns:
A new Structure instance with transformed coordinates.
"""
new_chains = []
start_index = 0
original_coords = self.coordinates
if original_coords is None:
# Handle case with no coordinates - return a structure with chains having None coordinates
# Recreate chains with None coords, ensuring topology is preserved
for _, chain in self.items():
# Create new chain with None coords
new_chains.append(
Chain(
chain_id=chain.id,
residues=chain.residues, # Use property to get list
index=chain.index, # Use original index
coordinates=None, # Explicitly None
# Pass a copy of the original secondary structure list
secondary_structure=list(chain._Chain__secondary_structure),
)
)
return Structure(new_chains, id=self.id)
transformed_coords = transformer_func(original_coords)
# Check for shape change after transformation
if transformed_coords.shape != original_coords.shape:
raise ValueError(
f"Transformer function changed coordinate array shape from "
f"{original_coords.shape} to {transformed_coords.shape}"
)
for (
_,
chain,
) in (
self.items()
): # Iterate in insertion order (Python 3.7+) or sorted order if needed
num_coords_in_chain = (
len(chain.coordinates) if chain.coordinates is not None else 0
)
if num_coords_in_chain > 0:
# Slice the transformed coordinates for the current chain
chain_transformed_coords = transformed_coords[
start_index : start_index + num_coords_in_chain
]
# Create the new chain with the sliced coordinates
new_chains.append(
Chain(
chain_id=chain.id,
residues=chain.residues,
index=chain.index,
coordinates=chain_transformed_coords,
# Pass a copy of the original secondary structure list
secondary_structure=list(chain._Chain__secondary_structure),
)
)
start_index += num_coords_in_chain
else:
# Handle chains originally having no coordinates
new_chains.append(
Chain(
chain_id=chain.id,
residues=chain.residues,
index=chain.index,
coordinates=None, # Keep coordinates as None
secondary_structure=list(chain._Chain__secondary_structure),
)
)
# Ensure all coordinates were assigned
if start_index != transformed_coords.shape[0]:
raise ValueError(
f"Coordinate slicing error: processed {start_index} coordinates, "
f"but expected {transformed_coords.shape[0]}."
)
return Structure(new_chains, id=self.id)
def get_coordinate_at_residue(
self, residue: ResidueCoordinate
) -> Optional[np.ndarray]:
"""Get the 3D coordinate for a specific residue.
Args:
residue: The residue coordinate to query.
Returns:
A NumPy array of coordinates (shape [3]) representing the residue's
position (X, Y, Z), or None if the residue is not found.
"""
chain = self.__chains.get(residue.chain_id)
if chain is None:
return None
# Use the Chain's __contains__ and __getitem__ for residue lookup
if residue.residue_index in chain:
target_residue_coord = chain[residue.residue_index]
# Access the coordinates using the coordinate_index stored in ResidueCoordinate
# Ensure the chain has coordinates and the index is valid
if (
chain.coordinates is not None
and 0 <= target_residue_coord.coordinate_index < len(chain.coordinates)
):
return chain.coordinates[target_residue_coord.coordinate_index]
# Residue index not found in chain or coordinate index invalid
return None
def with_coordinates(self, coordinates: np.ndarray) -> "Structure":
"""Create a new Structure with the given coordinates, preserving topology.
Args:
coordinates: A NumPy array of shape (N, 3) containing the new coordinates,
ordered consistently with the original structure's concatenated coordinates.
Returns:
A new Structure instance with the provided coordinates.
Raises:
ValueError: If the shape or total number of input coordinates does not match
the original structure's coordinate count.
"""
if not isinstance(coordinates, np.ndarray):
raise TypeError("Input coordinates must be a numpy array.")
if coordinates.ndim != 2 or coordinates.shape[1] != 3:
raise ValueError(
f"Input coordinates must have shape (N, 3), got {coordinates.shape}"
)
# Validate that the number of provided coordinates matches the original structure
if coordinates.shape[0] != self._total_coordinates:
raise ValueError(
f"Input coordinates count ({coordinates.shape[0]}) does not match "
f"the original structure's total coordinates ({self._total_coordinates})."
)
new_chains = []
start_index = 0
for (
_,
chain,
) in self.items(): # Iterate through original chains to maintain order
num_coords_in_chain = (
len(chain.coordinates) if chain.coordinates is not None else 0
)
if num_coords_in_chain > 0:
# Slice the *new* coordinates array for the current chain
new_chain_coords = coordinates[
start_index : start_index + num_coords_in_chain
]
# Create the new chain with the sliced coordinates
new_chains.append(
Chain(
chain_id=chain.id,
residues=chain.residues,
index=chain.index,
coordinates=new_chain_coords,
# Pass a copy of the original secondary structure list
secondary_structure=list(chain._Chain__secondary_structure),
)
)
start_index += num_coords_in_chain
else:
# Handle chains originally having no coordinates
new_chains.append(
Chain(
chain_id=chain.id,
residues=chain.residues,
index=chain.index,
coordinates=None, # Keep coordinates as None
secondary_structure=list(chain._Chain__secondary_structure),
)
)
# Final check to ensure all provided coordinates were used
if start_index != coordinates.shape[0]:
raise ValueError( # Should not happen if initial count check passes, but good sanity check
f"Coordinate assignment error during 'with_coordinates': processed {start_index} coordinates, "
f"but input had {coordinates.shape[0]}."
)
return Structure(new_chains, id=self.id)
|