Core API

This section documents the core data structures and fundamental types used within FlatProt.

Structure Representation

Represents a complete protein structure composed of multiple chains.

Source code in src/flatprot/core/structure.py
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)

coordinates property

Get a concatenated array of all coordinates across all chains, or None if empty.

residues property

Get a flattened list of all residues across all chains.

__contains__(chain_id)

Check if a chain ID or ResidueCoordinate exists in the structure.

Source code in src/flatprot/core/structure.py
441
442
443
444
445
446
447
448
449
450
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

__getitem__(chain_id)

Get a chain by its ID.

Source code in src/flatprot/core/structure.py
437
438
439
def __getitem__(self, chain_id: str) -> Chain:
    """Get a chain by its ID."""
    return self.__chains[chain_id]

__init__(chains, id=None)

Initializes a Structure object.

Parameters:
  • chains (list[Chain]) –

    A list of Chain objects representing the chains in the structure.

  • id (Optional[str], default: None ) –

    An optional identifier for the structure (e.g., PDB ID or filename stem).

Source code in src/flatprot/core/structure.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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()
    )

__iter__()

Iterate over chain IDs and Chain objects.

Source code in src/flatprot/core/structure.py
452
453
454
def __iter__(self) -> Iterator[tuple[str, Chain]]:
    """Iterate over chain IDs and Chain objects."""
    return iter(self.__chains.items())

__len__()

Return the number of chains in the structure.

Source code in src/flatprot/core/structure.py
464
465
466
def __len__(self) -> int:
    """Return the number of chains in the structure."""
    return len(self.__chains)

apply_vectorized_transformation(transformer_func)

Applies a transformation function to all coordinates and returns a new Structure.

Parameters:
  • transformer_func (Callable[[ndarray], ndarray]) –

    A function that takes an (N, 3) coordinate array and returns a transformed (N, 3) array.

Returns:
  • Structure

    A new Structure instance with transformed coordinates.

Source code in src/flatprot/core/structure.py
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
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)

get_coordinate_at_residue(residue)

Get the 3D coordinate for a specific residue.

Parameters:
Returns:
  • Optional[ndarray]

    A NumPy array of coordinates (shape [3]) representing the residue's

  • Optional[ndarray]

    position (X, Y, Z), or None if the residue is not found.

Source code in src/flatprot/core/structure.py
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
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

items()

Return an iterator over chain ID / Chain pairs.

Source code in src/flatprot/core/structure.py
456
457
458
def items(self) -> Iterator[tuple[str, Chain]]:
    """Return an iterator over chain ID / Chain pairs."""
    return self.__chains.items()

values()

Return an iterator over Chain objects.

Source code in src/flatprot/core/structure.py
460
461
462
def values(self) -> Iterator[Chain]:
    """Return an iterator over Chain objects."""
    return self.__chains.values()

with_coordinates(coordinates)

Create a new Structure with the given coordinates, preserving topology.

Parameters:
  • coordinates (ndarray) –

    A NumPy array of shape (N, 3) containing the new coordinates, ordered consistently with the original structure's concatenated coordinates.

Returns:
  • Structure

    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.

Source code in src/flatprot/core/structure.py
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
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)

options: show_root_heading: true members_order: source

Coordinate and Range Types

ResidueCoordinate dataclass

Source code in src/flatprot/core/coordinates.py
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
@dataclass(frozen=True)
class ResidueCoordinate:
    chain_id: str
    residue_index: int
    residue_type: Optional[ResidueType] = None
    coordinate_index: Optional[int] = None

    @staticmethod
    def from_string(string: str) -> "ResidueCoordinate":
        """Parse 'CHAIN:INDEX' format (e.g., 'A:123').

        Args:
            string: The string representation to parse.

        Returns:
            A ResidueCoordinate instance.

        Raises:
            ValueError: If the string format is invalid.
        """
        match = _RESIDUE_COORD_PATTERN.match(string)
        if not match:
            raise ValueError(
                f"Invalid ResidueCoordinate format: '{string}'. Expected 'CHAIN:INDEX'."
            )
        chain_name, residue_index_str = match.groups()
        return ResidueCoordinate(chain_name, int(residue_index_str))

    def __str__(self) -> str:
        if self.residue_type:
            return f"{self.chain_id}:{self.residue_index} ({self.residue_type.name})"
        else:
            return f"{self.chain_id}:{self.residue_index}"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ResidueCoordinate):
            raise TypeError(f"Cannot compare ResidueCoordinate with {type(other)}")
        return (
            self.chain_id == other.chain_id
            and self.residue_index == other.residue_index
        )

    def __lt__(self, other: object) -> bool:
        if not isinstance(other, ResidueCoordinate):
            raise TypeError(f"Cannot compare ResidueCoordinate with {type(other)}")

        if self.chain_id != other.chain_id:
            return self.chain_id < other.chain_id
        return self.residue_index < other.residue_index

from_string(string) staticmethod

Parse 'CHAIN:INDEX' format (e.g., 'A:123').

Parameters:
  • string (str) –

    The string representation to parse.

Returns:
Raises:
  • ValueError

    If the string format is invalid.

Source code in src/flatprot/core/coordinates.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@staticmethod
def from_string(string: str) -> "ResidueCoordinate":
    """Parse 'CHAIN:INDEX' format (e.g., 'A:123').

    Args:
        string: The string representation to parse.

    Returns:
        A ResidueCoordinate instance.

    Raises:
        ValueError: If the string format is invalid.
    """
    match = _RESIDUE_COORD_PATTERN.match(string)
    if not match:
        raise ValueError(
            f"Invalid ResidueCoordinate format: '{string}'. Expected 'CHAIN:INDEX'."
        )
    chain_name, residue_index_str = match.groups()
    return ResidueCoordinate(chain_name, int(residue_index_str))

ResidueRange dataclass

Represents a continuous range of residues within a single chain.

Source code in src/flatprot/core/coordinates.py
 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
@dataclass(frozen=True)
class ResidueRange:
    """Represents a continuous range of residues within a single chain."""

    chain_id: str
    start: int
    end: int
    coordinates_start_index: Optional[int] = None
    secondary_structure_type: Optional[SecondaryStructureType] = None

    def to_set(self) -> "ResidueRangeSet":
        return ResidueRangeSet([self])

    def __post_init__(self) -> None:
        if self.start > self.end:
            raise ValueError(f"Invalid range: {self.start} > {self.end}")

    def __iter__(self) -> Iterator[ResidueCoordinate]:
        """Iterate over all ResidueCoordinates in this range."""
        for i in range(self.start, self.end + 1):
            yield ResidueCoordinate(self.chain_id, i)

    def __len__(self) -> int:
        """Number of residues in this range."""
        return self.end - self.start + 1

    @staticmethod
    def from_string(string: str) -> "ResidueRange":
        """Parse 'CHAIN:START-END' format (e.g., 'A:14-20').

        Args:
            string: The string representation to parse.

        Returns:
            A ResidueRange instance.

        Raises:
            ValueError: If the string format is invalid or start > end.
        """
        match = _RESIDUE_RANGE_PATTERN.match(string)
        if not match:
            raise ValueError(
                f"Invalid ResidueRange format: '{string}'. Expected 'CHAIN:START-END'."
            )
        chain, start_str, end_str = match.groups()
        start, end = int(start_str), int(end_str)
        # The __post_init__ check for start > end will still run
        return ResidueRange(chain, start, end)

    def __str__(self) -> str:
        if self.secondary_structure_type:
            return f"{self.chain_id}:{self.start}-{self.end} ({self.secondary_structure_type.name})"
        else:
            return f"{self.chain_id}:{self.start}-{self.end}"

    def __lt__(self, other: "ResidueRange") -> bool:
        """Compare ranges for sorting.

        Sorts first by chain_id, then by start position.

        Args:
            other: Another ResidueRange to compare with

        Returns:
            bool: True if this range should come before the other
        """
        if not isinstance(other, ResidueRange):
            raise TypeError(f"Cannot compare ResidueRange with {type(other)}")

        if self.chain_id != other.chain_id:
            return self.chain_id < other.chain_id
        return self.start < other.start

    def __eq__(self, other: object) -> bool:
        """Check if two ranges are equal.

        Args:
            other: Another object to compare with

        Returns:
            bool: True if the ranges are equal
        """
        if not isinstance(other, ResidueRange):
            raise TypeError(f"Cannot compare ResidueRange with {type(other)}")

        return (
            self.chain_id == other.chain_id
            and self.start == other.start
            and self.end == other.end
        )

    def __contains__(self, other: object) -> bool:
        """Check if this range contains another range or residue coordinate.

        Args:
            other: Another object to check containment with

        Returns:
            bool: True if this range contains the other object
        """
        if isinstance(other, ResidueRange):
            return (
                self.chain_id == other.chain_id
                and self.start <= other.start
                and self.end >= other.end
            )
        elif isinstance(other, ResidueCoordinate):
            return (
                self.chain_id == other.chain_id
                and self.start <= other.residue_index <= self.end
            )

    def is_adjacent_to(self, other: Union["ResidueRange", ResidueCoordinate]) -> bool:
        """Check if this range is adjacent to another range or residue coordinate.

        Two ranges are considered adjacent if they are in the same chain and
        one range's end is exactly one residue before the other range's start.
        For example, A:10-15 is adjacent to A:16-20, but not to A:15-20 (overlap)
        or A:17-20 (gap).

        A range and a residue coordinate are considered adjacent if they are in the
        same chain and the coordinate is exactly one residue before the range's start
        or exactly one residue after the range's end.

        Args:
            other: The other range or residue coordinate to check adjacency with.

        Returns:
            bool: True if the range is adjacent to the other object, False otherwise.

        Raises:
            TypeError: If other is not a ResidueRange or ResidueCoordinate.
        """
        if not isinstance(other, (ResidueRange, ResidueCoordinate)):
            raise TypeError(f"Cannot check adjacency with {type(other)}")

        # Must be in the same chain to be adjacent
        if self.chain_id != other.chain_id:
            return False

        if isinstance(other, ResidueRange):
            # Check if self's end is exactly one residue before other's start
            if self.end + 1 == other.start:
                return True

            # Check if other's end is exactly one residue before self's start
            if other.end + 1 == self.start:
                return True
        else:  # ResidueCoordinate
            # Check if the coordinate is exactly one residue before the range's start
            if other.residue_index + 1 == self.start:
                return True

            # Check if the coordinate is exactly one residue after the range's end
            if self.end + 1 == other.residue_index:
                return True

        return False

__contains__(other)

Check if this range contains another range or residue coordinate.

Parameters:
  • other (object) –

    Another object to check containment with

Returns:
  • bool( bool ) –

    True if this range contains the other object

Source code in src/flatprot/core/coordinates.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __contains__(self, other: object) -> bool:
    """Check if this range contains another range or residue coordinate.

    Args:
        other: Another object to check containment with

    Returns:
        bool: True if this range contains the other object
    """
    if isinstance(other, ResidueRange):
        return (
            self.chain_id == other.chain_id
            and self.start <= other.start
            and self.end >= other.end
        )
    elif isinstance(other, ResidueCoordinate):
        return (
            self.chain_id == other.chain_id
            and self.start <= other.residue_index <= self.end
        )

__eq__(other)

Check if two ranges are equal.

Parameters:
  • other (object) –

    Another object to compare with

Returns:
  • bool( bool ) –

    True if the ranges are equal

Source code in src/flatprot/core/coordinates.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def __eq__(self, other: object) -> bool:
    """Check if two ranges are equal.

    Args:
        other: Another object to compare with

    Returns:
        bool: True if the ranges are equal
    """
    if not isinstance(other, ResidueRange):
        raise TypeError(f"Cannot compare ResidueRange with {type(other)}")

    return (
        self.chain_id == other.chain_id
        and self.start == other.start
        and self.end == other.end
    )

__iter__()

Iterate over all ResidueCoordinates in this range.

Source code in src/flatprot/core/coordinates.py
84
85
86
87
def __iter__(self) -> Iterator[ResidueCoordinate]:
    """Iterate over all ResidueCoordinates in this range."""
    for i in range(self.start, self.end + 1):
        yield ResidueCoordinate(self.chain_id, i)

__len__()

Number of residues in this range.

Source code in src/flatprot/core/coordinates.py
89
90
91
def __len__(self) -> int:
    """Number of residues in this range."""
    return self.end - self.start + 1

__lt__(other)

Compare ranges for sorting.

Sorts first by chain_id, then by start position.

Parameters:
  • other (ResidueRange) –

    Another ResidueRange to compare with

Returns:
  • bool( bool ) –

    True if this range should come before the other

Source code in src/flatprot/core/coordinates.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __lt__(self, other: "ResidueRange") -> bool:
    """Compare ranges for sorting.

    Sorts first by chain_id, then by start position.

    Args:
        other: Another ResidueRange to compare with

    Returns:
        bool: True if this range should come before the other
    """
    if not isinstance(other, ResidueRange):
        raise TypeError(f"Cannot compare ResidueRange with {type(other)}")

    if self.chain_id != other.chain_id:
        return self.chain_id < other.chain_id
    return self.start < other.start

from_string(string) staticmethod

Parse 'CHAIN:START-END' format (e.g., 'A:14-20').

Parameters:
  • string (str) –

    The string representation to parse.

Returns:
Raises:
  • ValueError

    If the string format is invalid or start > end.

Source code in src/flatprot/core/coordinates.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@staticmethod
def from_string(string: str) -> "ResidueRange":
    """Parse 'CHAIN:START-END' format (e.g., 'A:14-20').

    Args:
        string: The string representation to parse.

    Returns:
        A ResidueRange instance.

    Raises:
        ValueError: If the string format is invalid or start > end.
    """
    match = _RESIDUE_RANGE_PATTERN.match(string)
    if not match:
        raise ValueError(
            f"Invalid ResidueRange format: '{string}'. Expected 'CHAIN:START-END'."
        )
    chain, start_str, end_str = match.groups()
    start, end = int(start_str), int(end_str)
    # The __post_init__ check for start > end will still run
    return ResidueRange(chain, start, end)

is_adjacent_to(other)

Check if this range is adjacent to another range or residue coordinate.

Two ranges are considered adjacent if they are in the same chain and one range's end is exactly one residue before the other range's start. For example, A:10-15 is adjacent to A:16-20, but not to A:15-20 (overlap) or A:17-20 (gap).

A range and a residue coordinate are considered adjacent if they are in the same chain and the coordinate is exactly one residue before the range's start or exactly one residue after the range's end.

Parameters:
Returns:
  • bool( bool ) –

    True if the range is adjacent to the other object, False otherwise.

Raises:
  • TypeError

    If other is not a ResidueRange or ResidueCoordinate.

Source code in src/flatprot/core/coordinates.py
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
def is_adjacent_to(self, other: Union["ResidueRange", ResidueCoordinate]) -> bool:
    """Check if this range is adjacent to another range or residue coordinate.

    Two ranges are considered adjacent if they are in the same chain and
    one range's end is exactly one residue before the other range's start.
    For example, A:10-15 is adjacent to A:16-20, but not to A:15-20 (overlap)
    or A:17-20 (gap).

    A range and a residue coordinate are considered adjacent if they are in the
    same chain and the coordinate is exactly one residue before the range's start
    or exactly one residue after the range's end.

    Args:
        other: The other range or residue coordinate to check adjacency with.

    Returns:
        bool: True if the range is adjacent to the other object, False otherwise.

    Raises:
        TypeError: If other is not a ResidueRange or ResidueCoordinate.
    """
    if not isinstance(other, (ResidueRange, ResidueCoordinate)):
        raise TypeError(f"Cannot check adjacency with {type(other)}")

    # Must be in the same chain to be adjacent
    if self.chain_id != other.chain_id:
        return False

    if isinstance(other, ResidueRange):
        # Check if self's end is exactly one residue before other's start
        if self.end + 1 == other.start:
            return True

        # Check if other's end is exactly one residue before self's start
        if other.end + 1 == self.start:
            return True
    else:  # ResidueCoordinate
        # Check if the coordinate is exactly one residue before the range's start
        if other.residue_index + 1 == self.start:
            return True

        # Check if the coordinate is exactly one residue after the range's end
        if self.end + 1 == other.residue_index:
            return True

    return False

ResidueRangeSet

Represents multiple ranges of residues, potentially across different chains.

Source code in src/flatprot/core/coordinates.py
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
class ResidueRangeSet:
    """Represents multiple ranges of residues, potentially across different chains."""

    def __init__(self, ranges: List[ResidueRange]):
        # Sort ranges for consistent representation and efficient searching
        self.ranges = sorted(ranges, key=lambda r: (r.chain_id, r.start))

    @staticmethod
    def from_string(string: str) -> "ResidueRangeSet":
        """Parse 'A:14-20, B:10-15' format.

        Ranges are separated by commas. Whitespace around ranges and commas
        is ignored.

        Args:
            string: The string representation to parse.

        Returns:
            A ResidueRangeSet instance.

        Raises:
            ValueError: If the string is empty, contains empty parts after
                      splitting by comma, or if any individual range
                      part is invalid according to ResidueRange.from_string.
        """
        if not string:
            raise ValueError("Input string for ResidueRangeSet cannot be empty.")

        parts = string.split(",")
        ranges = []
        for part in parts:
            stripped_part = part.strip()
            if not stripped_part:
                # Handle cases like "A:1-5,,B:6-10" or leading/trailing commas
                raise ValueError(
                    f"Empty range part found in string: '{string}' after splitting by comma."
                )
            try:
                # Leverage ResidueRange's parsing and validation
                ranges.append(ResidueRange.from_string(stripped_part))
            except ValueError as e:
                # Re-raise with context about which part failed
                raise ValueError(
                    f"Error parsing range part '{stripped_part}' in '{string}': {e}"
                ) from e

        if not ranges:
            # This case might be redundant if empty string/parts are caught above,
            # but kept for robustness, e.g., if string only contains commas/whitespace.
            raise ValueError(f"No valid residue ranges found in string: '{string}'.")

        return ResidueRangeSet(ranges)

    def __iter__(self) -> Iterator[ResidueCoordinate]:
        """Iterate over all ResidueCoordinates in all ranges."""
        for range_ in self.ranges:
            yield from range_

    def __len__(self) -> int:
        """Total number of residues across all ranges."""
        return sum(len(range_) for range_ in self.ranges)

    def __str__(self) -> str:
        return ",".join(str(r) for r in self.ranges)

    def __repr__(self) -> str:
        return f"ResidueRangeSet({self.__str__()})"

    def __contains__(self, other: object) -> bool:
        """Check if this range set contains another range or residue coordinate.

        Args:
            other: Another object to check containment with

        Returns:
            bool: True if this range set contains the other object
        """
        if isinstance(other, ResidueRange):
            return any(other in range_ for range_ in self.ranges)
        elif isinstance(other, ResidueCoordinate):
            return any(other in range_ for range_ in self.ranges)
        return False

    def __eq__(self, other: object) -> bool:
        """Check if two range sets are equal.

        Args:
            other: Another object to compare with

        Returns:
            bool: True if the range sets are equal
        """
        if not isinstance(other, ResidueRangeSet):
            raise TypeError(f"Cannot compare ResidueRangeSet with {type(other)}")

        return sorted(self.ranges) == sorted(other.ranges)

    def is_adjacent_to(
        self, other: Union["ResidueRangeSet", ResidueRange, ResidueCoordinate]
    ) -> bool:
        """Check if this range set is adjacent to another range set, range, or coordinate.

        Two range sets are considered adjacent if any range in one set is
        adjacent to any range in the other set. Ranges are adjacent if they
        are in the same chain and one range's end is exactly one residue
        before the other range's start, or vice versa.

        Args:
            other: The other object to check adjacency with. Can be a ResidueRangeSet,
                  ResidueRange, or ResidueCoordinate.

        Returns:
            bool: True if the range sets are adjacent, False otherwise.

        Raises:
            TypeError: If other is not a ResidueRangeSet, ResidueRange, or ResidueCoordinate.
        """
        if isinstance(other, ResidueRangeSet):
            # Check each pair of ranges from both sets
            for range1 in self.ranges:
                for range2 in other.ranges:
                    if range1.is_adjacent_to(range2):
                        return True
        elif isinstance(other, (ResidueRange, ResidueCoordinate)):
            # Convert the single range to a set and check adjacency
            for range1 in self.ranges:
                if range1.is_adjacent_to(other):
                    return True
        else:
            raise TypeError(f"Cannot check adjacency with {type(other)}")

        return False

__contains__(other)

Check if this range set contains another range or residue coordinate.

Parameters:
  • other (object) –

    Another object to check containment with

Returns:
  • bool( bool ) –

    True if this range set contains the other object

Source code in src/flatprot/core/coordinates.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def __contains__(self, other: object) -> bool:
    """Check if this range set contains another range or residue coordinate.

    Args:
        other: Another object to check containment with

    Returns:
        bool: True if this range set contains the other object
    """
    if isinstance(other, ResidueRange):
        return any(other in range_ for range_ in self.ranges)
    elif isinstance(other, ResidueCoordinate):
        return any(other in range_ for range_ in self.ranges)
    return False

__eq__(other)

Check if two range sets are equal.

Parameters:
  • other (object) –

    Another object to compare with

Returns:
  • bool( bool ) –

    True if the range sets are equal

Source code in src/flatprot/core/coordinates.py
310
311
312
313
314
315
316
317
318
319
320
321
322
def __eq__(self, other: object) -> bool:
    """Check if two range sets are equal.

    Args:
        other: Another object to compare with

    Returns:
        bool: True if the range sets are equal
    """
    if not isinstance(other, ResidueRangeSet):
        raise TypeError(f"Cannot compare ResidueRangeSet with {type(other)}")

    return sorted(self.ranges) == sorted(other.ranges)

__iter__()

Iterate over all ResidueCoordinates in all ranges.

Source code in src/flatprot/core/coordinates.py
280
281
282
283
def __iter__(self) -> Iterator[ResidueCoordinate]:
    """Iterate over all ResidueCoordinates in all ranges."""
    for range_ in self.ranges:
        yield from range_

__len__()

Total number of residues across all ranges.

Source code in src/flatprot/core/coordinates.py
285
286
287
def __len__(self) -> int:
    """Total number of residues across all ranges."""
    return sum(len(range_) for range_ in self.ranges)

from_string(string) staticmethod

Parse 'A:14-20, B:10-15' format.

Ranges are separated by commas. Whitespace around ranges and commas is ignored.

Parameters:
  • string (str) –

    The string representation to parse.

Returns:
Raises:
  • ValueError

    If the string is empty, contains empty parts after splitting by comma, or if any individual range part is invalid according to ResidueRange.from_string.

Source code in src/flatprot/core/coordinates.py
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
@staticmethod
def from_string(string: str) -> "ResidueRangeSet":
    """Parse 'A:14-20, B:10-15' format.

    Ranges are separated by commas. Whitespace around ranges and commas
    is ignored.

    Args:
        string: The string representation to parse.

    Returns:
        A ResidueRangeSet instance.

    Raises:
        ValueError: If the string is empty, contains empty parts after
                  splitting by comma, or if any individual range
                  part is invalid according to ResidueRange.from_string.
    """
    if not string:
        raise ValueError("Input string for ResidueRangeSet cannot be empty.")

    parts = string.split(",")
    ranges = []
    for part in parts:
        stripped_part = part.strip()
        if not stripped_part:
            # Handle cases like "A:1-5,,B:6-10" or leading/trailing commas
            raise ValueError(
                f"Empty range part found in string: '{string}' after splitting by comma."
            )
        try:
            # Leverage ResidueRange's parsing and validation
            ranges.append(ResidueRange.from_string(stripped_part))
        except ValueError as e:
            # Re-raise with context about which part failed
            raise ValueError(
                f"Error parsing range part '{stripped_part}' in '{string}': {e}"
            ) from e

    if not ranges:
        # This case might be redundant if empty string/parts are caught above,
        # but kept for robustness, e.g., if string only contains commas/whitespace.
        raise ValueError(f"No valid residue ranges found in string: '{string}'.")

    return ResidueRangeSet(ranges)

is_adjacent_to(other)

Check if this range set is adjacent to another range set, range, or coordinate.

Two range sets are considered adjacent if any range in one set is adjacent to any range in the other set. Ranges are adjacent if they are in the same chain and one range's end is exactly one residue before the other range's start, or vice versa.

Parameters:
Returns:
  • bool( bool ) –

    True if the range sets are adjacent, False otherwise.

Raises:
  • TypeError

    If other is not a ResidueRangeSet, ResidueRange, or ResidueCoordinate.

Source code in src/flatprot/core/coordinates.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def is_adjacent_to(
    self, other: Union["ResidueRangeSet", ResidueRange, ResidueCoordinate]
) -> bool:
    """Check if this range set is adjacent to another range set, range, or coordinate.

    Two range sets are considered adjacent if any range in one set is
    adjacent to any range in the other set. Ranges are adjacent if they
    are in the same chain and one range's end is exactly one residue
    before the other range's start, or vice versa.

    Args:
        other: The other object to check adjacency with. Can be a ResidueRangeSet,
              ResidueRange, or ResidueCoordinate.

    Returns:
        bool: True if the range sets are adjacent, False otherwise.

    Raises:
        TypeError: If other is not a ResidueRangeSet, ResidueRange, or ResidueCoordinate.
    """
    if isinstance(other, ResidueRangeSet):
        # Check each pair of ranges from both sets
        for range1 in self.ranges:
            for range2 in other.ranges:
                if range1.is_adjacent_to(range2):
                    return True
    elif isinstance(other, (ResidueRange, ResidueCoordinate)):
        # Convert the single range to a set and check adjacency
        for range1 in self.ranges:
            if range1.is_adjacent_to(other):
                return True
    else:
        raise TypeError(f"Cannot check adjacency with {type(other)}")

    return False

options: show_root_heading: true members_order: source

Core Errors

CoordinateCalculationError

Bases: CoordinateError

Error raised when calculation of display coordinates fails (e.g., insufficient points).

Source code in src/flatprot/core/errors.py
20
21
22
23
24
class CoordinateCalculationError(CoordinateError):
    """Error raised when calculation of display coordinates fails (e.g., insufficient points)."""

    def __init__(self, message: str):
        super().__init__(message)

CoordinateError

Bases: FlatProtError

Error related to coordinate management.

Source code in src/flatprot/core/errors.py
13
14
15
16
17
class CoordinateError(FlatProtError):
    """Error related to coordinate management."""

    def __init__(self, message: str):
        super().__init__(message)

FlatProtError

Bases: Exception

Base exception class for FlatProt CLI errors.

This class is used as the base for all custom exceptions raised by the CLI. It provides a consistent interface for error handling and formatting.

Source code in src/flatprot/core/errors.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class FlatProtError(Exception):
    """Base exception class for FlatProt CLI errors.

    This class is used as the base for all custom exceptions raised by the CLI.
    It provides a consistent interface for error handling and formatting.
    """

    def __init__(self, message: str):
        self.message = message
        super().__init__(self.message)

options: show_root_heading: true members_order: source

Logger

Logging utilities for FlatProt.

getLogger(name=__app_name__)

Get a configured logger with the given name.

Parameters:
  • name (str, default: __app_name__ ) –

    Logger name (defaults to "flatprot")

Returns:
  • Logger

    Configured logging.Logger instance

Source code in src/flatprot/core/logger.py
10
11
12
13
14
15
16
17
18
19
20
21
def getLogger(name: str = __app_name__) -> logging.Logger:
    """Get a configured logger with the given name.

    Args:
        name: Logger name (defaults to "flatprot")

    Returns:
        Configured logging.Logger instance
    """
    # Get the logger
    logger = logging.getLogger(name)
    return logger

options: show_root_heading: true members_order: source