Skip to content

base

DEFAULT_SS_COIL_IDENTIFIER module-attribute

DEFAULT_SS_COIL_IDENTIFIER = 'C'

Secondary structure identifier mapping Stride B/b:Isolated bridge E:Strand/Extended conformation G:3-10 helix H:Alpha helix I:PI-helix T:Turn C:Coil (none of the above) SS_TURN_IDENTIFIERS = 'T' SS_DISORDER_IDENTIFIERS = 'C'

DSSP B:beta bridge E:strand/beta bulge G:310 helix H:α helix I:π helix T:turns S:high curvature (where the angle between i-2, i, and i+2 is at least 70°) " "(space):loop SS_DISORDER_IDENTIFIERS = ' ' SS_TURN_IDENTIFIERS = 'TS'

alpha_helix_15_atoms module-attribute

alpha_helix_15_atoms = Atoms([Atom(0, 1, 'N', ' ', 'ALA', 'A', 1, ' ', 27.128, 20.897, 37.943, 1.0, 0.0, 'N', ''), Atom(1, 2, 'CA', ' ', 'ALA', 'A', 1, ' ', 27.933, 21.94, 38.546, 1.0, 0.0, 'C', ''), Atom(2, 3, 'C', ' ', 'ALA', 'A', 1, ' ', 28.402, 22.92, 37.481, 1.0, 0.0, 'C', ''), Atom(3, 4, 'O', ' ', 'ALA', 'A', 1, ' ', 28.303, 24.132, 37.663, 1.0, 0.0, 'O', ''), Atom(4, 5, 'CB', ' ', 'ALA', 'A', 1, ' ', 29.162, 21.356, 39.234, 1.0, 0.0, 'C', ''), Atom(5, 6, 'N', ' ', 'ALA', 'A', 2, ' ', 28.914, 22.392, 36.367, 1.0, 0.0, 'N', ''), Atom(6, 7, 'CA', ' ', 'ALA', 'A', 2, ' ', 29.395, 23.219, 35.278, 1.0, 0.0, 'C', ''), Atom(7, 8, 'C', ' ', 'ALA', 'A', 2, ' ', 28.286, 24.142, 34.793, 1.0, 0.0, 'C', ''), Atom(8, 9, 'O', ' ', 'ALA', 'A', 2, ' ', 28.508, 25.337, 34.61, 1.0, 0.0, 'O', ''), Atom(9, 10, 'CB', ' ', 'ALA', 'A', 2, ' ', 29.857, 22.365, 34.102, 1.0, 0.0, 'C', ''), Atom(10, 11, 'N', ' ', 'ALA', 'A', 3, ' ', 27.092, 23.583, 34.584, 1.0, 0.0, 'N', ''), Atom(11, 12, 'CA', ' ', 'ALA', 'A', 3, ' ', 25.956, 24.355, 34.121, 1.0, 0.0, 'C', ''), Atom(12, 13, 'C', ' ', 'ALA', 'A', 3, ' ', 25.681, 25.505, 35.079, 1.0, 0.0, 'C', ''), Atom(13, 14, 'O', ' ', 'ALA', 'A', 3, ' ', 25.488, 26.639, 34.648, 1.0, 0.0, 'O', ''), Atom(14, 15, 'CB', ' ', 'ALA', 'A', 3, ' ', 24.703, 23.49, 34.038, 1.0, 0.0, 'C', ''), Atom(15, 16, 'N', ' ', 'ALA', 'A', 4, ' ', 25.662, 25.208, 36.38, 1.0, 0.0, 'N', ''), Atom(16, 17, 'CA', ' ', 'ALA', 'A', 4, ' ', 25.411, 26.214, 37.393, 1.0, 0.0, 'C', ''), Atom(17, 18, 'C', ' ', 'ALA', 'A', 4, ' ', 26.424, 27.344, 37.27, 1.0, 0.0, 'C', ''), Atom(18, 19, 'O', ' ', 'ALA', 'A', 4, ' ', 26.055, 28.516, 37.29, 1.0, 0.0, 'O', ''), Atom(19, 20, 'CB', ' ', 'ALA', 'A', 4, ' ', 25.519, 25.624, 38.794, 1.0, 0.0, 'C', ''), Atom(20, 21, 'N', ' ', 'ALA', 'A', 5, ' ', 27.704, 26.987, 37.142, 1.0, 0.0, 'N', ''), Atom(21, 22, 'CA', ' ', 'ALA', 'A', 5, ' ', 28.764, 27.968, 37.016, 1.0, 0.0, 'C', ''), Atom(22, 23, 'C', ' ', 'ALA', 'A', 5, ' ', 28.497, 28.876, 35.825, 1.0, 0.0, 'C', ''), Atom(23, 24, 'O', ' ', 'ALA', 'A', 5, ' ', 28.602, 30.096, 35.937, 1.0, 0.0, 'O', ''), Atom(24, 25, 'CB', ' ', 'ALA', 'A', 5, ' ', 30.115, 27.292, 36.812, 1.0, 0.0, 'C', ''), Atom(25, 26, 'N', ' ', 'ALA', 'A', 6, ' ', 28.151, 28.278, 34.682, 1.0, 0.0, 'N', ''), Atom(26, 27, 'CA', ' ', 'ALA', 'A', 6, ' ', 27.871, 29.032, 33.478, 1.0, 0.0, 'C', ''), Atom(27, 28, 'C', ' ', 'ALA', 'A', 6, ' ', 26.759, 30.04, 33.737, 1.0, 0.0, 'C', ''), Atom(28, 29, 'O', ' ', 'ALA', 'A', 6, ' ', 26.876, 31.205, 33.367, 1.0, 0.0, 'O', ''), Atom(29, 30, 'CB', ' ', 'ALA', 'A', 6, ' ', 27.429, 28.113, 32.344, 1.0, 0.0, 'C', ''), Atom(30, 31, 'N', ' ', 'ALA', 'A', 7, ' ', 25.678, 29.586, 34.376, 1.0, 0.0, 'N', ''), Atom(31, 32, 'CA', ' ', 'ALA', 'A', 7, ' ', 24.552, 30.444, 34.682, 1.0, 0.0, 'C', ''), Atom(32, 33, 'C', ' ', 'ALA', 'A', 7, ' ', 25.013, 31.637, 35.507, 1.0, 0.0, 'C', ''), Atom(33, 34, 'O', ' ', 'ALA', 'A', 7, ' ', 24.652, 32.773, 35.212, 1.0, 0.0, 'O', ''), Atom(34, 35, 'CB', ' ', 'ALA', 'A', 7, ' ', 23.489, 29.693, 35.478, 1.0, 0.0, 'C', ''), Atom(35, 36, 'N', ' ', 'ALA', 'A', 8, ' ', 25.814, 31.374, 36.543, 1.0, 0.0, 'N', ''), Atom(36, 37, 'CA', ' ', 'ALA', 'A', 8, ' ', 26.321, 32.423, 37.405, 1.0, 0.0, 'C', ''), Atom(37, 38, 'C', ' ', 'ALA', 'A', 8, ' ', 27.081, 33.454, 36.583, 1.0, 0.0, 'C', ''), Atom(38, 39, 'O', ' ', 'ALA', 'A', 8, ' ', 26.874, 34.654, 36.745, 1.0, 0.0, 'O', ''), Atom(39, 40, 'CB', ' ', 'ALA', 'A', 8, ' ', 27.193, 31.773, 38.487, 1.0, 0.0, 'C', ''), Atom(40, 41, 'N', ' ', 'ALA', 'A', 9, ' ', 27.963, 32.98, 35.7, 1.0, 0.0, 'N', ''), Atom(41, 42, 'CA', ' ', 'ALA', 'A', 9, ' ', 28.75, 33.859, 34.858, 1.0, 0.0, 'C', ''), Atom(42, 43, 'C', ' ', 'ALA', 'A', 9, ' ', 27.834, 34.759, 34.042, 1.0, 0.0, 'C', ''), Atom(43, 44, 'O', ' ', 'ALA', 'A', 9, ' ', 28.052, 35.967, 33.969, 1.0, 0.0, 'O', ''), Atom(44, 45, 'CB', ' ', 'ALA', 'A', 9, ' ', 29.621, 33.061, 33.894, 1.0, 0.0, 'C', ''), Atom(45, 46, 'N', ' ', 'ALA', 'A', 10, ' ', 26.807, 34.168, 33.427, 1.0, 0.0, 'N', ''), Atom(46, 47, 'CA', ' ', 'ALA', 'A', 10, ' ', 25.864, 34.915, 32.62, 1.0, 0.0, 'C', ''), Atom(47, 48, 'C', ' ', 'ALA', 'A', 10, ' ', 25.23, 36.024, 33.448, 1.0, 0.0, 'C', ''), Atom(48, 49, 'O', ' ', 'ALA', 'A', 10, ' ', 25.146, 37.165, 33.001, 1.0, 0.0, 'O', ''), Atom(49, 50, 'CB', ' ', 'ALA', 'A', 10, ' ', 24.752, 34.012, 32.097, 1.0, 0.0, 'C', ''), Atom(50, 51, 'N', ' ', 'ALA', 'A', 11, ' ', 24.783, 35.683, 34.66, 1.0, 0.0, 'N', ''), Atom(51, 52, 'CA', ' ', 'ALA', 'A', 11, ' ', 24.16, 36.646, 35.544, 1.0, 0.0, 'C', ''), Atom(52, 53, 'C', ' ', 'ALA', 'A', 11, ' ', 25.104, 37.812, 35.797, 1.0, 0.0, 'C', ''), Atom(53, 54, 'O', ' ', 'ALA', 'A', 11, ' ', 24.699, 38.97, 35.714, 1.0, 0.0, 'O', ''), Atom(54, 55, 'CB', ' ', 'ALA', 'A', 11, ' ', 23.81, 36.012, 36.887, 1.0, 0.0, 'C', ''), Atom(55, 56, 'N', ' ', 'ALA', 'A', 12, ' ', 26.365, 37.503, 36.107, 1.0, 0.0, 'N', ''), Atom(56, 57, 'CA', ' ', 'ALA', 'A', 12, ' ', 27.361, 38.522, 36.37, 1.0, 0.0, 'C', ''), Atom(57, 58, 'C', ' ', 'ALA', 'A', 12, ' ', 27.477, 39.461, 35.177, 1.0, 0.0, 'C', ''), Atom(58, 59, 'O', ' ', 'ALA', 'A', 12, ' ', 27.485, 40.679, 35.342, 1.0, 0.0, 'O', ''), Atom(59, 60, 'CB', ' ', 'ALA', 'A', 12, ' ', 28.73, 37.9, 36.625, 1.0, 0.0, 'C', ''), Atom(60, 61, 'N', ' ', 'ALA', 'A', 13, ' ', 27.566, 38.89, 33.974, 1.0, 0.0, 'N', ''), Atom(61, 62, 'CA', ' ', 'ALA', 'A', 13, ' ', 27.68, 39.674, 32.761, 1.0, 0.0, 'C', ''), Atom(62, 63, 'C', ' ', 'ALA', 'A', 13, ' ', 26.504, 40.634, 32.645, 1.0, 0.0, 'C', ''), Atom(63, 64, 'O', ' ', 'ALA', 'A', 13, ' ', 26.69, 41.815, 32.36, 1.0, 0.0, 'O', ''), Atom(64, 65, 'CB', ' ', 'ALA', 'A', 13, ' ', 27.69, 38.779, 31.527, 1.0, 0.0, 'C', ''), Atom(65, 66, 'N', ' ', 'ALA', 'A', 14, ' ', 25.291, 40.121, 32.868, 1.0, 0.0, 'N', ''), Atom(66, 67, 'CA', ' ', 'ALA', 'A', 14, ' ', 24.093, 40.932, 32.789, 1.0, 0.0, 'C', ''), Atom(67, 68, 'C', ' ', 'ALA', 'A', 14, ' ', 24.193, 42.112, 33.745, 1.0, 0.0, 'C', ''), Atom(68, 69, 'O', ' ', 'ALA', 'A', 14, ' ', 23.905, 43.245, 33.367, 1.0, 0.0, 'O', ''), Atom(69, 70, 'CB', ' ', 'ALA', 'A', 14, ' ', 22.856, 40.12, 33.158, 1.0, 0.0, 'C', ''), Atom(70, 71, 'N', ' ', 'ALA', 'A', 15, ' ', 24.604, 41.841, 34.986, 1.0, 0.0, 'N', ''), Atom(71, 72, 'CA', ' ', 'ALA', 'A', 15, ' ', 24.742, 42.878, 35.989, 1.0, 0.0, 'C', ''), Atom(72, 73, 'C', ' ', 'ALA', 'A', 15, ' ', 25.691, 43.96, 35.497, 1.0, 0.0, 'C', ''), Atom(73, 74, 'O', ' ', 'ALA', 'A', 15, ' ', 25.39, 45.147, 35.602, 1.0, 0.0, 'O', ''), Atom(74, 75, 'CB', ' ', 'ALA', 'A', 15, ' ', 24.418, 41.969, 34.808, 1.0, 0.0, 'C', '')])

Caution. After the first time this helix is created as a Structure, the alpha_helix_15_atoms Atom instances will have their .coords set to the alpha_helix_15 'parent' Structure instance. Transformation of this Structure causes the starting coordinates in each Atom instance in alpha_helix_15_atoms to be transformed as well. Making new structures from this Atoms container is sufficient to detach them, but the coordinates are moved from program start after usage the first time. This behavior isn't ideal, but a consequence of construction of Atom instances from the singular attribute basis with the intention to be reused

ArrayIndexer module-attribute

ArrayIndexer = Type[Union[Sequence[int], Sequence[bool], slice, None]]

Where integers, slices :, ellipsis ..., None and integer or boolean arrays are valid indices

Log

Log(log: Logger | None = logging.getLogger('null'))

Responsible for StructureBase logging operations

Parameters:

  • log (Logger | None, default: getLogger('null') ) –

    The logging.Logger to handle StructureBase logging. If None is passed a Logger with NullHandler is used

Source code in symdesign/structure/base.py
762
763
764
765
766
767
768
def __init__(self, log: Logger | None = logging.getLogger('null')):
    """Construct the instance

    Args:
        log: The logging.Logger to handle StructureBase logging. If None is passed a Logger with NullHandler is used
    """
    self.log = log

SymmetryBase

SymmetryBase(rotation_matrices: ndarray = None, translation_matrices: ndarray = None, **kwargs)

Bases: ABC

Adds functionality for symmetric manipulation of Structure instances

Collects known keyword arguments for all derived classes to protect object. Should always be the last class in the method resolution order of derived classes.

Source code in symdesign/structure/base.py
793
794
795
796
797
798
799
800
801
def __init__(self, rotation_matrices: np.ndarray = None, translation_matrices: np.ndarray = None, **kwargs):
    self._symmetry = self._symmetric_dependents = None
    try:
        super().__init__(**kwargs)  # SymmetryBase
    except TypeError:
        raise TypeError(
            f"The argument(s) passed to the {self.__class__.__name__} instance weren't recognized and aren't "
            f"accepted by the object class: {', '.join(kwargs.keys())}\n\nIt's likely that your class MRO is "
            "insufficient for your passed arguments or you have passed invalid arguments")

symmetry property writable

symmetry: str | None

The symmetry of the Structure described by its Schönflies notation

symmetric_dependents property writable

symmetric_dependents: list[StructureBase] | list

Access the symmetrically dependent Structure instances

reset_symmetry_state

reset_symmetry_state() -> None

Remove any state variable associated with the instance

Source code in symdesign/structure/base.py
825
826
827
828
829
830
831
832
def reset_symmetry_state(self) -> None:
    """Remove any state variable associated with the instance"""
    # self.log.debug(f"Removing symmetric attributes from {repr(self)}")
    for attribute in self.symmetry_state_attributes:
        try:
            delattr(self, attribute)
        except AttributeError:
            continue

is_symmetric

is_symmetric() -> bool

Query whether the Structure is symmetric. Returns True if self.symmetry is not None

Source code in symdesign/structure/base.py
834
835
836
def is_symmetric(self) -> bool:
    """Query whether the Structure is symmetric. Returns True if self.symmetry is not None"""
    return self._symmetry is not None

has_symmetric_dependents

has_symmetric_dependents() -> bool

Evaluates to True if the Structure has symmetrically dependent children

Source code in symdesign/structure/base.py
838
839
840
def has_symmetric_dependents(self) -> bool:
    """Evaluates to True if the Structure has symmetrically dependent children"""
    return True if self._symmetric_dependents else False

StructureMetadata

StructureMetadata(biological_assembly: str | int = None, cryst_record: str = None, entity_info: dict[str, dict[dict | list | str]] = None, file_path: AnyStr = None, reference_sequence: str | dict[str, str] = None, resolution: float = None, **kwargs)

Contains all metadata available from structure file parsing

Parameters:

  • biological_assembly (str | int, default: None ) –

    The integer of the biological assembly (as indicated by PDB AssemblyID format)

  • cryst_record (str, default: None ) –

    The string specifying how the molecule is situated in a lattice

  • entity_info (dict[str, dict[dict | list | str]], default: None ) –

    A mapping of the metadata to their distinct molecular identifiers

  • file_path (AnyStr, default: None ) –

    The location on disk where the file was accessed

  • reference_sequence (str | dict[str, str], default: None ) –

    The reference sequence (according to expression sequence or reference database)

  • resolution (float, default: None ) –

    The level of detail available from an experimental dataset contributing to the sharpness with which structural data can contribute towards building a model

Source code in symdesign/structure/base.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
def __init__(self, biological_assembly: str | int = None, cryst_record: str = None,
             entity_info: dict[str, dict[dict | list | str]] = None, file_path: AnyStr = None,
             reference_sequence: str | dict[str, str] = None, resolution: float = None, **kwargs):
    """Construct the instance

    Args:
        biological_assembly: The integer of the biological assembly (as indicated by PDB AssemblyID format)
        cryst_record: The string specifying how the molecule is situated in a lattice
        entity_info: A mapping of the metadata to their distinct molecular identifiers
        file_path: The location on disk where the file was accessed
        reference_sequence: The reference sequence (according to expression sequence or reference database)
        resolution: The level of detail available from an experimental dataset contributing to the sharpness with
            which structural data can contribute towards building a model
    """
    if biological_assembly is None:
        self.biological_assembly = biological_assembly
    else:
        self.biological_assembly = str(biological_assembly)
    self.cryst_record = cryst_record
    self.entity_info = entity_info
    self.file_path = file_path
    self.reference_sequence = reference_sequence
    self.resolution = resolution

CoordinateOpsMixin

Bases: ABC

coords abstractmethod property writable

coords

distance_from_reference

distance_from_reference(reference: ndarray = utils.symmetry.origin, measure: str = 'mean', **kwargs) -> float

From a Structure, find the furthest coordinate from the origin (default) or from a reference.

Parameters:

  • reference (ndarray, default: origin ) –

    The reference where the point should be measured from. Default is origin

  • measure (str, default: 'mean' ) –

    The measurement to take with respect to the reference. Could be 'mean', 'min', 'max', or any numpy function to describe computed distance scalars

Returns:

  • float

    The distance from the reference point to the furthest point

Source code in symdesign/structure/base.py
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
def distance_from_reference(
    self, reference: np.ndarray = utils.symmetry.origin, measure: str = 'mean', **kwargs
) -> float:
    """From a Structure, find the furthest coordinate from the origin (default) or from a reference.

    Args:
        reference: The reference where the point should be measured from. Default is origin
        measure: The measurement to take with respect to the reference. Could be 'mean', 'min', 'max', or any
            numpy function to describe computed distance scalars

    Returns:
        The distance from the reference point to the furthest point
    """
    if reference is None:
        reference = utils.symmetry.origin

    return getattr(np, measure)(np.linalg.norm(self.coords - reference, axis=1))

translate

translate(translation: list[float] | ndarray, **kwargs) -> None

Perform a translation to the Structure ensuring only the Structure container of interest is translated ensuring the underlying coords are not modified

Parameters:

  • translation (list[float] | ndarray) –

    The first translation to apply, expected array shape (3,)

Source code in symdesign/structure/base.py
936
937
938
939
940
941
942
943
944
945
def translate(self, translation: list[float] | np.ndarray, **kwargs) -> None:
    """Perform a translation to the Structure ensuring only the Structure container of interest is translated
    ensuring the underlying coords are not modified

    Args:
        translation: The first translation to apply, expected array shape (3,)
    """
    self._transforming = True
    self.coords += translation
    self._transforming = False

rotate

rotate(rotation: list[list[float]] | ndarray, **kwargs) -> None

Perform a rotation to the Structure ensuring only the Structure container of interest is rotated ensuring the underlying coords are not modified

Parameters:

  • rotation (list[list[float]] | ndarray) –

    The first rotation to apply, expected array shape (3, 3)

Source code in symdesign/structure/base.py
947
948
949
950
951
952
953
954
955
956
957
def rotate(self, rotation: list[list[float]] | np.ndarray, **kwargs) -> None:
    """Perform a rotation to the Structure ensuring only the Structure container of interest is rotated ensuring the
    underlying coords are not modified

    Args:
        rotation: The first rotation to apply, expected array shape (3, 3)
    """
    self._transforming = True
    self.coords = np.matmul(self.coords, np.transpose(rotation))  # Allows a list to be passed
    # self.coords = np.matmul(self.coords, rotation.swapaxes(-2, -1))  # Essentially a transpose
    self._transforming = False

transform

transform(rotation: list[list[float]] | ndarray = None, translation: list[float] | ndarray = None, rotation2: list[list[float]] | ndarray = None, translation2: list[float] | ndarray = None, **kwargs) -> None

Perform a specific transformation to the Structure ensuring only the Structure container of interest is transformed ensuring the underlying coords are not modified

Transformation proceeds by matrix multiplication and vector addition with the order of operations as: rotation, translation, rotation2, translation2

Parameters:

  • rotation (list[list[float]] | ndarray, default: None ) –

    The first rotation to apply, expected array shape (3, 3)

  • translation (list[float] | ndarray, default: None ) –

    The first translation to apply, expected array shape (3,)

  • rotation2 (list[list[float]] | ndarray, default: None ) –

    The second rotation to apply, expected array shape (3, 3)

  • translation2 (list[float] | ndarray, default: None ) –

    The second translation to apply, expected array shape (3,)

Source code in symdesign/structure/base.py
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def transform(
    self, rotation: list[list[float]] | np.ndarray = None, translation: list[float] | np.ndarray = None,
    rotation2: list[list[float]] | np.ndarray = None, translation2: list[float] | np.ndarray = None, **kwargs
) -> None:
    """Perform a specific transformation to the Structure ensuring only the Structure container of interest is
    transformed ensuring the underlying coords are not modified

    Transformation proceeds by matrix multiplication and vector addition with the order of operations as:
    rotation, translation, rotation2, translation2

    Args:
        rotation: The first rotation to apply, expected array shape (3, 3)
        translation: The first translation to apply, expected array shape (3,)
        rotation2: The second rotation to apply, expected array shape (3, 3)
        translation2: The second translation to apply, expected array shape (3,)
    """
    if rotation is not None:  # Required for np.ndarray or None checks
        new_coords = np.matmul(self.coords, np.transpose(rotation))  # Allows list to be passed...
        # new_coords = np.matmul(self.coords, rotation.swapaxes(-2, -1))  # Essentially a transpose
    else:
        new_coords = self.coords  # No need to copy as this is a view

    if translation is not None:  # Required for np.ndarray or None checks
        new_coords += translation

    if rotation2 is not None:  # Required for np.ndarray or None checks
        np.matmul(new_coords, np.transpose(rotation2), out=new_coords)  # Allows list to be passed...
        # np.matmul(new_coords, rotation2.swapaxes(-2, -1), out=new_coords)  # Essentially a transpose

    if translation2 is not None:  # Required for np.ndarray or None checks
        new_coords += translation2

    self._transforming = True
    self.coords = new_coords
    self._transforming = False

copy abstractmethod

copy()
Source code in symdesign/structure/base.py
995
996
997
@abc.abstractmethod
def copy(self):
    """"""

get_transformed_copy

get_transformed_copy(rotation: list[list[float]] | ndarray = None, translation: list[float] | ndarray = None, rotation2: list[list[float]] | ndarray = None, translation2: list[float] | ndarray = None) -> StructureBase

Make a semi-deep copy of the Structure object with the coordinates transformed in cartesian space

Transformation proceeds by matrix multiplication and vector addition with the order of operations as: rotation, translation, rotation2, translation2

Parameters:

  • rotation (list[list[float]] | ndarray, default: None ) –

    The first rotation to apply, expected array shape (3, 3)

  • translation (list[float] | ndarray, default: None ) –

    The first translation to apply, expected array shape (3,)

  • rotation2 (list[list[float]] | ndarray, default: None ) –

    The second rotation to apply, expected array shape (3, 3)

  • translation2 (list[float] | ndarray, default: None ) –

    The second translation to apply, expected array shape (3,)

Returns:

Source code in symdesign/structure/base.py
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
def get_transformed_copy(
    self, rotation: list[list[float]] | np.ndarray = None, translation: list[float] | np.ndarray = None,
    rotation2: list[list[float]] | np.ndarray = None, translation2: list[float] | np.ndarray = None
) -> StructureBase:  # Todo -> Self in python 3.11
    """Make a semi-deep copy of the Structure object with the coordinates transformed in cartesian space

    Transformation proceeds by matrix multiplication and vector addition with the order of operations as:
    rotation, translation, rotation2, translation2

    Args:
        rotation: The first rotation to apply, expected array shape (3, 3)
        translation: The first translation to apply, expected array shape (3,)
        rotation2: The second rotation to apply, expected array shape (3, 3)
        translation2: The second translation to apply, expected array shape (3,)

    Returns:
        A transformed copy of the original object
    """
    if rotation is not None:  # Required for np.ndarray or None checks
        new_coords = np.matmul(self.coords, np.transpose(rotation))  # Allows list to be passed...
        # new_coords = np.matmul(self.coords, rotation.swapaxes(-2, -1))  # Essentially a transpose
    else:
        new_coords = self.coords  # No need to copy as this is a view

    if translation is not None:  # Required for np.ndarray or None checks
        new_coords += translation

    if rotation2 is not None:  # Required for np.ndarray or None checks
        np.matmul(new_coords, np.transpose(rotation2), out=new_coords)  # Allows list to be passed...
        # np.matmul(new_coords, rotation2.swapaxes(-2, -1), out=new_coords)  # Essentially a transpose

    if translation2 is not None:  # Required for np.ndarray or None checks
        new_coords += translation2

    new_structure = self.copy()
    new_structure._transforming = True
    new_structure.coords = new_coords
    new_structure._transforming = False

    return new_structure

StructureBase

StructureBase(parent: StructureBase = None, log: Log | Logger | bool = True, coords: ndarray | Coordinates | list[list[float]] = None, name: str = None, file_path: AnyStr = None, biological_assembly: str | int = None, cryst_record: str = None, resolution: float = None, entity_info: dict[str, dict[dict | list | str]] = None, reference_sequence: str | dict[str, str] = None, **kwargs)

Bases: SymmetryBase, CoordinateOpsMixin, ABC

Manipulates Coordinates and Log instances as well as the .atom_indices.

Additionally. sorts through parent Structure and dependent Structure hierarchies during Structure subclass creation.

Parameters:

  • parent (StructureBase, default: None ) –

    If another Structure object created this Structure instance, pass the 'parent' instance. Will take ownership over Structure containers (coords, atoms, residues) for dependent Structures

  • log (Log | Logger | bool, default: True ) –

    The Log or Logger instance, or the name for the logger to handle parent Structure logging. None or False prevents logging while any True assignment enables it

  • coords (ndarray | Coordinates | list[list[float]], default: None ) –

    When setting up a parent Structure instance, the coordinates of that Structure

  • name (str, default: None ) –

    The identifier for the Structure instance

Source code in symdesign/structure/base.py
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def __init__(self, parent: StructureBase = None, log: Log | Logger | bool = True,
             coords: np.ndarray | Coordinates | list[list[float]] = None, name: str = None,
             # metadata: StructureMetadata = None,
             file_path: AnyStr = None, biological_assembly: str | int = None,
             cryst_record: str = None, resolution: float = None,
             entity_info: dict[str, dict[dict | list | str]] = None,
             reference_sequence: str | dict[str, str] = None,
             # entity_info=None,
             **kwargs):
    # These shouldn't be passed as they should be stripped by prior constructors...
    # entity_names=None, rotation_matrices=None, translation_matrices=None,
    # metadata=None, pose_format=None, query_by_sequence=True, rename_chains=None
    """Construct the instance

    Args:
        parent: If another Structure object created this Structure instance, pass the 'parent' instance. Will take
            ownership over Structure containers (coords, atoms, residues) for dependent Structures
        log: The Log or Logger instance, or the name for the logger to handle parent Structure logging.
            None or False prevents logging while any True assignment enables it
        coords: When setting up a parent Structure instance, the coordinates of that Structure
        name: The identifier for the Structure instance
    """
    self.name = name if name not in [None, False] else f'Unnamed_{self.__class__.__name__}'
    if parent is not None:  # Initialize StructureBase from parent
        self._parent = parent
    else:  # This is the parent
        self._parent_ = None
        self.metadata = StructureMetadata(
            biological_assembly=biological_assembly, cryst_record=cryst_record, entity_info=entity_info,
            file_path=file_path, reference_sequence=reference_sequence, resolution=resolution
        )
        # Initialize Log
        if log:
            if isinstance(log, Log):  # Initialized Log
                self._log = log
            elif isinstance(log, Logger):  # logging.Logger object
                self._log = Log(log)
            elif isinstance(log, str):
                self._log = Log(utils.start_log(name=f'{__name__}.{self.name}', level=log))
            else:  # log is True or some other type:  # Use the module logger
                self._log = Log(logger)
        else:  # When explicitly passed as None or False, uses the null logger
            self._log = null_struct_log  # Log()

        # Initialize Coordinates
        if coords is None:  # Check this first
            # Most init occurs from Atom instances that are their own parent until another StructureBase adopts them
            self._coords = Coordinates()
        elif isinstance(coords, Coordinates):
            self._coords = coords
        else:  # Create a Coordinates instance. This assumes the dimensions are correct. Coordinates() handles if not
            self._coords = Coordinates(coords)

    # try:
    super().__init__(**kwargs)  # StructureBase

parent property

parent: StructureBase | None

Return the instance's 'parent' StructureBase which is responsible for manipulation of Structure containers

log property writable

log: Logger

The StructureBase Logger

coords property writable

coords: ndarray

The coordinates for the Atoms in the StructureBase object

is_dependent

is_dependent() -> bool

Is this instance a dependent on a parent StructureBase?

Source code in symdesign/structure/base.py
1140
1141
1142
def is_dependent(self) -> bool:
    """Is this instance a dependent on a parent StructureBase?"""
    return self._parent_ is not None

is_parent

is_parent() -> bool

Is this instance a parent?

Source code in symdesign/structure/base.py
1144
1145
1146
def is_parent(self) -> bool:
    """Is this instance a parent?"""
    return self._parent_ is None

make_parent

make_parent()

Remove this instance from its parent, making it a parent in the process

Source code in symdesign/structure/base.py
1196
1197
1198
1199
1200
1201
def make_parent(self):
    """Remove this instance from its parent, making it a parent in the process"""
    # Set parent explicitly as None
    self.__setattr__(_parent_variable, None)
    # Create a new, Coords instance detached from the parent
    self._coords = Coordinates(self.coords)

reset_state

reset_state()

Removes attributes that are valid for the current state. Additionally, resets the symmetry state if symmetric

This is useful for transfer of ownership, or changes in the state that should be overwritten

Source code in symdesign/structure/base.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
def reset_state(self):
    """Removes attributes that are valid for the current state. Additionally, resets the symmetry state if symmetric

    This is useful for transfer of ownership, or changes in the state that should be overwritten
    """
    # self.log.debug(f'Resetting {repr(self)} state_attributes')
    for attr in self.state_attributes:
        try:
            self.__delattr__(attr)
        except AttributeError:
            continue

    self.reset_symmetry_state()

Atom

Atom(index: int = None, number: int = None, atom_type: str = None, alt_location: str = ' ', residue_type: str = None, chain_id: str = None, residue_number: int = None, code_for_insertion: str = ' ', x: float = None, y: float = None, z: float = None, occupancy: float = None, b_factor: float = None, element: str = None, charge: str = None, coords: list[float] = None, **kwargs)

Bases: CoordinateOpsMixin

Contains Atom metadata and a single coordinate position

Parameters:

  • index (int, default: None ) –

    The zero-indexed number to describe this Atom instance's position in a StructureBaseContainer

  • number (int, default: None ) –

    The integer number describing this Atom instances position in comparison to others instances

  • atom_type (str, default: None ) –

    The characters describing the classification of atom via membership to a molecule

  • alt_location (str, default: ' ' ) –

    Whether the observation of the Atom has alternative evidences

  • residue_type (str, default: None ) –

    The characters describing the molecular unit to which this Atom belongs

  • chain_id (str, default: None ) –

    The identifier which signifies this Atom instances membership to a larger polymer

  • residue_number (int, default: None ) –

    The integer of the polymer that this Atom belongs too

  • code_for_insertion (str, default: ' ' ) –

    Whether the Atom is included in a residue which is inserted according to a common numbering scheme

  • x (float, default: None ) –

    The x axis value of the instances coordinate position, i.e., it's x coordinate

  • y (float, default: None ) –

    The y axis value of the instances coordinate position, i.e., it's y coordinate

  • z (float, default: None ) –

    The z axis value of the instances coordinate position, i.e., it's z coordinate

  • occupancy (float, default: None ) –

    The fraction of the time this Atom is observed in the experiment

  • b_factor (float, default: None ) –

    The thermal fluctuation for the Atom OR a value for which structural representation should account

  • element (str, default: None ) –

    The atomic symbol for the Atom

  • charge (str, default: None ) –

    The numeric value for the electronic charge of the Atom

  • coords (list[float], default: None ) –

    The set of values of the x, y, and z coordinate position

  • **kwargs
Source code in symdesign/structure/base.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
def __init__(self, index: int = None, number: int = None, atom_type: str = None, alt_location: str = ' ',
             residue_type: str = None, chain_id: str = None, residue_number: int = None,
             code_for_insertion: str = ' ', x: float = None, y: float = None, z: float = None,
             occupancy: float = None, b_factor: float = None, element: str = None, charge: str = None,
             coords: list[float] = None, **kwargs):
    """Construct the instance

    Args:
        index: The zero-indexed number to describe this Atom instance's position in a StructureBaseContainer
        number: The integer number describing this Atom instances position in comparison to others instances
        atom_type: The characters describing the classification of atom via membership to a molecule
        alt_location: Whether the observation of the Atom has alternative evidences
        residue_type: The characters describing the molecular unit to which this Atom belongs
        chain_id: The identifier which signifies this Atom instances membership to a larger polymer
        residue_number: The integer of the polymer that this Atom belongs too
        code_for_insertion: Whether the Atom is included in a residue which is inserted according to a common
            numbering scheme
        x: The x axis value of the instances coordinate position, i.e., it's x coordinate
        y: The y axis value of the instances coordinate position, i.e., it's y coordinate
        z: The z axis value of the instances coordinate position, i.e., it's z coordinate
        occupancy: The fraction of the time this Atom is observed in the experiment
        b_factor: The thermal fluctuation for the Atom OR a value for which structural representation should account
        element: The atomic symbol for the Atom
        charge: The numeric value for the electronic charge of the Atom
        coords: The set of values of the x, y, and z coordinate position
        **kwargs:
    """
    # super().__init__(**kwargs)  # Atom
    self.index = index
    # self._atom_indices = [index]
    self.number = number
    self._type = atom_type
    # Comply with special .pdb formatting syntax by padding type with a space if len(atom_type) == 4
    self._type_str = f'{"" if atom_type[3:] else " "}{atom_type:<3s}'
    self.alt_location = alt_location
    self.residue_type = residue_type
    self.chain_id = chain_id
    self.residue_number = residue_number
    self.code_for_insertion = code_for_insertion
    if coords is not None:
        self._coords_ = coords
    elif x is not None and y is not None and z is not None:
        self._coords_ = [x, y, z]
    else:
        self._coords_ = []
    self.occupancy = occupancy
    self.b_factor = b_factor
    self.element = element
    self.charge = charge
    self.sasa = None

type property

type: str

This can't currently be set

atom_indices property

atom_indices: list[int]

The index of the Atom in the Atoms/Coords container

coords property writable

coords: ndarray

The coordinates for the Atom. Array is 1 dimensional in contrast to other .coords properties

center_of_mass property

center_of_mass: ndarray

The center of mass (the Atom coordinates). Provided for compatibility with StructureBase API

radius property

radius: float

The width of the Atom

x property writable

x: float

Access the value for the x coordinate

y property writable

y: float

Access the value for the y coordinate

z property writable

z: float

Access the value for the z coordinate

without_coordinates classmethod

without_coordinates(idx, number, atom_type, alt_location, residue_type, chain_id, residue_number, code_for_insertion, occupancy, b_factor, element, charge)

Initialize Atom record data without coordinates. Performs all type casting

Source code in symdesign/structure/base.py
1292
1293
1294
1295
1296
1297
1298
1299
@classmethod
def without_coordinates(cls, idx, number, atom_type, alt_location, residue_type, chain_id, residue_number,
                        code_for_insertion, occupancy, b_factor, element, charge):
    """Initialize Atom record data without coordinates. Performs all type casting"""
    return cls(index=idx, number=int(number), atom_type=atom_type, alt_location=alt_location,
               residue_type=residue_type, chain_id=chain_id, residue_number=int(residue_number),
               code_for_insertion=code_for_insertion, occupancy=float(occupancy), b_factor=float(b_factor),
               element=element, charge=charge, coords=[])  # Use a list for speed

is_dependent

is_dependent() -> bool

Is this instance a dependent on a parent StructureBase?

Source code in symdesign/structure/base.py
1377
1378
1379
def is_dependent(self) -> bool:
    """Is this instance a dependent on a parent StructureBase?"""
    return True

is_parent

is_parent() -> bool

Is this instance a parent?

Source code in symdesign/structure/base.py
1382
1383
1384
def is_parent(self) -> bool:
    """Is this instance a parent?"""
    return False

make_parent

make_parent()

Remove this instance from its parent, making it a parent in the process

Source code in symdesign/structure/base.py
1408
1409
1410
1411
1412
1413
1414
def make_parent(self):
    """Remove this instance from its parent, making it a parent in the process"""
    # super().make_parent()  # When subclassing StructureBase
    # Create a new, Coords instance detached from the parent
    self._coords = Coordinates(self.coords)
    self.index = 0
    self.reset_state()

reset_state

reset_state()

Remove attributes that are valid for the current state

This is useful for transfer of ownership, or changes in the state that should be overwritten

Source code in symdesign/structure/base.py
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
def reset_state(self):
    """Remove attributes that are valid for the current state

    This is useful for transfer of ownership, or changes in the state that should be overwritten
    """
    for attr in self.state_attributes:
        try:
            self.__delattr__(attr)
        except AttributeError:
            continue

is_backbone_and_cb

is_backbone_and_cb() -> bool

Is the Atom is a backbone or CB Atom? Includes N, CA, C, O, and CB

Source code in symdesign/structure/base.py
1525
1526
1527
def is_backbone_and_cb(self) -> bool:
    """Is the Atom is a backbone or CB Atom? Includes N, CA, C, O, and CB"""
    return self._type in protein_backbone_and_cb_atom_types

is_backbone

is_backbone() -> bool

Is the Atom is a backbone Atom? These include N, CA, C, and O

Source code in symdesign/structure/base.py
1529
1530
1531
def is_backbone(self) -> bool:
    """Is the Atom is a backbone Atom? These include N, CA, C, and O"""
    return self._type in protein_backbone_atom_types

is_cb

is_cb(gly_ca: bool = True) -> bool

Is the Atom a CB atom? Default returns True if Glycine and Atom is CA

Parameters:

  • gly_ca (bool, default: True ) –

    Whether to include Glycine CA in the boolean evaluation

Source code in symdesign/structure/base.py
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
def is_cb(self, gly_ca: bool = True) -> bool:
    """Is the Atom a CB atom? Default returns True if Glycine and Atom is CA

    Args:
        gly_ca: Whether to include Glycine CA in the boolean evaluation
    """
    if gly_ca:
        return self._type == 'CB' or (self.residue_type == 'GLY' and self._type == 'CA')
    else:
        #                                         When Rosetta assigns, it is this   v, but PDB assigns this v
        return self._type == 'CB' or (self.residue_type == 'GLY' and (self._type == '2HA' or self._type == 'HA3'))

is_ca

is_ca() -> bool

Is the Atom a CA atom?

Source code in symdesign/structure/base.py
1545
1546
1547
def is_ca(self) -> bool:
    """Is the Atom a CA atom?"""
    return self._type == 'CA'

is_heavy

is_heavy() -> bool

Is the Atom a heavy atom?

Source code in symdesign/structure/base.py
1549
1550
1551
def is_heavy(self) -> bool:
    """Is the Atom a heavy atom?"""
    return 'H' not in self._type

get_atom_record

get_atom_record() -> str

Provide the Atom as an Atom record string

Returns:

  • str

    The archived .pdb formatted ATOM records for the Structure

Source code in symdesign/structure/base.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
def get_atom_record(self) -> str:
    """Provide the Atom as an Atom record string

    Returns:
        The archived .pdb formatted ATOM records for the Structure
    """
    x, y, z = list(self.coords)
    # Add 1 to the self.index since this is 0 indexed
    return f'ATOM  {self.index + 1:5d} {self._type_str}{self.alt_location:1s}{self.residue_type:3s}' \
           f'{self.chain_id:>2s}{self.residue_number:4d}{self.code_for_insertion:1s}   ' \
           f'{x:8.3f}{y:8.3f}{z:8.3f}{self.occupancy:6.2f}{self.b_factor:6.2f}          ' \
           f'{self.element:>2s}{self.charge:2s}'

__str__

__str__() -> str

Represent Atom in PDB format

Source code in symdesign/structure/base.py
1570
1571
1572
1573
1574
1575
1576
1577
def __str__(self) -> str:
    """Represent Atom in PDB format"""
    # Use self.type_str to comply with the PDB format specifications because of the atom type field
    # ATOM     32  CG2 VAL A 132       9.902  -5.550   0.695  1.00 17.48           C  <-- PDB format
    # Checks if len(atom.type)=4 with slice v. If not insert a space
    return f'ATOM  {"{}"} {self._type_str}{self.alt_location:1s}{"{}"}{"{}"}{"{}"}' \
           f'{self.code_for_insertion:1s}   {"{}"}{self.occupancy:6.2f}{self.b_factor:6.2f}          ' \
           f'{self.element:>2s}{self.charge:2s}'

StructureBaseContainer

StructureBaseContainer(structs: Sequence[StructureBase] | ndarray = None)

Bases: Generic[_StructType]

Container for a StructureBase instances

Parameters:

  • structs (Sequence[StructureBase] | ndarray, default: None ) –

    The StructureBase instances to store. Should be a homogeneous Sequence

Source code in symdesign/structure/base.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
def __init__(self, structs: Sequence[StructureBase] | np.ndarray = None):
    """Construct the instance

    Args:
        structs: The StructureBase instances to store. Should be a homogeneous Sequence
    """
    if structs is None:
        structs = []
    elif not isinstance(structs, (np.ndarray, list)):
        structs = list(structs)
        # raise TypeError(
        #     f"Can't initialize {self.__class__.__name__} with {type(structs).__name__}. Type must be a "
        #     f'numpy.ndarray or list[{StructureBase.__name__}]')

    self.structs = np.array(structs, dtype=np.object_)

reindex abstractmethod property

reindex

are_dependents

are_dependents() -> bool

Check if any of the StructureBase instances are dependents of another StructureBase

Source code in symdesign/structure/base.py
1628
1629
1630
1631
1632
1633
def are_dependents(self) -> bool:
    """Check if any of the StructureBase instances are dependents of another StructureBase"""
    for struct in self:
        if struct.is_dependent():
            return True
    return False

append

append(new_structures: list[_StructType] | ndarray)

Append additional StructureBase instances to the StructureBaseContainer

Parameters:

  • new_structures (list[_StructType] | ndarray) –

    The Structure instances to append

Source code in symdesign/structure/base.py
1635
1636
1637
1638
1639
1640
1641
def append(self, new_structures: list[_StructType] | np.ndarray):
    """Append additional StructureBase instances to the StructureBaseContainer

    Args:
        new_structures: The Structure instances to append
    """
    self.structs = np.concatenate((self.structs, new_structures))

delete

delete(indices: Sequence[int])

Delete StructureBase instances from the StructureBaseContainer

Parameters:

  • indices (Sequence[int]) –

    The indices to delete

Source code in symdesign/structure/base.py
1643
1644
1645
1646
1647
1648
1649
def delete(self, indices: Sequence[int]):
    """Delete StructureBase instances from the StructureBaseContainer

    Args:
        indices: The indices to delete
    """
    self.structs = np.delete(self.structs, indices)

insert

insert(at: int, new_structures: list[_StructType] | ndarray)

Insert StructureBase instances into the StructureBaseContainer

Parameters:

  • at (int) –

    The index to perform the insert at

  • new_structures (list[_StructType] | ndarray) –

    The Structure instances to insert

Source code in symdesign/structure/base.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
def insert(self, at: int, new_structures: list[_StructType] | np.ndarray):
    """Insert StructureBase instances into the StructureBaseContainer

    Args:
        at: The index to perform the insert at
        new_structures: The Structure instances to insert
    """
    self.structs = np.concatenate((
        self.structs[:at],
        new_structures if isinstance(new_structures, Iterable) else [new_structures],
        self.structs[at:]
    ))

set

set(new_structures: list[_StructType] | ndarray)

Set the StructureBaseContainer with new StructureBase instances

Parameters:

  • new_structures (list[_StructType] | ndarray) –

    The new instances which should make up the container

Source code in symdesign/structure/base.py
1664
1665
1666
1667
1668
1669
1670
1671
def set(self, new_structures: list[_StructType] | np.ndarray):
    """Set the StructureBaseContainer with new StructureBase instances

    Args:
        new_structures: The new instances which should make up the container
    """
    self.structs = np.array(new_structures)
    self.reindex()

reset_state

reset_state()

Remove any attributes from the Structure instances that are part of the current state

This is useful for transfer of ownership, or changes in the state that need to be overwritten

Source code in symdesign/structure/base.py
1678
1679
1680
1681
1682
1683
1684
def reset_state(self):
    """Remove any attributes from the Structure instances that are part of the current state

    This is useful for transfer of ownership, or changes in the state that need to be overwritten
    """
    for struct in self:
        struct.reset_state()

set_attributes

set_attributes(**kwargs)

Set Structure attributes passed by keyword to their corresponding value

Source code in symdesign/structure/base.py
1686
1687
1688
1689
1690
def set_attributes(self, **kwargs):
    """Set Structure attributes passed by keyword to their corresponding value"""
    for struct in self:
        for key, value in kwargs.items():
            setattr(struct, key, value)

Atoms

Atoms(structs: Sequence[StructureBase] | ndarray = None)

Bases: StructureBaseContainer

Parameters:

  • structs (Sequence[StructureBase] | ndarray, default: None ) –

    The StructureBase instances to store. Should be a homogeneous Sequence

Source code in symdesign/structure/base.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
def __init__(self, structs: Sequence[StructureBase] | np.ndarray = None):
    """Construct the instance

    Args:
        structs: The StructureBase instances to store. Should be a homogeneous Sequence
    """
    if structs is None:
        structs = []
    elif not isinstance(structs, (np.ndarray, list)):
        structs = list(structs)
        # raise TypeError(
        #     f"Can't initialize {self.__class__.__name__} with {type(structs).__name__}. Type must be a "
        #     f'numpy.ndarray or list[{StructureBase.__name__}]')

    self.structs = np.array(structs, dtype=np.object_)

reindex

reindex(start_at: int = 0)

Set each Atom instance index according to incremental Atoms/Coords index

Parameters:

  • start_at (int, default: 0 ) –

    The index to start reindexing at. Must be [0, 'inf']

Source code in symdesign/structure/base.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
def reindex(self, start_at: int = 0):
    """Set each Atom instance index according to incremental Atoms/Coords index

    Args:
        start_at: The index to start reindexing at. Must be [0, 'inf']
    """
    if start_at == 0:
        _start_at = start_at
    else:
        _start_at = start_at - 1
        if start_at < 0:
            _start_at += len(self)
    try:
        prior_struct, *other_structs = self.structs[_start_at:]
    except ValueError:  # Not enough values to unpack as the index didn't slice anything
        raise IndexError(
            f'{self.reindex.__name__}: {start_at=} is outside of the {self.__class__.__name__} indices with '
            f'size {len(self)}')
    else:
        if start_at == 0:
            prior_struct.index = 0

        for idx, struct in enumerate(other_structs, prior_struct.index + 1):
            struct.index = idx

ContainsAtoms

ContainsAtoms(atoms: list[Atom] | Atoms = None, atom_indices: list[int] = None, **kwargs)

Bases: StructureBase, ABC

Parameters:

  • atoms (list[Atom] | Atoms, default: None ) –

    Atom instances to initialize the instance

Source code in symdesign/structure/base.py
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def __init__(self, atoms: list[Atom] | Atoms = None, atom_indices: list[int] = None, **kwargs):
    """Construct the instance

    Args:
        atoms: Atom instances to initialize the instance
    """
    super().__init__(**kwargs)  # ContainsAtoms
    if self.is_parent():
        if atoms is not None:
            self._assign_atoms(atoms)
        else:  # Create an empty container
            # try:
            #     self._atoms
            # except AttributeError:
            self._atoms = Atoms()
    elif atom_indices is not None:
        try:
            atom_indices[0]
        except (TypeError, IndexError):
            raise ValueError(
                f"The {self.__class__.__name__} wasn't passed 'atom_indices' which are required for initialization")

        if not isinstance(atom_indices, list):
            atom_indices = list(atom_indices)
        self._atom_indices = atom_indices

atoms property

atoms: list[Atom] | None

Return the Atom instances in the StructureBase

atom_indices property

atom_indices: list[int]

The Atoms/Coords indices which the StructureBase has access to

number_of_atoms property

number_of_atoms: int

The number of atoms/coordinates in the StructureBase

backbone_and_cb_indices abstractmethod property

backbone_and_cb_indices: list[int]

The indices that index the StructureBase backbone and CB Atoms/Coords

backbone_indices abstractmethod property

backbone_indices: list[int]

The indices that index the StructureBase backbone and CB Atoms/Coords

ca_indices abstractmethod property

ca_indices: list[int]

The indices that index the StructureBase CA Atoms/Coords

cb_indices abstractmethod property

cb_indices: list[int]

The indices that index the StructureBase CB Atoms/Coords

heavy_indices abstractmethod property

heavy_indices: list[int]

The indices that index the StructureBase heavy (non-hydrogen) Atoms/Coords

side_chain_indices abstractmethod property

side_chain_indices: list[int]

The indices that index the StructureBase side-chain Atoms/Coords

backbone_atoms property

backbone_atoms: list[Atom]

Returns backbone Atom instances from the StructureBase

backbone_and_cb_atoms property

backbone_and_cb_atoms: list[Atom]

Returns backbone and CB Atom instances from the StructureBase

ca_atoms property

ca_atoms: list[Atom]

Returns CA Atom instances from the StructureBase

cb_atoms property

cb_atoms: list[Atom]

Returns CB Atom instances from the StructureBase

heavy_atoms property

heavy_atoms: list[Atom]

Returns heavy Atom instances from the StructureBase

side_chain_atoms property

side_chain_atoms: list[Atom]

Returns side chain Atom instances from the StructureBase

center_of_mass property

center_of_mass: ndarray

The center of mass for the Atom coordinates

radius property

radius: float

The furthest point from the center of mass of the StructureBase

radius_of_gyration property

radius_of_gyration: float

The measurement of the implied radius (Angstroms) affecting how the StructureBase diffuses through solution

Satisfies the equation

Rg = SQRT(SUM|i->N(Ri**2)/N)

Where: - Ri is the radius of the point i from the center of mass point - N is the total number of points

backbone_coords property

backbone_coords: ndarray

Return a view of the Coords from the StructureBase with backbone atom coordinates

backbone_and_cb_coords property

backbone_and_cb_coords: ndarray

Return a view of the Coords from the StructureBase with backbone and CB atom coordinates. Includes glycine CA

ca_coords property

ca_coords: ndarray

Return a view of the Coords from the Structure with CA atom coordinates

cb_coords property

cb_coords: ndarray

Return a view of the Coords from the Structure with CB atom coordinates

heavy_coords property

heavy_coords: ndarray

Return a view of the Coords from the StructureBase with heavy atom coordinates

side_chain_coords property

side_chain_coords: ndarray

Return a view of the Coords from the StructureBase with side chain atom coordinates

start_index property

start_index: int

The first atomic index of the StructureBase

end_index property

end_index: int

The last atomic index of the StructureBase

make_parent

make_parent()

Remove this instance from its parent, making it a parent in the process

Source code in symdesign/structure/base.py
1913
1914
1915
1916
1917
1918
def make_parent(self):
    """Remove this instance from its parent, making it a parent in the process"""
    super().make_parent()
    # Populate the Structure with its existing instances removed of any indexing
    self._assign_atoms(self.atoms)
    self.reset_state()

get_base_containers

get_base_containers() -> dict[str, Any]

Access each of the constituent structure container attributes

Returns:

  • dict[str, Any]

    The instance structural containers as a dictionary with attribute as key and container as value

Source code in symdesign/structure/base.py
1920
1921
1922
1923
1924
1925
1926
def get_base_containers(self) -> dict[str, Any]:
    """Access each of the constituent structure container attributes

    Returns:
        The instance structural containers as a dictionary with attribute as key and container as value
    """
    return dict(coords=self._coords, atoms=self._atoms)

neighboring_atom_indices

neighboring_atom_indices(distance: float = 8.0, **kwargs) -> list[int]

Returns the Atom instances in the Structure

Parameters:

  • distance (float, default: 8.0 ) –

    The distance to measure neighbors by

Returns:

  • list[int]

    The sorted atom_indices which are in contact with this instance, however, do not belong to the instance

Source code in symdesign/structure/base.py
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
def neighboring_atom_indices(self, distance: float = 8., **kwargs) -> list[int]:  # np.ndarray:
    """Returns the Atom instances in the Structure

    Args:
        distance: The distance to measure neighbors by

    Returns:
        The sorted atom_indices which are in contact with this instance, however, do not belong to the instance
    """
    parent_coords = self._coords.coords
    atom_indices = self.atom_indices

    # Create a "self.coords" and modify only coordinates in the ContainsAtoms instance
    modified_self_coords = parent_coords.copy()
    # Translate each self coordinate
    modified_self_coords[atom_indices] = parent_coords.max(axis=0) + [1000, 1000, 1000]
    modified_coords_balltree = BallTree(modified_self_coords)

    # Query for neighbors of the self coordinates but excluding the self indices
    coords = parent_coords[atom_indices]
    query = modified_coords_balltree.query_radius(coords, distance)

    return sorted({idx for contacts in query.tolist() for idx in contacts.tolist()})

atom

atom(atom_number: int) -> Atom | None

Returns the Atom specified by atom number if a matching Atom is found, otherwise None

Source code in symdesign/structure/base.py
2142
2143
2144
2145
2146
2147
def atom(self, atom_number: int) -> Atom | None:
    """Returns the Atom specified by atom number if a matching Atom is found, otherwise None"""
    for atom in self.atoms:
        if atom.number == atom_number:
            return atom
    return None

renumber_atoms

renumber_atoms(at: int = 1)

Renumber all Atom objects sequentially starting with 1

Parameters:

  • at (int, default: 1 ) –

    The number to start renumbering at

Source code in symdesign/structure/base.py
2207
2208
2209
2210
2211
2212
2213
2214
def renumber_atoms(self, at: int = 1):
    """Renumber all Atom objects sequentially starting with 1

    Args:
        at: The number to start renumbering at
    """
    for idx, atom in enumerate(self.atoms, at):
        atom.number = idx

reset_indices

reset_indices()

Reset the indices attached to the instance

Source code in symdesign/structure/base.py
2226
2227
2228
2229
2230
2231
2232
def reset_indices(self):
    """Reset the indices attached to the instance"""
    for attr in self._indices_attributes:
        try:
            delattr(self, attr)
        except AttributeError:
            continue

format_header

format_header(**kwargs) -> str

Returns the base .pdb formatted header

Returns:

  • str

    The .pdb file header string

Source code in symdesign/structure/base.py
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
def format_header(self, **kwargs) -> str:
    """Returns the base .pdb formatted header

    Returns:
        The .pdb file header string
    """
    # XXXX should be substituted for the PDB code. Ex:
    # f'HEADER    VIRAL PROTEIN                           28-MAY-21   7OP2              \n'
    # f'HEADER    VIRAL PROTEIN/DE NOVO PROTEIN           11-MAY-12   4ATZ              \n'
    return \
        f'HEADER    {self.name[:40]:<40s}{utils.short_start_date.upper():<12s}{"XXXX":<18s}\n' \
        'EXPDTA    THEORETICAL MODEL                                                     \n' \
        'REMARK 220                                                                      \n' \
        'REMARK 220 EXPERIMENTAL DETAILS                                                 \n' \
        'REMARK 220  EXPERIMENT TYPE                : THEORETICAL MODELLING              \n' \
        f'REMARK 220  DATE OF DATA COLLECTION        : {utils.long_start_date:<35s}\n' \
        f'REMARK 220 REMARK: MODEL GENERATED BY {putils.program_name.upper():<50s}\n' \
        f'REMARK 220         VERSION {putils.commit_short:<61s}\n'

get_atom_record abstractmethod

get_atom_record(**kwargs) -> str

Provide the Structure Atom instances as a .pdb file string

Other Parameters:

  • chain_id

    str = None - The chain ID to use

  • atom_offset

    int = 0 - How much to offset the atom number by. Default returns one-indexed

Returns:

  • str

    The archived .pdb formatted ATOM records for the Structure

Source code in symdesign/structure/base.py
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
@abc.abstractmethod
def get_atom_record(self, **kwargs) -> str:
    """Provide the Structure Atom instances as a .pdb file string

    Keyword Args:
        chain_id: str = None - The chain ID to use
        atom_offset: int = 0 - How much to offset the atom number by. Default returns one-indexed

    Returns:
        The archived .pdb formatted ATOM records for the Structure
    """

write

write(out_path: bytes | str = os.getcwd(), file_handle: IO = None, header: str = None, **kwargs) -> AnyStr | None

Write Atom instances to a file specified by out_path or with a passed file_handle

If a file_handle is passed, no header information will be written. Arguments are mutually exclusive

Parameters:

  • out_path (bytes | str, default: getcwd() ) –

    The location where the Structure object should be written to disk

  • file_handle (IO, default: None ) –

    Used to write Structure details to an open FileObject

  • header (str, default: None ) –

    A string that is desired at the top of the file

Keyword Args chain_id: str = None - The chain ID to use atom_offset: int = 0 - How much to offset the atom index by. Default uses one-indexed atom numbers

Returns:

  • AnyStr | None

    The name of the written file if out_path is used

Source code in symdesign/structure/base.py
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
def write(
    self, out_path: bytes | str = os.getcwd(), file_handle: IO = None, header: str = None, **kwargs
) -> AnyStr | None:
    """Write Atom instances to a file specified by out_path or with a passed file_handle

    If a file_handle is passed, no header information will be written. Arguments are mutually exclusive

    Args:
        out_path: The location where the Structure object should be written to disk
        file_handle: Used to write Structure details to an open FileObject
        header: A string that is desired at the top of the file

    Keyword Args
        chain_id: str = None - The chain ID to use
        atom_offset: int = 0 - How much to offset the atom index by. Default uses one-indexed atom numbers

    Returns:
        The name of the written file if out_path is used
    """
    if file_handle:
        file_handle.write(f'{self.get_atom_record(**kwargs)}\n')
        return None
    else:  # out_path always has default argument current working directory
        _header = self.format_header()
        if header is not None:
            if not isinstance(header, str):
                header = str(header)
            _header += (header if header[-2:] == '\n' else f'{header}\n')

        with open(out_path, 'w') as outfile:
            outfile.write(_header)
            outfile.write(f'{self.get_atom_record(**kwargs)}\n')
        return out_path

get_atoms

get_atoms(numbers: Container = None, **kwargs) -> list[Atom]

Retrieves Atom instances. Returns all by default unless a list of numbers is specified

Parameters:

  • numbers (Container, default: None ) –

    The Atom numbers of interest

Returns:

  • list[Atom]

    The requested Atom objects

Source code in symdesign/structure/base.py
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
def get_atoms(self, numbers: Container = None, **kwargs) -> list[Atom]:
    """Retrieves Atom instances. Returns all by default unless a list of numbers is specified

    Args:
        numbers: The Atom numbers of interest

    Returns:
        The requested Atom objects
    """
    if numbers is not None:
        if isinstance(numbers, Container):
            return [atom for atom in self.atoms if atom.number in numbers]
        else:
            self.log.error(f'The passed numbers type "{type(numbers).__name__}" must be a Container. Returning'
                           f' all Atom instances instead')
    return self.atoms

set_atoms_attributes

set_atoms_attributes(**kwargs)

Set attributes specified by key, value pairs for Atoms in the Structure

Other Parameters:

  • numbers

    Container[int] = None - The Atom numbers of interest

  • pdb

    bool = False - Whether to search for numbers as they were parsed (if True)

Source code in symdesign/structure/base.py
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
def set_atoms_attributes(self, **kwargs):
    """Set attributes specified by key, value pairs for Atoms in the Structure

    Keyword Args:
        numbers: Container[int] = None - The Atom numbers of interest
        pdb: bool = False - Whether to search for numbers as they were parsed (if True)
    """
    for atom in self.get_atoms(**kwargs):
        for kwarg, value in kwargs.items():
            setattr(atom, kwarg, value)

Residue

Residue(**kwargs)

Bases: ContainsAtoms, ResidueFragment

Parameters:

  • **kwargs
Source code in symdesign/structure/base.py
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
def __init__(self, **kwargs):
    """Construct the instance

    Args:
        **kwargs:
    """
    super().__init__(**kwargs)  # Residue
    if self.is_parent():
        # Setting up a parent (independent) Residue
        self._ensure_valid_residue()
        self.start_index = 0

    self.delegate_atoms()

index property

index

The Residue index in a Residues container

range property

range: list[int]

The range of indices corresponding to the Residue atoms

type1 property

type1: str

Access the one character representation of the amino acid type

backbone_indices property writable

backbone_indices: list[int]

The indices that index the Residue backbone Atoms/Coords

backbone_and_cb_indices property writable

backbone_and_cb_indices: list[int]

The indices that index the Residue backbone and CB Atoms/Coords

ca_indices property

ca_indices: list[int]

Return the index of the CA Atom as a list in the Residue Atoms/Coords

cb_indices property

cb_indices: list[int]

Return the index of the CB Atom as a list in the Residue Atoms/Coords. Will return CA index if Glycine

side_chain_indices property writable

side_chain_indices: list[int]

The indices that index the Residue side chain Atoms/Coords

heavy_indices property writable

heavy_indices: list[int]

The indices that index the Residue heavy (non-hydrogen) Atoms/Coords

n property

n: Atom | None

Return the amide N Atom object

n_coords property

n_coords: ndarray | None

Return the amide N Atom coordinate

n_atom_index property

n_atom_index: int | None

Return the index of the amide N Atom in the Structure Atoms/Coords

n_index property

n_index: int | None

Return the index of the amide N Atom in the Residue Atoms/Coords

h property

h: Atom | None

Return the amide H Atom object

h_coords property

h_coords: ndarray | None

Return the amide H Atom coordinate

h_atom_index property

h_atom_index: int | None

Return the index of the amide H Atom in the Structure Atoms/Coords

h_index property

h_index: int | None

Return the index of the amide H Atom in the Residue Atoms/Coords

ca property

ca: Atom | None

Return the CA Atom object

ca_coords property

ca_coords: ndarray | None

Return the CA Atom coordinate

ca_atom_index property

ca_atom_index: int | None

Return the index of the CA Atom in the Structure Atoms/Coords

ca_index property

ca_index: int | None

Return the index of the CA Atom in the Residue Atoms/Coords

cb property

cb: Atom | None

Return the CB Atom object

cb_coords property

cb_coords: ndarray | None

Return the CB Atom coordinate

cb_atom_index property

cb_atom_index: int | None

Return the index of the CB Atom in the Structure Atoms/Coords

cb_index property

cb_index: int | None

Return the index of the CB Atom in the Residue Atoms/Coords

c property

c: Atom | None

Return the carbonyl C Atom object

c_coords property

c_coords: ndarray | None

Return the carbonyl C Atom coordinate

c_atom_index property

c_atom_index: int | None

Return the index of the carbonyl C Atom in the Structure Atoms/Coords

c_index property

c_index: int | None

Return the index of the carbonyl C Atom in the Residue Atoms/Coords

o property

o: Atom | None

Return the carbonyl O Atom object

o_coords property

o_coords: ndarray | None

Return the carbonyl O Atom coords

o_atom_index property

o_atom_index: int | None

Return the index of the carbonyl C Atom in the Structure Atoms/Coords

o_index property

o_index: int | None

Return the index of the carbonyl O Atom in the Residue Atoms/Coords

prev_residue property

prev_residue: Residue | None

The previous Residue in the Structure if this Residue is part of a polymer

next_residue property

next_residue: Residue | None

The next Residue in the Structure if this Residue is part of a polymer

local_density property writable

local_density: float

Describes how many heavy Atoms are within a distance (default = 12 Angstroms) of Residue heavy Atoms

secondary_structure property writable

secondary_structure: str

Return the secondary structure designation as defined by a secondary structure calculation

sasa property writable

sasa: float

Return the solvent accessible surface area as calculated by a solvent accessible surface area calculator

sasa_apolar property writable

sasa_apolar: float

Return apolar solvent accessible surface area as calculated by a solvent accessible surface area calculator

sasa_polar property writable

sasa_polar: float

Return polar solvent accessible surface area as calculated by a solvent accessible surface area calculator

relative_sasa property

relative_sasa: float

The solvent accessible surface area relative to the standard surface accessibility of the Residue type

spatial_aggregation_propensity property writable

spatial_aggregation_propensity: float

The Residue contact order, which describes how far away each Residue makes contacts in the polymer chain

contact_order property writable

contact_order: float

The Residue contact order, which describes how far away each Residue makes contacts in the polymer chain

start_index

start_index(index: int)

Set Residue atom_indices starting with atom_indices[0] as start_index. Creates remainder incrementally and updates individual Atom instance .index accordingly

Source code in symdesign/structure/base.py
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
@ContainsAtoms.start_index.setter
def start_index(self, index: int):
    """Set Residue atom_indices starting with atom_indices[0] as start_index. Creates remainder incrementally and
    updates individual Atom instance .index accordingly
    """
    self._atom_indices = list(range(index, index + self.number_of_atoms))
    for atom, index in zip(self._atoms[self._atom_indices], self._atom_indices):
        atom.index = index
    # Clear all the indices attributes for this Residue
    self.reset_indices()

delegate_atoms

delegate_atoms()

Set the Residue atoms from a parent StructureBase

Source code in symdesign/structure/base.py
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
def delegate_atoms(self):
    """Set the Residue atoms from a parent StructureBase"""
    side_chain_indices, heavy_indices = [], []
    # try:
    #     for idx, atom in enumerate(self.atoms):
    #         match atom.type:  # Todo python 3.10
    #             case 'N':
    #                 self._n_index = idx
    #                 if self.number is None:
    #                     self.chain_id = atom.chain_id
    #                     self.number = atom.residue_number
    #                     self.type = atom.residue_type
    #                else:
    #                    raise stutils.ConstructionError(
    #                        f"Couldn't create a {self.__class__.__name__} with multiple 'N' Atom instances"
    #                    )
    #             case 'CA':
    #                 self._ca_index = idx
    #             case 'CB':
    #                 self._cb_index = idx
    #             case 'C':
    #                 self._c_index = idx
    #             case 'O':
    #                 self._o_index = idx
    #             case 'H':
    #                 self._h_index = idx
    #             case _:
    #                 side_chain_indices.append(idx)
    #                 if 'H' not in atom.type:
    #                     heavy_indices.append(idx)
    # except SyntaxError:  # python version not 3.10
    for idx, atom in enumerate(self.atoms):
        atom_type = atom.type
        if atom_type == 'N':
            self._n_index = idx
            if self.number is None:
                self.chain_id = atom.chain_id
                self.number = atom.residue_number
                self.type = atom.residue_type
            else:
                raise stutils.ConstructionError(
                    f"Couldn't create a {self.__class__.__name__} with multiple 'N' Atom instances"
                )
        elif atom_type == 'CA':
            self._ca_index = idx
        elif atom_type == 'CB':
            self._cb_index = idx
        elif atom_type == 'C':
            self._c_index = idx
        elif atom_type == 'O':
            self._o_index = idx
        elif atom_type == 'H':  # 1H or H1
            self._h_index = idx
        # elif atom_type == 'OXT':
        #     self._oxt_index = idx
        # elif atom_type == 'H2':
        #     self._h2_index = idx
        # elif atom_type == 'H3':
        #     self._h3_index = idx
        else:
            side_chain_indices.append(idx)
            if 'H' not in atom_type:
                heavy_indices.append(idx)

    # Construction ensures proper order for _bb_indices even if out of order
    # Important this order is correct for ProteinMPNN
    self.backbone_indices = [getattr(self, f'_{index}_index', None) for index in ['n', 'ca', 'c', 'o']]
    cb_index = getattr(self, '_cb_index', None)
    if cb_index:
        cb_indices = [cb_index]
    else:
        if self.type == 'GLY':  # Set _cb_index, but don't include in backbone_and_cb_indices
            self._cb_index = getattr(self, '_ca_index')
        cb_indices = []

    # By using private backbone_indices variable v, None is removed
    self.backbone_and_cb_indices = self._bb_indices + cb_indices
    self.heavy_indices = self._bb_and_cb_indices + heavy_indices
    self.side_chain_indices = side_chain_indices

contains_hydrogen

contains_hydrogen() -> bool

Returns whether the Residue contains hydrogen atoms

Source code in symdesign/structure/base.py
2626
2627
2628
def contains_hydrogen(self) -> bool:  # in Structure too
    """Returns whether the Residue contains hydrogen atoms"""
    return self.heavy_indices != self._atom_indices

is_n_termini

is_n_termini() -> bool

Returns whether the Residue is the n-termini of the parent Structure

Source code in symdesign/structure/base.py
2863
2864
2865
def is_n_termini(self) -> bool:
    """Returns whether the Residue is the n-termini of the parent Structure"""
    return self.prev_residue is None

is_c_termini

is_c_termini() -> bool

Returns whether the Residue is the c-termini of the parent Structure

Source code in symdesign/structure/base.py
2875
2876
2877
def is_c_termini(self) -> bool:
    """Returns whether the Residue is the c-termini of the parent Structure"""
    return self.next_residue is None

get_upstream

get_upstream(number: int = None) -> list[Residue]

Get the Residues upstream of (n-terminal to) the current Residue

Parameters:

  • number (int, default: None ) –

    The number of residues to retrieve. If not provided gets all

Returns:

  • list[Residue]

    The Residue instances in n- to c-terminal order

Source code in symdesign/structure/base.py
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
def get_upstream(self, number: int = None) -> list[Residue]:
    """Get the Residues upstream of (n-terminal to) the current Residue

    Args:
        number: The number of residues to retrieve. If not provided gets all

    Returns:
        The Residue instances in n- to c-terminal order
    """
    if number is None:
        number = sys.maxsize
    elif number == 0:
        raise ValueError("Can't get 0 upstream residues. 1 or more must be specified")

    last_prev_residue = self.prev_residue
    prev_residues = [last_prev_residue]
    idx = 0
    try:
        for idx in range(abs(number) - 1):
            prev_residue = last_prev_residue.prev_residue
            prev_residues.append(prev_residue)
            last_prev_residue = prev_residue
    except AttributeError:  # Hit a termini, where prev_residue is None
        # logger.debug(f'Stopped at {idx=} with {repr(prev_residues)}. Popping the last')
        prev_residues.pop(idx)
    else:  # For the edge case where the last added residue is a termini, strip from results
        if last_prev_residue is None:
            prev_residues.pop()

    return prev_residues[::-1]

get_downstream

get_downstream(number: int = None) -> list[Residue]

Get the Residues downstream of (c-terminal to) the current Residue

Parameters:

  • number (int, default: None ) –

    The number of residues to retrieve. If not provided gets all

Returns:

  • list[Residue]

    The Residue instances in n- to c-terminal order

Source code in symdesign/structure/base.py
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
def get_downstream(self, number: int = None) -> list[Residue]:
    """Get the Residues downstream of (c-terminal to) the current Residue

    Args:
        number: The number of residues to retrieve. If not provided gets all

    Returns:
        The Residue instances in n- to c-terminal order
    """
    if number is None:
        number = sys.maxsize
    elif number == 0:
        raise ValueError("Can't get 0 downstream residues. 1 or more must be specified")

    last_next_residue = self.next_residue
    next_residues = [last_next_residue]
    idx = 0
    try:
        for idx in range(abs(number) - 1):
            next_residue = last_next_residue.next_residue
            next_residues.append(next_residue)
            last_next_residue = next_residue
    except AttributeError:  # Hit a termini, where next_residue is None
        # logger.debug(f'Stopped at {idx=} with {repr(next_residues)}. Popping the last')
        next_residues.pop(idx)
    else:  # For the edge case where the last added residue is a termini, strip from results
        if last_next_residue is None:
            next_residues.pop()

    return next_residues

get_neighbors

get_neighbors(distance: float = 8.0, **kwargs) -> list[Residue]

If this Residue instance is part of a polymer, find neighboring Residue instances defined by a distance

Parameters:

  • distance (float, default: 8.0 ) –

    The distance to measure neighbors by

Returns:

  • list[Residue]

    The Residue instances that are within the distance to this Residue

Source code in symdesign/structure/base.py
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
def get_neighbors(self, distance: float = 8., **kwargs) -> list[Residue]:
    """If this Residue instance is part of a polymer, find neighboring Residue instances defined by a distance

    Args:
        distance: The distance to measure neighbors by

    Returns:
        The Residue instances that are within the distance to this Residue
    """
    try:
        return self.parent.get_residues_by_atom_indices(self.neighboring_atom_indices(distance=distance, **kwargs))
    except AttributeError:  # This Residue is the parent
        return [self]

mutation_possibilities_from_directive

mutation_possibilities_from_directive(directive: directives = None, background: set[str] = None, special: bool = False, **kwargs) -> set[protein_letters3_alph1_literal] | set

Select mutational possibilities for each Residue based on the Residue and a directive

Parameters:

  • directive (directives, default: None ) –

    Where the choice is one of 'special', 'same', 'different', 'charged', 'polar', 'apolar', 'hydrophobic', 'aromatic', 'hbonding', 'branched'

  • background (set[str], default: None ) –

    The background amino acids to compare possibilities against

  • special (bool, default: False ) –

    Whether to include special residues

Returns:

  • set[protein_letters3_alph1_literal] | set

    The possible amino acid types available given the mutational directive

Source code in symdesign/structure/base.py
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
def mutation_possibilities_from_directive(
    self, directive: directives = None, background: set[str] = None, special: bool = False, **kwargs
) -> set[protein_letters3_alph1_literal] | set:
    """Select mutational possibilities for each Residue based on the Residue and a directive

    Args:
        directive: Where the choice is one of 'special', 'same', 'different', 'charged', 'polar', 'apolar',
            'hydrophobic', 'aromatic', 'hbonding', 'branched'
        background: The background amino acids to compare possibilities against
        special: Whether to include special residues

    Returns:
        The possible amino acid types available given the mutational directive
    """
    if not directive or directive not in mutation_directives:
        self.log.debug(f'{self.mutation_possibilities_from_directive.__name__}: The mutation directive {directive} '
                       f'is not a valid directive yet. Possible directives are: {", ".join(mutation_directives)}')
        return set()
        # raise TypeError('%s: The mutation directive %s is not a valid directive yet. Possible directives are: %s'
        #                 % (self.mutation_possibilities_from_directive.__name__, directive,
        #                    ', '.join(mutation_directives)))

    current_properties = residue_properties[self.type]
    if directive == 'same':
        properties = current_properties
    elif directive == 'different':  # hmm not right -> .difference({hbonding, branched}) <- for ex. polar if apolar
        properties = set(aa_by_property.keys()).difference(current_properties)
    else:
        properties = [directive]
    available_aas = set(aa for prop in properties for aa in aa_by_property[prop])

    if directive != 'special' and not special:
        available_aas = available_aas.difference(aa_by_property['special'])
    if background:
        available_aas = background.intersection(available_aas)

    return available_aas

distance

distance(other: Residue, dtype: str = 'ca') -> float

Return the distance from this Residue to another specified by atom type "dtype"

Parameters:

  • other (Residue) –

    The other Residue to measure against

  • dtype (str, default: 'ca' ) –

    The Atom type to perform the measurement with

Returns:

  • float

    The Euclidean distance between the specified Atom type

Source code in symdesign/structure/base.py
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
def distance(self, other: Residue, dtype: str = 'ca') -> float:
    """Return the distance from this Residue to another specified by atom type "dtype"

    Args:
        other: The other Residue to measure against
        dtype: The Atom type to perform the measurement with

    Returns:
        The Euclidean distance between the specified Atom type
    """
    return np.linalg.norm(getattr(self, f'.{dtype}_coords') - getattr(other, f'.{dtype}_coords'))

get_atom_record

get_atom_record(chain_id: str = None, atom_offset: int = 0, **kwargs) -> str

Provide the Structure Atoms as a PDB file string

Parameters:

  • chain_id (str, default: None ) –

    The chain ID to use

  • atom_offset (int, default: 0 ) –

    How much to offset the atom number by. Default returns one-indexed

Returns:

  • str

    The archived .pdb formatted ATOM records for the Structure

Source code in symdesign/structure/base.py
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
def get_atom_record(self, chain_id: str = None, atom_offset: int = 0, **kwargs) -> str:
    """Provide the Structure Atoms as a PDB file string

    Args:
        chain_id: The chain ID to use
        atom_offset: How much to offset the atom number by. Default returns one-indexed

    Returns:
        The archived .pdb formatted ATOM records for the Structure
    """
    return f'{self.__str__(chain_id=chain_id, atom_offset=atom_offset, **kwargs)}\n'

__str__

__str__(chain_id: str = None, atom_offset: int = 0, **kwargs) -> str

Format the Residue into the contained Atoms. The Atom number is truncated at 5 digits for PDB compliant formatting

Parameters:

  • chain_id (str, default: None ) –

    The chain ID to use

  • atom_offset (int, default: 0 ) –

    How much to offset the atom number by. Default returns one-indexed

Returns:

  • str

    The archived .pdb formatted ATOM records for the Residue

Source code in symdesign/structure/base.py
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
def __str__(self, chain_id: str = None, atom_offset: int = 0, **kwargs) -> str:
    #         type=None, number=None
    """Format the Residue into the contained Atoms. The Atom number is truncated at 5 digits for PDB compliant
    formatting

    Args:
        chain_id: The chain ID to use
        atom_offset: How much to offset the atom number by. Default returns one-indexed

    Returns:
        The archived .pdb formatted ATOM records for the Residue
    """
    #     pdb: Whether the Residue representation should use the number at file parsing
    # format the string returned from each Atom, such as
    #  'ATOM  %s  CG2 %s %s%s    %s  1.00 17.48           C  0'
    #       AtomIdx  TypeChNumberCoords
    # To
    #  'ATOM     32  CG2 VAL A 132       9.902  -5.550   0.695  1.00 17.48           C  0'
    # self.type, self.alt_location, self.code_for_insertion, self.occupancy, self.b_factor,
    #                     self.element, self.charge)
    # res_str = self.residue_string(**kwargs)
    res_str = format(self.type, '3s'), format(chain_id or self.chain_id, '>2s'), format(self.number, '4d')
    # Add 1 to make index one-indexed
    offset = 1 + atom_offset
    # Limit atom_index with atom_index_slice to keep ATOM record correct length v
    return '\n'.join(atom.__str__().format(format(atom_idx + offset, '5d')[atom_index_slice],
                                           *res_str, '{:8.3f}{:8.3f}{:8.3f}'.format(*coord))
                     for atom, atom_idx, coord in zip(self.atoms, self._atom_indices, self.coords.tolist()))

Residues

Residues(structs: Sequence[StructureBase] | ndarray = None)

Bases: StructureBaseContainer

Parameters:

  • structs (Sequence[StructureBase] | ndarray, default: None ) –

    The StructureBase instances to store. Should be a homogeneous Sequence

Source code in symdesign/structure/base.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
def __init__(self, structs: Sequence[StructureBase] | np.ndarray = None):
    """Construct the instance

    Args:
        structs: The StructureBase instances to store. Should be a homogeneous Sequence
    """
    if structs is None:
        structs = []
    elif not isinstance(structs, (np.ndarray, list)):
        structs = list(structs)
        # raise TypeError(
        #     f"Can't initialize {self.__class__.__name__} with {type(structs).__name__}. Type must be a "
        #     f'numpy.ndarray or list[{StructureBase.__name__}]')

    self.structs = np.array(structs, dtype=np.object_)

reindex

reindex(start_at: int = 0)

Index the Residue instances and their corresponding Atom/Coords indices according to their position

Parameters:

  • start_at (int, default: 0 ) –

    The index to start reindexing at. Must be [0, 'inf']

Source code in symdesign/structure/base.py
3287
3288
3289
3290
3291
3292
3293
3294
def reindex(self, start_at: int = 0):
    """Index the Residue instances and their corresponding Atom/Coords indices according to their position

    Args:
        start_at: The index to start reindexing at. Must be [0, 'inf']
    """
    self.set_index(start_at=start_at)
    self.reindex_atoms(start_at=start_at)

set_index

set_index(start_at: int = 0)

Index the Residue instances according to their position in the Residues container

Parameters:

  • start_at (int, default: 0 ) –

    The Residue index to start reindexing at

Source code in symdesign/structure/base.py
3296
3297
3298
3299
3300
3301
3302
3303
def set_index(self, start_at: int = 0):
    """Index the Residue instances according to their position in the Residues container

    Args:
        start_at: The Residue index to start reindexing at
    """
    for idx, struct in enumerate(self.structs[start_at:].tolist(), start_at):
        struct._index = idx

reindex_atoms

reindex_atoms(start_at: int = 0)

Index the Residue instances Atoms/Coords indices according to incremental Atoms/Coords index. Responsible for updating member Atom.index attributes as well

Parameters:

  • start_at (int, default: 0 ) –

    The index to start reindexing at. Must be [0, 'inf']

Source code in symdesign/structure/base.py
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
def reindex_atoms(self, start_at: int = 0):
    """Index the Residue instances Atoms/Coords indices according to incremental Atoms/Coords index. Responsible
    for updating member Atom.index attributes as well

    Args:
        start_at: The index to start reindexing at. Must be [0, 'inf']
    """
    if start_at == 0:
        _start_at = start_at
    else:
        _start_at = start_at - 1
        if start_at < 0:
            _start_at += len(self)

    struct: Residue
    prior_struct: Residue
    try:
        # prior_struct, *other_structs = self.structs[start_at - 1:]
        prior_struct, *other_structs = self[_start_at:]
    except ValueError:  # Not enough values to unpack as the index didn't slice anything
        raise IndexError(
            f'{self.reindex_atoms.__name__}: {start_at=} is outside of the allowed {self.__class__.__name__} '
            f'indices with size {len(self)}')
    else:
        if start_at == 0:
            prior_struct.start_index = start_at

        for struct in other_structs:
            struct.start_index = prior_struct.end_index + 1
            prior_struct = struct

StructureIndexMixin

Bases: ABC

is_parent abstractmethod

is_parent() -> bool
Source code in symdesign/structure/base.py
3355
3356
3357
@abc.abstractmethod
def is_parent(self) -> bool:
    """"""

ContainsResidues

ContainsResidues(structure: ContainsResidues = None, residues: list[Residue] | Residues = None, residue_indices: list[int] = None, pose_format: bool = False, fragment_db: FragmentDatabase = None, **kwargs)

Bases: ContainsAtoms, StructureIndexMixin

Structure object handles Atom/Residue/Coords manipulation of all Structure containers. Must pass parent and residue_indices, atoms and coords, or residues to initialize

Polymer/Chain designation. This designation essentially means it contains Residue instances in a Residues object

Parameters:

  • structure (ContainsResidues, default: None ) –

    Create the instance based on an existing Structure instance

  • residues (list[Residue] | Residues, default: None ) –

    The Residue instances which should constitute a new Structure instance

  • residue_indices (list[int], default: None ) –

    The indices which specify the particular Residue instances to make this Structure instance. Used with a parent to specify a subdivision of a larger Structure

  • pose_format (bool, default: False ) –

    Whether to initialize with continuous Residue numbering from 1 to N

Other Parameters:

  • atoms

    list[Atom] | Atoms = None - The Atom instances which should constitute a new Structure instance

  • parent

    StructureBase = None - If another Structure object created this Structure instance, pass the 'parent' instance. Will take ownership over Structure containers (coords, atoms, residues) for dependent Structures

  • log

    Log | Logger | bool = True - The Log or Logger instance, or the name for the logger to handle parent Structure logging. None or False prevents logging while any True assignment enables it

  • coords

    Coords | np.ndarray | list[list[float]] = None - When setting up a parent Structure instance, the coordinates of that Structure

  • name

    str = None - The identifier for the Structure instance

Source code in symdesign/structure/base.py
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
def __init__(self, structure: ContainsResidues = None,
             residues: list[Residue] | Residues = None, residue_indices: list[int] = None,
             pose_format: bool = False, fragment_db: fragment.db.FragmentDatabase = None, **kwargs):
    """Construct the instance

    Args:
        structure: Create the instance based on an existing Structure instance
        residues: The Residue instances which should constitute a new Structure instance
        residue_indices: The indices which specify the particular Residue instances to make this Structure instance.
            Used with a parent to specify a subdivision of a larger Structure
        pose_format: Whether to initialize with continuous Residue numbering from 1 to N

    Keyword Args:
        atoms: list[Atom] | Atoms = None - The Atom instances which should constitute a new Structure instance
        parent: StructureBase = None - If another Structure object created this Structure instance, pass the
            'parent' instance. Will take ownership over Structure containers (coords, atoms, residues) for
            dependent Structures
        log: Log | Logger | bool = True - The Log or Logger instance, or the name for the logger to handle parent
            Structure logging. None or False prevents logging while any True assignment enables it
        coords: Coords | np.ndarray | list[list[float]] = None - When setting up a parent Structure instance, the
            coordinates of that Structure
        name: str = None - The identifier for the Structure instance
    """
    if structure:
        if isinstance(structure, ContainsResidues):
            model_kwargs = structure.get_base_containers()
            for key, value in model_kwargs.items():
                if key in kwargs:
                    logger.warning(f"Passing an argument for '{key}' while providing the 'model' argument "
                                   f"overwrites the '{key}' argument from the 'model'")
            new_model_kwargs = {**model_kwargs, **kwargs}
            super().__init__(**new_model_kwargs)
        else:
            raise NotImplementedError(
                f"Setting {self.__class__.__name__} with model={type(structure).__name__} isn't supported")
    else:
        super().__init__(**kwargs)  # ContainsResidues

    # self._coords_indexed_residues_ = None
    # self._residue_indices = None
    # self.secondary_structure = None
    # self.nucleotides_present = False
    self._fragment_db = fragment_db
    self.sasa = None
    self.ss_sequence_indices = []
    self.ss_type_sequence = []

    if self.is_dependent():
        try:
            residue_indices[0]
        except TypeError:
            if isinstance(self, Structures):  # Structures handles this itself
                return
            raise stutils.ConstructionError(
                f"The {self.__class__.__name__} wasn't passed 'residue_indices' which are required for "
                f"initialization"
            )

        if not isinstance(residue_indices, list):
            residue_indices = list(residue_indices)
        # Must set this before setting _atom_indices
        self._residue_indices = residue_indices
        # Get the atom_indices from the provided residues
        self._atom_indices = [idx for residue in self.residues for idx in residue.atom_indices]
    # Setting up a parent Structure
    elif residues:  # Assume the passed residues aren't bound to an existing Structure
        self._assign_residues(residues)
    elif self.atoms:
        # Assume ContainsAtoms initialized .atoms. Make Residue instances, Residues
        self._create_residues()
    else:  # Set up an empty Structure or let subclass handle population
        return

    if pose_format:
        self.pose_numbering()

ss_sequence_indices instance-attribute

ss_sequence_indices: list[int] = []

Index which indicates the Residue membership to the secondary structure type element sequence

ss_type_sequence instance-attribute

ss_type_sequence: list[str] = []

The ordered secondary structure type sequence which contains one character/secondary structure element

fragment_db property writable

fragment_db: FragmentDatabase

The FragmentDatabase used to create Fragment instances

sequence property writable

sequence: str

Holds the Structure amino acid sequence

residue_indices property

residue_indices: list[int] | None

Return the residue indices which belong to the Structure

residues property

residues: list[Residue] | None

Return the Residue instances in the Structure

alphafold_atom_mask property

alphafold_atom_mask: ndarray

Return an Alphafold mask describing which Atom positions have Coord data

alphafold_coords property

alphafold_coords: ndarray

Return a view of the Coords from the StructureBase in Alphafold coordinate format

coords_indexed_residues property

coords_indexed_residues: list[Residue]

Returns the Residue associated with each Coord in the Structure

Returns:

  • list[Residue]

    Each Residue which owns the corresponding index in the .atoms/.coords attribute

backbone_coords_indexed_residues property

backbone_coords_indexed_residues: list[Residue]

Returns the Residue associated with each backbone Atom/Coord in the Structure

Returns:

  • list[Residue]

    Each Residue which owns the corresponding index in the .atoms/.coords attribute

backbone_and_cb_coords_indexed_residues property

backbone_and_cb_coords_indexed_residues: list[Residue]

Returns the Residue associated with each backbone and CB Atom/Coord in the Structure

Returns:

  • list[Residue]

    Each Residue which owns the corresponding index in the .atoms/.coords attribute

heavy_coords_indexed_residues property

heavy_coords_indexed_residues: list[Residue]

Returns the Residue associated with each heavy Atom/Coord in the Structure

Returns:

  • list[Residue]

    Each Residue which owns the corresponding index in the .atoms/.coords attribute

side_chain_coords_indexed_residues property

side_chain_coords_indexed_residues: list[Residue]

Returns the Residue associated with each side chain Atom/Coord in the Structure

Returns:

  • list[Residue]

    Each Residue which owns the corresponding index in the .atoms/.coords attribute

number_of_residues property

number_of_residues: int

Access the number of Residues in the Structure

backbone_indices property

backbone_indices: list[int]

The indices that index the Structure backbone Atoms/Coords

backbone_and_cb_indices property

backbone_and_cb_indices: list[int]

The indices that index the Structure backbone and CB Atoms. Inherently gets CA of Residue instances missing CB

cb_indices property

cb_indices: list[int]

The indices that index the Structure CB Atoms. Inherently gets CA of Residue instances missing CB

ca_indices property

ca_indices: list[int]

The indices that index the Structure CA Atoms/Coords

heavy_indices property

heavy_indices: list[int]

The indices that index the Structure heavy Atoms/Coords

side_chain_indices property

side_chain_indices: list[int]

The indices that index the Structure side chain Atoms/Coords

helix_cb_indices property

helix_cb_indices: list[int]

The indices that index the Structure helical CB Atoms/Coords

n_terminal_residue property

n_terminal_residue: Residue

Retrieve the Residue from the n-termini

c_terminal_residue property

c_terminal_residue: Residue

Retrieve the Residue from the c-termini

relative_sasa property

relative_sasa: list[float]

Return a per-residue array of the relative solvent accessible area for the Structure

sasa_apolar property

sasa_apolar: list[float]

Return a per-residue array of the polar (hydrophilic) solvent accessible area for the Structure

sasa_polar property

sasa_polar: list[float]

Return a per-residue array of the apolar (hydrophobic) solvent accessible area for the Structure

surface_residues property

surface_residues: list[Residue]

Get the Residue instances that reside on the surface of the molecule

Parameters:

  • relative_sasa_thresh

    The relative area threshold that the Residue should have before it is considered 'surface'. Default cutoff is based on Levy, E. 2010

Other Parameters:

  • atom

    bool = True - Whether the output should be generated for each atom. If False, will be generated for each Residue

  • probe_radius

    float = 1.4 - The radius which surface area should be generated

Returns:

  • list[Residue]

    The surface Residue instances

interior_residues property

interior_residues: list[Residue]

Get the Residue instances that reside in the interior of the molecule

Parameters:

  • relative_sasa_thresh

    The relative area threshold that the Residue should fall below before it is considered 'interior'. Default cutoff is based on Levy, E. 2010

Other Parameters:

  • atom

    bool = True - Whether the output should be generated for each atom. If False, will be generated for each Residue

  • probe_radius

    float = 1.4 - The radius which surface area should be generated

Returns:

  • list[Residue]

    The interior Residue instances

secondary_structure property writable

secondary_structure: str

The Structure secondary structure assignment as provided by the DEFAULT_SS_PROGRAM

spatial_aggregation_propensity property

spatial_aggregation_propensity: ndarray

Return the spatial aggregation propensity on a per-residue basis

Returns:

  • ndarray

    The array of floats representing the spatial aggregation propensity for each Residue in the Structure

contact_order property writable

contact_order: ndarray

Return the contact order on a per-Residue basis

Returns:

  • ndarray

    The array of floats representing the contact order for each Residue in the Structure

from_residues classmethod

from_residues(residues: list[Residue] | Residues, **kwargs)

Initialize from existing Residue instances

Source code in symdesign/structure/base.py
3493
3494
3495
3496
@classmethod
def from_residues(cls, residues: list[Residue] | Residues, **kwargs):
    """Initialize from existing Residue instances"""
    return cls(residues=residues, **kwargs)

from_structure classmethod

from_structure(structure: ContainsResidues, **kwargs)

Initialize from an existing Structure

Source code in symdesign/structure/base.py
3498
3499
3500
3501
@classmethod
def from_structure(cls, structure: ContainsResidues, **kwargs):
    """Initialize from an existing Structure"""
    return cls(structure=structure, **kwargs)

assign_residues_from_structures

assign_residues_from_structures(structures: Iterable[ContainsResidues])

Initialize the instance from existing structure instance attributes, .coords, and .atoms, and .residues

Source code in symdesign/structure/base.py
3579
3580
3581
3582
3583
3584
3585
3586
3587
def assign_residues_from_structures(self, structures: Iterable[ContainsResidues]):
    """Initialize the instance from existing structure instance attributes, .coords, and .atoms, and .residues"""
    atoms, residues, coords = [], [], []
    for structure in structures:
        atoms.extend(structure.atoms)
        residues.extend(structure.residues)
        coords.append(structure.coords)

    self._assign_residues(residues, atoms=atoms, coords=coords)

make_parent

make_parent()

Remove this instance from its parent, making it a parent in the process

Source code in symdesign/structure/base.py
3596
3597
3598
3599
3600
3601
def make_parent(self):
    """Remove this instance from its parent, making it a parent in the process"""
    super(ContainsAtoms, ContainsAtoms).make_parent(self)
    # Populate the Structure with its existing instances removed of any indexing
    self._assign_residues(self.residues, atoms=self.atoms)
    self.reset_state()

get_base_containers

get_base_containers() -> dict[str, Any]

Returns the instance structural containers as a dictionary with attribute as key and container as value

Source code in symdesign/structure/base.py
3603
3604
3605
def get_base_containers(self) -> dict[str, Any]:
    """Returns the instance structural containers as a dictionary with attribute as key and container as value"""
    return dict(coords=self._coords, atoms=self._atoms, residues=self._residues)

contains_hydrogen

contains_hydrogen() -> bool

Returns whether the Structure contains hydrogen atoms

Source code in symdesign/structure/base.py
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
def contains_hydrogen(self) -> bool:  # in Residue too
    """Returns whether the Structure contains hydrogen atoms"""
    try:
        return self._contains_hydrogen
    except AttributeError:
        # Sample 20 residues from various "locations".
        # If H is still present but not found, there is an anomaly in the Structure
        slice_amount = max(int(self.number_of_residues / 20), 1)
        for residue in self.residues[::slice_amount]:
            if residue.contains_hydrogen():
                self._contains_hydrogen = True
                break
        else:
            self._contains_hydrogen = False

    return self._contains_hydrogen

get_coords_subset

get_coords_subset(residue_numbers: Container[int] = None, indices: Iterable[int] = None, start: int = None, end: int = None, dtype: coords_type_literal = 'ca') -> ndarray

Return a view of a subset of the Coords from the Structure specified by a range of Residue numbers

Parameters:

  • residue_numbers (Container[int], default: None ) –

    The Residue numbers to return

  • indices (Iterable[int], default: None ) –

    Residue indices of interest

  • start (int, default: None ) –

    The Residue number to start at. Inclusive

  • end (int, default: None ) –

    The Residue number to end at. Inclusive

  • dtype (coords_type_literal, default: 'ca' ) –

    The type of coordinates to get

Returns:

  • ndarray

    The specific coordinates from the Residue instances with the specified dtype

Source code in symdesign/structure/base.py
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
def get_coords_subset(self, residue_numbers: Container[int] = None, indices: Iterable[int] = None,
                      start: int = None, end: int = None, dtype: stutils.coords_type_literal = 'ca') -> np.ndarray:
    """Return a view of a subset of the Coords from the Structure specified by a range of Residue numbers

    Args:
        residue_numbers: The Residue numbers to return
        indices: Residue indices of interest
        start: The Residue number to start at. Inclusive
        end: The Residue number to end at. Inclusive
        dtype: The type of coordinates to get

    Returns:
        The specific coordinates from the Residue instances with the specified dtype
    """
    if indices is None:
        if residue_numbers is None:
            if start is not None and end is not None:
                residue_numbers = list(range(start, end + 1))
            else:
                raise ValueError(
                    f"{self.get_coords_subset.__name__}: Must provide either 'indices', 'residue_numbers' or "
                    f"'start' and 'end'")
        residues = self.get_residues(residue_numbers)
    else:
        residues = self.get_residues(indices=indices)

    coords_type = 'coords' if dtype == 'all' else f'{dtype}_coords'
    return np.concatenate([getattr(residue, coords_type) for residue in residues])

set_residues_attributes

set_residues_attributes(**kwargs)

Set attributes specified by key, value pairs for Residues in the Structure

Other Parameters:

  • numbers

    Container[int] = None - The Atom numbers of interest

  • pdb

    bool = False - Whether to search for numbers as they were parsed (if True)

Source code in symdesign/structure/base.py
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
def set_residues_attributes(self, **kwargs):
    """Set attributes specified by key, value pairs for Residues in the Structure

    Keyword Args:
        numbers: Container[int] = None - The Atom numbers of interest
        pdb: bool = False - Whether to search for numbers as they were parsed (if True)
    """
    for residue in self.get_residues(**kwargs):
        for kwarg, value in kwargs.items():
            setattr(residue, kwarg, value)

get_residue_atom_indices

get_residue_atom_indices(**kwargs) -> list[int]

Returns Atom indices for Residue instances. Returns all by default unless numbers are specified, returns only those Residue instance selected by number.

Other Parameters:

  • numbers

    Container[int] = None - The Residue numbers of interest

Source code in symdesign/structure/base.py
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
def get_residue_atom_indices(self, **kwargs) -> list[int]:
    """Returns Atom indices for Residue instances. Returns all by default unless numbers are specified, returns only
    those Residue instance selected by number.

    Keyword Args:
        numbers: Container[int] = None - The Residue numbers of interest
    """
    atom_indices = []
    for residue in self.get_residues(**kwargs):
        atom_indices.extend(residue.atom_indices)
    return atom_indices

get_residues_by_atom_indices

get_residues_by_atom_indices(atom_indices: ArrayIndexer) -> list[Residue]

Retrieve Residues in the Structure specified by Atom indices

Parameters:

  • atom_indices (ArrayIndexer) –

    The atom indices to retrieve Residue objects by

Returns:

  • list[Residue]

    The sorted, unique Residue instances corresponding to the provided atom_indices

Source code in symdesign/structure/base.py
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
def get_residues_by_atom_indices(self, atom_indices: ArrayIndexer) -> list[Residue]:
    """Retrieve Residues in the Structure specified by Atom indices

    Args:
        atom_indices: The atom indices to retrieve Residue objects by

    Returns:
        The sorted, unique Residue instances corresponding to the provided atom_indices
    """
    if self.is_parent():
        _struct = self
    else:
        _struct = self.parent

    all_residues = _struct._coords_indexed_residues[atom_indices].tolist()
    return sorted(set(all_residues), key=lambda residue: residue.index)

renumber

renumber()

Change the Atom and Residue numbering. Access the readtime Residue number in Residue.pdb_number attribute

Source code in symdesign/structure/base.py
4019
4020
4021
4022
def renumber(self):
    """Change the Atom and Residue numbering. Access the readtime Residue number in Residue.pdb_number attribute"""
    self.renumber_atoms()
    self.pose_numbering()

pose_numbering

pose_numbering()

Change the Residue numbering to start at 1. Access the readtime Residue number in .pdb_number attribute

Source code in symdesign/structure/base.py
4024
4025
4026
4027
4028
def pose_numbering(self):
    """Change the Residue numbering to start at 1. Access the readtime Residue number in .pdb_number attribute"""
    for idx, residue in enumerate(self.residues, 1):
        residue.number = idx
    self.log.debug(f'{self.name} was formatted in Pose numbering (residues now 1 to {self.number_of_residues})')

renumber_residues

renumber_residues(index: int = 0, at: int = 1)

Renumber Residue objects sequentially starting with "at"

Parameters:

  • index (int, default: 0 ) –

    The index to start the renumbering process

  • at (int, default: 1 ) –

    The number to start renumbering at

Source code in symdesign/structure/base.py
4030
4031
4032
4033
4034
4035
4036
4037
4038
def renumber_residues(self, index: int = 0, at: int = 1):
    """Renumber Residue objects sequentially starting with "at"

    Args:
        index: The index to start the renumbering process
        at: The number to start renumbering at
    """
    for idx, residue in enumerate(self.residues[index:], at):
        residue.number = idx

get_residues

get_residues(numbers: Container[int] = None, indices: Iterable[int] = None, **kwargs) -> list[Residue]

Returns Residue instances as specified. Returns all by default

Parameters:

  • numbers (Container[int], default: None ) –

    Residue numbers of interest

  • indices (Iterable[int], default: None ) –

    Residue indices of interest for the Structure

Returns:

  • list[Residue]

    The requested Residue instances, sorted in the order they appear in the Structure

Source code in symdesign/structure/base.py
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
def get_residues(self, numbers: Container[int] = None, indices: Iterable[int] = None, **kwargs) -> list[Residue]:
    """Returns Residue instances as specified. Returns all by default

    Args:
        numbers: Residue numbers of interest
        indices: Residue indices of interest for the Structure

    Returns:
        The requested Residue instances, sorted in the order they appear in the Structure
    """
    residues = self.residues
    if numbers is not None:
        if isinstance(numbers, Container):
            residues = [residue for residue in residues if residue.number in numbers]
        else:
            self.log.warning(f'The passed numbers type "{type(numbers).__name__}" must be a Container. Returning '
                             f'all Residue instances instead')
    elif indices is not None:
        try:
            residues = [residues[idx] for idx in indices]
        except IndexError:
            number_of_residues = self.number_of_residues
            for idx in indices:
                if idx < 0 or idx >= number_of_residues:
                    raise IndexError(
                        f'The residue index {idx} is out of bounds for the {self.__class__.__name__} {self.name} '
                        f'with size of {number_of_residues} residues')
    return residues

residue

residue(residue_number: int) -> Residue | None

Retrieve the specified Residue

Parameters:

  • residue_number (int) –

    The number of the Residue to search for

Source code in symdesign/structure/base.py
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
def residue(self, residue_number: int) -> Residue | None:
    """Retrieve the specified Residue

    Args:
        residue_number: The number of the Residue to search for
    """
    for residue in self.residues:
        if residue.number == residue_number:
            return residue
    return None

add_ideal_helix

add_ideal_helix(termini: termini_literal = 'n', length: int = 5, alignment_length: int = 5)

Add an ideal helix to a termini given by a certain length

Parameters:

  • termini (termini_literal, default: 'n' ) –

    The termini to add the ideal helix to

  • length (int, default: 5 ) –

    The length of the addition, where viable values are [1-10] residues additions

  • alignment_length (int, default: 5 ) –

    The number of residues used to calculation overlap of the target to the ideal helix

Source code in symdesign/structure/base.py
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
def add_ideal_helix(self, termini: stutils.termini_literal = 'n', length: int = 5, alignment_length: int = 5):
    """Add an ideal helix to a termini given by a certain length

    Args:
        termini: The termini to add the ideal helix to
        length: The length of the addition, where viable values are [1-10] residues additions
        alignment_length: The number of residues used to calculation overlap of the target to the ideal helix
    """
    maximum_extension_length = 15 - alignment_length
    if length > maximum_extension_length:
        number_of_iterations, length = divmod(length, maximum_extension_length)
        # First add the remainder 'length' with the specified alignment length,
        self.add_ideal_helix(termini=termini, length=length, alignment_length=alignment_length)
        # Then perform 10 residue extensions until complete
        # Using the default 10 and 5 alignment to prevent any errors from alignment of shorter amount from
        # propagating to the ideal addition and creating ideal "kinks"
        addition_count = count()
        while next(addition_count) != number_of_iterations:
            self.add_ideal_helix(termini=termini, length=10)

        return
    elif length < 1:
        return
    else:
        self.log.debug(f'Adding {length} residue ideal helix to {termini}-terminus of {self.name}')

    alpha_helix_15_struct = ContainsResidues.from_atoms(alpha_helix_15_atoms)

    if termini == 'n':
        residue = self.n_terminal_residue
        residue_index = residue.index
        fixed_coords = self.get_coords_subset(
            indices=list(range(residue_index, residue_index + alignment_length)), dtype='backbone')

        ideal_end_index = alpha_helix_15_struct.c_terminal_residue.index + 1
        ideal_start_index = ideal_end_index - alignment_length
        moving_coords = alpha_helix_15_struct.get_coords_subset(
            indices=list(range(ideal_start_index, ideal_end_index)), dtype='backbone')
        rmsd, rot, tx = superposition3d(fixed_coords, moving_coords)
        alpha_helix_15_struct.transform(rotation=rot, translation=tx)

        # Add residues
        helix_add_start = ideal_start_index - length
        # Exclude ideal_start_index from residue selection
        add_residues = alpha_helix_15_struct.get_residues(indices=list(range(helix_add_start, ideal_start_index)))
    elif termini == 'c':
        residue = self.c_terminal_residue
        residue_index = residue.index + 1
        fixed_coords = self.get_coords_subset(
            indices=list(range(residue_index - alignment_length, residue_index)), dtype='backbone')

        ideal_start_index = alpha_helix_15_struct.n_terminal_residue.index
        ideal_end_index = ideal_start_index + alignment_length
        moving_coords = alpha_helix_15_struct.get_coords_subset(
            indices=list(range(ideal_start_index, ideal_end_index)), dtype='backbone')
        rmsd, rot, tx = superposition3d(fixed_coords, moving_coords)
        alpha_helix_15_struct.transform(rotation=rot, translation=tx)

        # Add residues
        helix_add_end = ideal_end_index + length
        # Leave out the residue with ideal_end_index, and include the helix_add_end number
        add_residues = alpha_helix_15_struct.get_residues(indices=list(range(ideal_end_index, helix_add_end)))
    else:
        raise ValueError(
            f"'termini' must be either 'n' or 'c', not {termini}")

    self.insert_residues(residue_index, add_residues, chain_id=residue.chain_id)

get_residue_atoms

get_residue_atoms(**kwargs) -> list[Atom]

Return the Atoms contained in the Residue objects matching a set of residue numbers

Other Parameters:

  • numbers

    Container[int] = None – Residue numbers of interest

  • indices

    Iterable[int] = None – Residue indices of interest for the Structure

Returns:

  • list[Atom]

    The Atom instances belonging to the Residue instances

Source code in symdesign/structure/base.py
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
def get_residue_atoms(self, **kwargs) -> list[Atom]:
    """Return the Atoms contained in the Residue objects matching a set of residue numbers

    Keyword Args:
        numbers: Container[int] = None – Residue numbers of interest
        indices: Iterable[int] = None – Residue indices of interest for the Structure

    Returns:
        The Atom instances belonging to the Residue instances
    """
    atoms = []
    for residue in self.get_residues(**kwargs):
        atoms.extend(residue.atoms)
    return atoms

mutate_residue

mutate_residue(residue: Residue = None, index: int = None, number: int = None, to: str = 'A', **kwargs) -> list[int] | list

Mutate a specific Residue to a new residue type. Type can be 1 or 3 letter format

Parameters:

  • residue (Residue, default: None ) –

    A Residue instance to mutate

  • index (int, default: None ) –

    A Residue index to select the Residue instance of interest

  • number (int, default: None ) –

    A Residue number to select the Residue instance of interest

  • to (str, default: 'A' ) –

    The type of amino acid to mutate to

Returns:

  • list[int] | list

    The indices of the Atoms being removed from the Structure

Source code in symdesign/structure/base.py
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
def mutate_residue(self, residue: Residue = None, index: int = None, number: int = None, to: str = 'A', **kwargs) \
        -> list[int] | list:
    """Mutate a specific Residue to a new residue type. Type can be 1 or 3 letter format

    Args:
        residue: A Residue instance to mutate
        index: A Residue index to select the Residue instance of interest
        number: A Residue number to select the Residue instance of interest
        to: The type of amino acid to mutate to

    Returns:
        The indices of the Atoms being removed from the Structure
    """
    if index is not None:
        try:
            residue = self.residues[index]
        except IndexError:
            raise IndexError(
                f'The residue index {index} is out of bounds for the {self.__class__.__name__} '
                f'{self.name} with size of {self.number_of_residues} residues')
    elif number is not None:
        residue = self.residue(number)

    if residue is None:
        raise ValueError(
            f"Can't {self.mutate_residue.__name__} without Residue instance, index, or number")
    elif self.is_dependent():
        _parent = self.parent
        self.log.debug(f"{self.mutate_residue.__name__} can't be performed on a dependent StructureBase. "
                       f"Calling on the {self.__class__.__name__}.parent {repr(_parent)}")
        # Ensure the deletion is done by the Structure parent to account for everything correctly
        return _parent.mutate_residue(residue, to=to)

    to = protein_letters_1to3.get(to.upper(), to.upper())
    if residue.type == to:  # No mutation necessary
        return []
    else:
        try:
            protein_letters_3to1_extended[to]
        except KeyError:
            raise KeyError(
                f"The mutation type '{to}' isn't a viable Residue type")
    self.log.debug(f'Mutating {residue.type}{residue.number}{to}')
    residue.type = to
    for atom in residue.atoms:
        atom.residue_type = to

    # Find the corresponding Residue Atom indices to delete
    delete_indices = residue.side_chain_indices
    if not delete_indices:  # There are no indices
        return []
    else:  # Clear all state variables for all Residue instances
        self._residues.reset_state()
        # residue.side_chain_indices = []

    # Remove indices from the Residue, and Structure atom_indices
    residue_atom_indices = residue.atom_indices
    residue_atom_delete_index = residue_atom_indices.index(delete_indices[0])
    _atom_indices = self._atom_indices
    structure_atom_delete_index = _atom_indices.index(delete_indices[0])
    for _ in iter(delete_indices):
        residue_atom_indices.pop(residue_atom_delete_index)
        _atom_indices.pop(structure_atom_delete_index)

    self._offset_indices(start_at=structure_atom_delete_index, offset=-len(delete_indices), dtype='atom')

    # Re-index all succeeding Atom and Residue instance indices
    self._coords.delete(delete_indices)
    self._atoms.delete(delete_indices)
    # self._atoms.reindex(start_at=structure_atom_delete_index)
    self._residues.reindex_atoms(start_at=residue.index)

    # Reissue the atom assignments for the Residue
    residue.delegate_atoms()
    self.reset_state()

    return delete_indices

delete_residues

delete_residues(residues: Iterable[Residue] = None, indices: Iterable[int] = None, numbers: Container[int] = None, **kwargs) -> list[Residue] | list

Deletes Residue instances from the Structure

Parameters:

  • residues (Iterable[Residue], default: None ) –

    Residue instances to delete

  • indices (Iterable[int], default: None ) –

    Residue indices to select the Residue instances of interest

  • numbers (Container[int], default: None ) –

    Residue numbers to select the Residue instances of interest

Returns:

  • list[Residue] | list

    Each deleted Residue

Source code in symdesign/structure/base.py
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
def delete_residues(self, residues: Iterable[Residue] = None, indices: Iterable[int] = None,
                    numbers: Container[int] = None, **kwargs) -> list[Residue] | list:
    """Deletes Residue instances from the Structure

    Args:
        residues: Residue instances to delete
        indices: Residue indices to select the Residue instances of interest
        numbers: Residue numbers to select the Residue instances of interest

    Returns:
        Each deleted Residue
    """
    if indices is not None:
        residues = self.get_residues(indices=indices)
    elif numbers is not None:
        residues = self.get_residues(numbers=numbers)

    if residues is None:
        raise ValueError(
            f"Can't {self.delete_residues.__name__} without Residue instances. Provide with indices, numbers, or "
            "residues")
    elif not residues:
        self.log.debug(f'{self.delete_residues.__name__}: No residues found')
        return []
    elif self.is_dependent():  # Call on the parent
        _parent = self.parent
        self.log.debug(f"{self.delete_residues.__name__} can't be performed on a dependent StructureBase. "
                       f"Calling on the {self.__class__.__name__}.parent {repr(_parent)}")
        # Ensure the deletion is done by the Structure parent to account for everything correctly
        return _parent.delete_residues(residues=residues)

    # Find the Residue, Atom indices to delete
    atom_indices = []
    for residue in residues:
        self.log.debug(f'Deleting {residue.type}{residue.number}')
        atom_indices.extend(residue.atom_indices)

    if not atom_indices:
        return []  # There are no indices for the Residue instances
    else:  # Find the Residue indices to delete
        residue_indices = []
        for residue in residues:
            residue_indices.append(residue.index)

    # Remove indices from the Residue, and Structure atom_indices
    self._delete_indices(atom_indices, dtype='atom')
    self._delete_indices(residue_indices, dtype='residue')
    # Re-index all succeeding Atom and Residue instance indices
    self._coords.delete(atom_indices)
    self._atoms.delete(atom_indices)
    self._residues.delete(residue_indices)
    self._residues.reindex(start_at=residue_indices[0])

    # Clear state variables for remaining Residue instances. Residue deletion affected remaining attrs and indices
    self._residues.reset_state()
    # Reindex the coords/residues map
    self.reset_state()

    return residues

insert_residue_type

insert_residue_type(index: int, residue_type: str, chain_id: str = None) -> Residue

Insert a standard Residue type into the Structure at the origin. No structural alignment is performed!

Parameters:

  • index (int) –

    The residue index where a new Residue should be inserted into the Structure

  • residue_type (str) –

    Either the 1 or 3 letter amino acid code for the residue in question

  • chain_id (str, default: None ) –

    The chain identifier to associate the new Residue with

Returns:

  • Residue

    The newly inserted Residue object

Source code in symdesign/structure/base.py
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
def insert_residue_type(self, index: int, residue_type: str, chain_id: str = None) -> Residue:
    """Insert a standard Residue type into the Structure at the origin. No structural alignment is performed!

    Args:
        index: The residue index where a new Residue should be inserted into the Structure
        residue_type: Either the 1 or 3 letter amino acid code for the residue in question
        chain_id: The chain identifier to associate the new Residue with

    Returns:
        The newly inserted Residue object
    """
    if self.is_dependent():  # Call on the parent
        _parent = self.parent
        self.log.debug(f"{self.insert_residue_type.__name__} can't be performed on a dependent StructureBase. "
                       f"Calling on the {self.__class__.__name__}.parent {repr(_parent)}")
        # Ensure the deletion is done by the Structure parent to account for everything correctly
        if chain_id is None:
            chain_id = getattr(self, 'chain_id', None)
        return _parent.insert_residue_type(index, residue_type, chain_id=chain_id)

    self.log.debug(f'Inserting {residue_type} into index {index} of {self.name}')

    # Convert incoming amino acid to an index to select the stutils.reference_residue.
    # protein_letters_alph1 has a matching index
    reference_index = \
        protein_letters_alph1.find(protein_letters_3to1_extended.get(residue_type, residue_type.upper()))
    if reference_index == -1:
        raise IndexError(
            f"{self.insert_residue_type.__name__} of residue_type '{residue_type}' isn't allowed")
    if index < 0:
        raise IndexError(
            f"{self.insert_residue_type.__name__} at index {index} < 0 isn't allowed")

    # Grab the reference atom coordinates and push into the atom list
    new_residue = reference_residues[reference_index].copy()

    # Find the prior and next Residue, atom_start_index (starting atom in new Residue index)
    residues = self.residues
    if index == 0:  # n-termini = True
        prev_residue = None
        atom_start_index = 0
    else:
        prev_residue = residues[index - 1]
        atom_start_index = prev_residue.end_index + 1

    try:
        next_residue = residues[index]
    except IndexError:  # c_termini = True
        next_residue = None
        if not prev_residue:  # Insertion on an empty Structure? block for now to simplify chain identification
            raise stutils.DesignError(
                f"Can't {self.insert_residue_type.__name__} for an empty {self.__class__.__name__} class")

    # Set found attributes
    new_residue._insert = True

    # Insert the new_residue coords, atoms, and residues into the Structure
    self._coords.insert(atom_start_index, new_residue.coords)
    self._atoms.insert(atom_start_index, new_residue.atoms)
    self._residues.insert(index, [new_residue])
    # After coords, atoms, residues insertion into "_" containers, set parent to self
    new_residue._parent = self

    # Reformat indices
    # new_residue.start_index = atom_start_index
    # self._atoms.reindex(start_at=atom_start_index)  # Called in self._residues.reindex
    self._residues.reindex(start_at=index)  # .set_index()
    # Insert new_residue index and atom_indices into Structure indices
    self._insert_indices(index, [index], dtype='residue')
    self._insert_indices(atom_start_index, new_residue.atom_indices, dtype='atom')

    # Set the new chain_id. Must occur after self._residue_indices update if chain isn't provided
    if chain_id is None:  # Try to solve without it...
        if prev_residue and next_residue:
            if prev_residue.chain_id == next_residue.chain_id:
                chain_id = prev_residue.chain_id
            else:  # There is a discrepancy which means this is an internal termini
                raise stutils.DesignError(chain_assignment_error)
        # This can be solved as it represents an absolute termini case
        elif prev_residue:
            chain_id = prev_residue.chain_id
        else:
            chain_id = next_residue.chain_id
    new_residue.chain_id = chain_id

    # Solve the Residue number and renumber Structure if there is overlap
    if prev_residue and next_residue:
        tentative_number = prev_residue.number + 1
        if tentative_number == next_residue.number:
            # There is a conflicting insertion
            # The prev_residue could also be inserted and needed to be numbered lower
            try:  # Check residue._insert
                prev_residue._insert
            except AttributeError:  # Not inserted. Renumber all subsequent
                # self.renumber_residues()
                residues_renumber = residues[index:]
                for residue in residues_renumber:
                    residue.number = residue.number + 1
            else:
                for residue in prev_residue.get_upstream() + [prev_residue]:
                    residue.number = residue.number - 1

        new_residue.number = tentative_number
    elif prev_residue:
        new_residue.number = prev_residue.number + 1
    else:  # next_residue
        # This cautionary note may not apply anymore
        #  Subtracting one may not be enough if this insert_residue_type() is part of a set of inserts and all
        #  n-terminal insertions are being conducted before this next_residue. Clean this in the first check of
        #  this logic block
        new_residue.number = next_residue.number - 1

    try:
        secondary_structure = self._secondary_structure
    except AttributeError:  # When not set yet
        self.calculate_secondary_structure()  # The new_residue will be included
    else:  # Insert the new ss with a coiled assumption
        # ASSUME the insertion is disordered and coiled segment
        new_residue.secondary_structure = DEFAULT_SS_COIL_IDENTIFIER
        self._secondary_structure = \
            secondary_structure[:index] + DEFAULT_SS_COIL_IDENTIFIER + secondary_structure[index:]

    # Reindex the coords/residues map
    self.reset_state()

    return new_residue

insert_residues

insert_residues(index: int, new_residues: Iterable[Residue], chain_id: str = None) -> list[Residue]

Insert Residue instances into the Structure at the origin. No structural alignment is performed!

Parameters:

  • index (int) –

    The index to perform the insertion at

  • new_residues (Iterable[Residue]) –

    The Residue instances to insert

  • chain_id (str, default: None ) –

    The chain identifier to associate the new Residue instances with

Returns:

  • list[Residue]

    The inserted Residue instances

Source code in symdesign/structure/base.py
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
def insert_residues(self, index: int, new_residues: Iterable[Residue], chain_id: str = None) -> list[Residue]:
    """Insert Residue instances into the Structure at the origin. No structural alignment is performed!

    Args:
        index: The index to perform the insertion at
        new_residues: The Residue instances to insert
        chain_id: The chain identifier to associate the new Residue instances with

    Returns:
        The inserted Residue instances
    """
    if not new_residues:
        return []

    if self.is_dependent():  # Call on the parent
        _parent = self.parent
        self.log.debug(f"{self.insert_residues.__name__} can't be performed on a dependent StructureBase. "
                       f"Calling on the {self.__class__.__name__}.parent {repr(_parent)}")
        # Ensure the deletion is done by the Structure parent to account for everything correctly
        if chain_id is None:
            chain_id = getattr(self, 'chain_id', None)
        return _parent.insert_residues(index, new_residues, chain_id=chain_id)

    # Make a copy of the Residue instances
    new_residues = [residue.copy() for residue in new_residues]
    number_new_residues = len(new_residues)

    # Find the prior and next Residue, atom_start_index (starting atom in new Residue index)
    residues = self.residues
    if index == 0:  # n-termini = True
        prev_residue = _prev_residue = None
        atom_start_index = 0
    else:
        prev_residue = _prev_residue = residues[index - 1]
        atom_start_index = prev_residue.end_index + 1

    try:
        next_residue = residues[index]
    except IndexError:  # c_termini = True
        next_residue = None
        if not prev_residue:  # Insertion on an empty Structure? block for now to simplify chain identification
            raise stutils.DesignError(
                f"Can't {self.insert_residue_type.__name__} for an empty {self.__class__.__name__} class")

    # Set found attributes
    # prev_residue, *other_residues = new_residues
    for residue in new_residues:
        residue._insert = True

    # Insert the new_residue coords, atoms, and residues into the Structure
    self._coords.insert(atom_start_index, np.concatenate([residue.coords for residue in new_residues]))
    self._atoms.insert(atom_start_index, [atom for residue in new_residues for atom in residue.atoms])
    self._residues.insert(index, new_residues)
    # After coords, atoms, residues insertion into "_" containers, set parent to self
    for residue in new_residues:
        residue._parent = self

    # Reformat indices
    # new_residue.start_index = atom_start_index
    # self._atoms.reindex(start_at=atom_start_index)  # Called in self._residues.reindex
    self._residues.reindex(start_at=index)  # .set_index()
    # Insert new_residue index and atom_indices into Structure indices
    new_residue_atom_indices = list(range(atom_start_index, new_residues[-1].end_index + 1))
    self._insert_indices(atom_start_index, new_residue_atom_indices, dtype='atom')
    new_residue_indices = list(range(index, index + number_new_residues))
    self._insert_indices(index, new_residue_indices, dtype='residue')

    # Set the new chain_id. Must occur after self._residue_indices update if chain isn't provided
    if chain_id is None:  # Try to solve without it...
        if prev_residue and next_residue:
            if prev_residue.chain_id == next_residue.chain_id:
                chain_id = prev_residue.chain_id
            else:  # There is a discrepancy which means this is an internal termini
                raise stutils.DesignError(chain_assignment_error)
        # This can be solved as it represents an absolute termini case
        elif prev_residue:
            chain_id = prev_residue.chain_id
        else:
            chain_id = next_residue.chain_id
    for residue in new_residues:
        residue.chain_id = chain_id

    # Solve the Residue number and renumber Structure if there is overlap
    if prev_residue and next_residue:
        first_number = prev_residue.number + 1
        tentative_residue_numbers = list(range(first_number, first_number + number_new_residues))
        if next_residue.number in tentative_residue_numbers:
            # There is a conflicting insertion. Correct existing residue numbers
            # The prev_residue could also be inserted and needed to be numbered lower
            try:  # Check residue._insert
                prev_residue._insert
            except AttributeError:  # Not inserted. Renumber all subsequent
                # self.renumber_residues()
                residues_renumber = residues[index:]
                for residue in residues_renumber:
                    residue.number = residue.number + number_new_residues
            else:
                for residue in prev_residue.get_upstream() + [prev_residue]:
                    residue.number = residue.number - number_new_residues
        # Set the new numbers
        for residue, new_number in zip(new_residues, tentative_residue_numbers):
            residue.number = new_number
    elif prev_residue:
        _prev_residue = prev_residue
        for residue in new_residues:
            residue.number = _prev_residue.number + 1
            _prev_residue = residue
    else:  # next_residue
        # This cautionary note may not apply to insert_residues(
        #  Subtracting one may not be enough if insert_residues() is part of a set of inserts and all
        #  n-terminal insertions are being conducted before this next_residue. Clean this in the first check of
        #  this logic block
        _prev_residue = next_residue
        for residue in reversed(new_residues):
            residue.number = _prev_residue.number - 1
            _prev_residue = residue

    # Reindex the coords/residues map
    self.reset_state()

    return new_residues

delete_termini

delete_termini(how: str = 'unstructured', termini: termini_literal = None)

Remove Residue instances from the Structure termini that are not helices

Uses the default secondary structure prediction program's SS_HELIX_IDENTIFIERS (typically 'H') to search for non-conforming secondary structure

Parameters:

  • how (str, default: 'unstructured' ) –

    How should termini be trimmed? Either 'unstructured' (default) or 'to_helices' can be used. If 'unstructured', will use 'SS_DISORDER_IDENTIFIERS' (typically coil) to detect disorder. Function will then remove any disordered segments, as well as turns ('T') that exist between disordered segments If 'to_helices', will use 'SS_HELIX_IDENTIFIERS' (typically 'H') to remove any non-conforming secondary structure elements until a helix is reached

  • termini (termini_literal, default: None ) –

    If a specific termini should be targeted, which one?

Source code in symdesign/structure/base.py
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
def delete_termini(self, how: str = 'unstructured', termini: stutils.termini_literal = None):
    """Remove Residue instances from the Structure termini that are not helices

    Uses the default secondary structure prediction program's SS_HELIX_IDENTIFIERS (typically 'H') to search for
    non-conforming secondary structure

    Args:
        how: How should termini be trimmed? Either 'unstructured' (default) or 'to_helices' can be used.
            If 'unstructured',
                will use 'SS_DISORDER_IDENTIFIERS' (typically coil) to detect disorder. Function will then remove any
                disordered segments, as well as turns ('T') that exist between disordered segments
            If 'to_helices',
                will use 'SS_HELIX_IDENTIFIERS' (typically 'H') to remove any non-conforming secondary structure
                elements until a helix is reached
        termini: If a specific termini should be targeted, which one?
    """
    if termini is None or termini.lower() == 'nc':
        termini_ = 'nc'
    elif termini in 'NnCc':  # Only one of the two
        termini_ = termini.lower()
    else:
        raise ValueError(
            f"'termini' must be one of 'n' or 'c', not '{termini}")

    secondary_structure = working_secondary_structure = self.secondary_structure
    number_of_residues = self.number_of_residues
    # no_nterm_disorder_ss = secondary_structure.lstrip(SS_DISORDER_IDENTIFIERS)
    # n_removed_nterm_res = number_of_residues - len(no_nterm_disorder_ss)
    # no_cterm_disorder_ss = secondary_structure.rstrip(SS_DISORDER_IDENTIFIERS)
    # n_removed_cterm_res = number_of_residues - len(no_cterm_disorder_ss)
    # sasa = self.relative_sasa
    # self.log.debug(f'Found n-term relative sasa {sasa[:n_removed_nterm_res + 10]}')
    # self.log.debug(f'Found c-term relative sasa {sasa[-(n_removed_cterm_res + 10):]}')

    n_removed_nterm_res = 0
    # Remove coils. Find the next coil. If only ss present is (T)urn, then remove that as well and start again
    for idx, termini in enumerate('NC'):
        if idx == 0:  # n-termini
            self.log.debug(f'Starting N-term is: {working_secondary_structure[:15]}')
            possible_secondary_structure = working_secondary_structure
        else:  # c-termini
            self.log.debug(f'N-term is: {working_secondary_structure[:15]}')
            # Get the number of n-termini removed
            n_removed_nterm_res = number_of_residues - len(working_secondary_structure)
            # Reverse the sequence to get the c-termini first
            possible_secondary_structure = working_secondary_structure[::-1]
            self.log.debug(f'Starting C-term (reversed) is: {possible_secondary_structure[:15]}')

        if how == 'to_helices':
            ss_helix_index = possible_secondary_structure.find(SS_HELIX_IDENTIFIERS)
            working_secondary_structure = working_secondary_structure[ss_helix_index:]
        else:  # how == 'unstructured'
            ss_disorder_index = possible_secondary_structure.find(SS_DISORDER_IDENTIFIERS)
            while ss_disorder_index == 0:  # Go again
                # Remove DISORDER ss
                working_secondary_structure = possible_secondary_structure.lstrip(SS_DISORDER_IDENTIFIERS)
                # Next try to remove TURN ss. Only remove if it is between DISORDER segments
                possible_secondary_structure = working_secondary_structure.lstrip(SS_TURN_IDENTIFIERS)
                ss_disorder_index = possible_secondary_structure.find(SS_DISORDER_IDENTIFIERS)

    self.log.debug(f'C-term (reversed) is: {working_secondary_structure[:15]}')

    residues = self.residues
    _delete_residues = []
    context_length = 10
    if 'n' in termini_ and n_removed_nterm_res:
        old_ss = secondary_structure[:n_removed_nterm_res + context_length]
        self.log.debug(f'Found N-term secondary_structure {secondary_structure[:n_removed_nterm_res + 5]}')
        self.log.info(f"Removing {n_removed_nterm_res} N-terminal residues. Resulting secondary structure:\n"
                      f"\told : {old_ss}...\n"
                      f"\tnew : {'-' * n_removed_nterm_res}{old_ss[n_removed_nterm_res:]}...")
        _delete_residues += residues[:n_removed_nterm_res]

    # Get the number of c-termini removed
    n_removed_cterm_res = number_of_residues - len(working_secondary_structure) - n_removed_nterm_res
    if 'c' in termini_ and n_removed_cterm_res:
        c_term_index = number_of_residues - n_removed_cterm_res
        old_ss = secondary_structure[c_term_index - context_length:]
        self.log.debug(f'Found C-term secondary_structure {secondary_structure[-(n_removed_cterm_res + 5):]}')
        self.log.info(f"Removing {n_removed_cterm_res} C-terminal residues. Resulting secondary structure:\n"
                      f"\told :...{old_ss}\n"
                      f"\tnew :...{old_ss[:-n_removed_cterm_res]}{'-' * n_removed_cterm_res}")
        _delete_residues += residues[c_term_index:]

    self.delete_residues(_delete_residues)

local_density

local_density(residues: list[Residue] = None, residue_numbers: list[int] = None, distance: float = 12.0) -> list[float]

Return the number of Atoms within 'distance' Angstroms of each Atom in the requested Residues

Parameters:

  • residues (list[Residue], default: None ) –

    The Residues to include in the calculation

  • residue_numbers (list[int], default: None ) –

    The numbers of the Residues to include in the calculation

  • distance (float, default: 12.0 ) –

    The cutoff distance with which Atoms should be included in local density

Returns:

  • list[float]

    An array like containing the local density around each requested Residue

Source code in symdesign/structure/base.py
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
def local_density(self, residues: list[Residue] = None, residue_numbers: list[int] = None, distance: float = 12.) \
        -> list[float]:
    """Return the number of Atoms within 'distance' Angstroms of each Atom in the requested Residues

    Args:
        residues: The Residues to include in the calculation
        residue_numbers: The numbers of the Residues to include in the calculation
        distance: The cutoff distance with which Atoms should be included in local density

    Returns:
        An array like containing the local density around each requested Residue
    """
    if residues:
        coords = []
        for residue in residues:
            coords.extend(residue.heavy_coords)
        coords_indexed_residues = [residue for residue in residues for _ in residue.heavy_indices]
    elif residue_numbers:
        coords = []
        residues = self.get_residues(numbers=residue_numbers)
        for residue in residues:
            coords.extend(residue.heavy_coords)
        coords_indexed_residues = [residue for residue in residues for _ in residue.heavy_indices]
    else:  # use all Residue instances
        residues = self.residues
        coords = self.heavy_coords
        coords_indexed_residues = self.heavy_coords_indexed_residues

    # in case this was already called, we should set all to 0.
    if residues[0].local_density > 0:
        for residue in residues:
            residue.local_density = 0.

    all_atom_tree = BallTree(coords)
    all_atom_counts_query = all_atom_tree.query_radius(coords, distance, count_only=True)
    # residue_neighbor_counts, current_residue = 0, coords_indexed_residues[0]
    current_residue = coords_indexed_residues[0]
    for residue, atom_neighbor_counts in zip(coords_indexed_residues, all_atom_counts_query.tolist()):
        if residue == current_residue:
            current_residue.local_density += atom_neighbor_counts
        else:  # We have a new residue, find the average
            current_residue.local_density /= current_residue.number_of_heavy_atoms
            current_residue = residue
            current_residue.local_density += atom_neighbor_counts
    # Ensure the last residue is calculated
    current_residue.local_density /= current_residue.number_of_heavy_atoms  # Find the average

    return [residue.local_density for residue in self.residues]

is_clash

is_clash(measure: coords_type_literal = stutils.default_clash_criteria, distance: float = stutils.default_clash_distance, warn: bool = False, silence_exceptions: bool = False, report_hydrogen: bool = False) -> bool

Check if the Structure contains any self clashes. If clashes occur with the Backbone, return True. Reports the Residue where the clash occurred and the clashing Atoms

Parameters:

  • measure (coords_type_literal, default: default_clash_criteria ) –

    The atom type to measure clashing by

  • distance (float, default: default_clash_distance ) –

    The distance which clashes should be checked

  • warn (bool, default: False ) –

    Whether to emit warnings about identified clashes. Output grouped into measure vs non-measure

  • silence_exceptions (bool, default: False ) –

    Whether to silence the raised ClashError and Return True instead

  • report_hydrogen (bool, default: False ) –

    Whether to report clashing hydrogen atoms

Returns:

  • bool

    True if the Structure clashes, False if not

Source code in symdesign/structure/base.py
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
def is_clash(self, measure: stutils.coords_type_literal = stutils.default_clash_criteria,
             distance: float = stutils.default_clash_distance,
             warn: bool = False, silence_exceptions: bool = False,
             report_hydrogen: bool = False) -> bool:
    """Check if the Structure contains any self clashes. If clashes occur with the Backbone, return True. Reports
    the Residue where the clash occurred and the clashing Atoms

    Args:
        measure: The atom type to measure clashing by
        distance: The distance which clashes should be checked
        warn: Whether to emit warnings about identified clashes. Output grouped into measure vs non-measure
        silence_exceptions: Whether to silence the raised ClashError and Return True instead
        report_hydrogen: Whether to report clashing hydrogen atoms

    Raises:
        ClashError if the Structure has an identified clash

    Returns:
        True if the Structure clashes, False if not
    """
    if measure == 'backbone_and_cb':
        other = 'non-cb sidechain'
    elif measure == 'heavy':
        other = 'hydrogen'
        report_hydrogen = True
    elif measure == 'backbone':
        other = 'sidechain'
    elif measure == 'cb':
        other = 'non-cb'
    elif measure == 'ca':
        other = 'non-ca'
    else:  # measure == 'all'
        other = 'solvent'  # this should never appear unless someone added solvent parsing

    coords_type = 'coords' if measure == 'all' else f'{measure}_coords'
    # cant use heavy_coords as the Residue.atom_indices aren't offset for the BallTree made from them...
    # another option is to only care about heavy atoms on the residues...
    # if self.contains_hydrogen():
    #     atom_tree = BallTree(self.heavy_coords)
    #     coords_indexed_residues = self.heavy_coords_indexed_residues
    #     atoms = self.heavy_atoms
    # else:

    # Set up the query indices. BallTree is faster upon timeit with 131 msec/loop
    atom_tree = BallTree(self.coords)
    atoms = self.atoms
    measured_clashes, other_clashes = [], []

    def return_true(): return True

    clashes = False
    _any_clashes: Callable[[Iterable[int]], bool]
    """Local helper to separate clash reporting from clash generation"""
    clash_msg = f'{self.name} contains Residue {measure} atom clashes at a {distance} A distance'
    if warn:

        def _any_clashes(_clash_indices: Iterable[int]) -> bool:
            new_clashes = any(_clash_indices)
            if new_clashes:
                for clashing_idx in _clash_indices:
                    atom = atoms[clashing_idx]
                    if getattr(atom, f'is_{measure}', return_true)():
                        measured_clashes.append((residue, atom))
                    elif report_hydrogen:  # Report all clashes, no need to check
                        other_clashes.append((residue, atom))
                    elif atom.is_heavy():  # Check if atom is a heavy atom then report if it is
                        other_clashes.append((residue, atom))

            return clashes or new_clashes

        # Using _any_clashes to set the global clashes
        #     clashes = _any_clashes(): ... return clashes
        # While checking global clashes against new_clashes
    else:  # Raise a ClashError to defer to caller
        def _any_clashes(_clash_indices: Iterable[int]) -> bool:
            for clashing_idx in _clash_indices:
                if getattr(atoms[clashing_idx], f'is_{measure}', return_true)():
                    raise stutils.ClashError(clash_msg)

            return clashes

    residues = self.residues
    # Check first and last residue with different considerations given covalent bonding
    try:
        residue, next_residue = residues[:2]
        # residue, next_residue, *other_residues = self.residues
    except ValueError:  # Can't unpack
        # residues < 2. Insufficient to check clashing
        return False

    # Query each residue with requested coords_type against the atom_tree
    residue_atom_contacts = atom_tree.query_radius(getattr(residue, coords_type), distance)
    # residue_atom_contacts returns as ragged nested array, (array of different sized array)
    # Reduce the dimensions to all contacts
    all_contacts = {atom_contact for residue_contacts in residue_atom_contacts.tolist()
                    for atom_contact in residue_contacts.tolist()}
    try:
        # Subtract the N and C atoms from the adjacent residues for each residue as these are within a bond
        clashes = _any_clashes(
            all_contacts.difference(residue.atom_indices + [next_residue.n_atom_index]))
        prev_residue = residue
        residue = next_residue

        # Perform routine for all middle residues
        for next_residue in residues[2:]:
            residue_atom_contacts = atom_tree.query_radius(getattr(residue, coords_type), distance)
            all_contacts = {atom_contact for residue_contacts in residue_atom_contacts.tolist()
                            for atom_contact in residue_contacts.tolist()}
            clashes = _any_clashes(
                all_contacts.difference(
                    [prev_residue.o_atom_index, prev_residue.c_atom_index, next_residue.n_atom_index]
                    + residue.atom_indices
                ))
            prev_residue = residue
            residue = next_residue

        residue_atom_contacts = atom_tree.query_radius(getattr(residue, coords_type), distance)
        all_contacts = {atom_contact for residue_contacts in residue_atom_contacts.tolist()
                        for atom_contact in residue_contacts.tolist()}
        clashes = _any_clashes(
            all_contacts.difference([prev_residue.o_atom_index, prev_residue.c_atom_index]
                                    + residue.atom_indices)
        )
    except stutils.ClashError as error:  # Raised by _any_clashes()
        if silence_exceptions:
            return True
        else:
            raise error
    else:
        if clashes:
            if measured_clashes:
                bb_info = '\n\t'.join(f'Chain {residue.chain_id} {residue.number:5d}: {atom.get_atom_record()}'
                                      for residue, atom in measured_clashes)
                self.log.error(f'{self.name} contains {len(measured_clashes)} {measure} clashes from the following '
                               f'Residues to the corresponding Atom:\n\t{bb_info}')
                raise stutils.ClashError(clash_msg)
            if other_clashes:
                sc_info = '\n\t'.join(f'Chain {residue.chain_id} {residue.number:5d}: {atom.get_atom_record()}'
                                      for residue, atom in other_clashes)
                self.log.warning(f'{self.name} contains {len(other_clashes)} {other} clashes between the '
                                 f'following Residues:\n\t{sc_info}')
    return False

get_sasa

get_sasa(probe_radius: float = 1.4, atom: bool = True, **kwargs)

Use FreeSASA to calculate the surface area of residues in the Structure object.

Parameters:

  • probe_radius (float, default: 1.4 ) –

    The radius which surface area should be generated

  • atom (bool, default: True ) –

    Whether the output should be generated for each atom. If False, will be generated for each Residue

Sets

self.sasa, self.residue(s).sasa

Source code in symdesign/structure/base.py
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
def get_sasa(self, probe_radius: float = 1.4, atom: bool = True, **kwargs):
    """Use FreeSASA to calculate the surface area of residues in the Structure object.

    Args:
        probe_radius: The radius which surface area should be generated
        atom: Whether the output should be generated for each atom. If False, will be generated for each Residue

    Sets:
        self.sasa, self.residue(s).sasa
    """
    if atom:
        out_format = 'pdb'
    # --format=pdb --depth=atom
    # REMARK 999 This PDB file was generated by FreeSASA 2.0.
    # REMARK 999 In the ATOM records temperature factors have been
    # REMARK 999 replaced by the SASA of the atom, and the occupancy
    # REMARK 999 by the radius used in the calculation.
    # MODEL        1                                        [radii][sasa]
    # ATOM   2557  C   PHE C 113      -2.627 -17.654  13.108  1.61  1.39
    # ATOM   2558  O   PHE C 113      -2.767 -18.772  13.648  1.42 39.95
    # ATOM   2559  CB  PHE C 113      -1.255 -16.970  11.143  1.88 13.46
    # ATOM   2560  CG  PHE C 113      -0.886 -17.270   9.721  1.61  1.98
    # ATOM   2563 CE1  PHE C 113      -0.041 -18.799   8.042  1.76 28.76
    # ATOM   2564 CE2  PHE C 113      -0.694 -16.569   7.413  1.76  2.92
    # ATOM   2565  CZ  PHE C 113      -0.196 -17.820   7.063  1.76  4.24
    # ATOM   2566 OXT  PHE C 113      -2.515 -16.590  13.750  1.46 15.09
    # ...
    # TER    7913      GLU A 264
    # ENDMDL EOF
    # if residue:
    else:
        out_format = 'seq'
    # --format=seq
    # Residues in ...
    # SEQ A    1 MET :   74.46
    # SEQ A    2 LYS :   96.30
    # SEQ A    3 VAL :    0.00
    # SEQ A    4 VAL :    0.00
    # SEQ A    5 VAL :    0.00
    # SEQ A    6 GLN :    0.00
    # SEQ A    7 ILE :    0.00
    # SEQ A    8 LYS :    0.87
    # SEQ A    9 ASP :    1.30
    # SEQ A   10 PHE :   64.55
    # ...
    # \n EOF
    if self.contains_hydrogen():
        include_hydrogen = ['--hydrogen']  # the addition of hydrogen changes results quite a bit
    else:
        include_hydrogen = []
    cmd = [putils.freesasa_exe_path, f'--format={out_format}', '--probe-radius', str(probe_radius),
           '-c', putils.freesasa_config_path, '--n-threads=2'] + include_hydrogen
    self.log.debug(f'FreeSASA:\n{subprocess.list2cmdline(cmd)}')
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate(input=self.get_atom_record().encode('utf-8'))
    # if err:  # usually results from Hydrogen atoms, silencing
    #     self.log.warning('\n%s' % err.decode('utf-8'))
    sasa_output = out.decode('utf-8').split('\n')
    if_idx = 0
    if atom:
        # slice removes first REMARK, MODEL and final TER, MODEL regardless of # of chains, TER inclusion
        # since return_atom_record doesn't have models, these won't be present and no option to freesasa about model
        # would be provided with above subprocess call
        atoms = self.atoms
        for line_split in map(str.split, sasa_output[5:-2]):  # Does slice remove need for if line[0] == 'ATOM'?
            if line_split[0] == 'ATOM':  # This line appears necessary as MODEL can be added if MODEL is written
                atoms[if_idx].sasa = float(line_split[-1])
                if_idx += 1
    else:
        seq_slice = slice(3)
        sasa_slice = slice(16, None)
        residues = self.residues
        for idx, line in enumerate(sasa_output[1:-1]):  # Does slice remove the need for if line[:3] == 'SEQ'?
            if line[seq_slice] == 'SEQ':  # Doesn't seem that this equality is sufficient ^
                residues[if_idx].sasa = float(line[sasa_slice])
                if_idx += 1
    try:
        self.sasa = sum([residue.sasa for residue in self.residues])
    except RecursionError:
        self.log.error('RecursionError measuring SASA')
        os.makedirs(putils.sasa_debug_dir, exist_ok=True)
        self.write(out_path=os.path.join(putils.sasa_debug_dir, f'SASA-INPUT-{self.name}.pdb'))
        with open(os.path.join(putils.sasa_debug_dir, f'SASA-OUTPUT-{self.name}.pdb'), 'w') as f:
            f.write('%s\n' % '\n'.join(sasa_output))

        raise stutils.DesignError(
            "Measurement of SASA isn't working, probably due to a missing Atom. Debug files written to "
            f'{putils.sasa_debug_dir}')

get_surface_area_residues

get_surface_area_residues(residues: list[Residue] = None, dtype: sasa_types_literal = 'polar', **kwargs) -> float

Get the surface area for specified residues

Parameters:

  • residues (list[Residue], default: None ) –

    The Residues to sum. If not provided, will be retrieved by .get_residues()

  • dtype (sasa_types_literal, default: 'polar' ) –

    The type of area classification to query.

Other Parameters:

  • atom

    bool = True - Whether the output should be generated for each atom. If False, will be generated for each Residue

  • probe_radius

    float = 1.4 - The radius which surface area should be generated

  • numbers

    Container[int] = None – Residue numbers of interest

  • indices

    Iterable[int] = None – Residue indices of interest for the Structure

Returns:

  • float

    Angstrom^2 of surface area

Source code in symdesign/structure/base.py
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
def get_surface_area_residues(
    self, residues: list[Residue] = None, dtype: sasa_types_literal = 'polar', **kwargs
) -> float:
    """Get the surface area for specified residues

    Args:
        residues: The Residues to sum. If not provided, will be retrieved by `.get_residues()`
        dtype: The type of area classification to query.

    Keyword Args:
        atom: bool = True - Whether the output should be generated for each atom.
            If False, will be generated for each Residue
        probe_radius: float = 1.4 - The radius which surface area should be generated
        numbers: Container[int] = None – Residue numbers of interest
        indices: Iterable[int] = None – Residue indices of interest for the Structure

    Returns:
        Angstrom^2 of surface area
    """
    if not self.sasa:
        self.get_sasa(**kwargs)

    if not residues:
        residues = self.get_residues(**kwargs)

    sasa_dtype = f'sasa_{dtype}'
    try:
        return sum([getattr(residue, sasa_dtype) for residue in residues])
    except AttributeError:
        raise ValueError(
            f" {dtype=} is an invalid 'sasa_dtype'. Viable types are {', '.join(sasa_types)}"
        )

errat

errat(out_path: AnyStr = os.getcwd()) -> tuple[float, ndarray]

Find the overall and per residue Errat accuracy for the given Structure

Parameters:

  • out_path (AnyStr, default: getcwd() ) –

    The path where Errat files should be written

Returns:

  • tuple[float, ndarray]

    Overall Errat score, Errat value/residue array

Source code in symdesign/structure/base.py
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
def errat(self, out_path: AnyStr = os.getcwd()) -> tuple[float, np.ndarray]:
    """Find the overall and per residue Errat accuracy for the given Structure

    Args:
        out_path: The path where Errat files should be written

    Returns:
        Overall Errat score, Errat value/residue array
    """
    # name = 'errat_input-%s-%d.pdb' % (self.name, random() * 100000)
    # current_struc_file = self.write(out_path=os.path.join(out_path, name))
    # errat_cmd = [putils.errat_exe_path, os.path.splitext(name)[0], out_path]  # for writing file first
    # os.system('rm %s' % current_struc_file)
    out_path = out_path if out_path[-1] == os.sep else out_path + os.sep  # errat needs trailing "/"
    errat_cmd = [putils.errat_exe_path, out_path]  # for passing atoms by stdin
    # p = subprocess.Popen(errat_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    # out, err = p.communicate(input=self.get_atom_record().encode('utf-8'))
    # logger.info(self.get_atom_record()[:120])
    iteration = 1
    all_residue_scores = []
    number_of_residues = self.number_of_residues
    while iteration < 5:
        p = subprocess.run(errat_cmd, input=self.get_atom_record(), encoding='utf-8', capture_output=True)
        all_residue_scores = p.stdout.strip().split('\n')
        # Subtract one due to the addition of overall score
        if len(all_residue_scores) - 1 == number_of_residues:
            break
        iteration += 1

    if iteration == 5:
        error = p.stderr.strip().split('\n')
        self.log.debug(f"{self.errat.__name__} couldn't generate the correct output length. "
                       f'({len(all_residue_scores) - 1}) != number_of_residues ({number_of_residues}). Got stderr:'
                       f'\n{error}')
    # errat_output_file = os.path.join(out_path, '%s.ps' % name)
    # errat_output_file = os.path.join(out_path, 'errat.ps')
    # else:
    # print(subprocess.list2cmdline(['grep', 'Overall quality factor**: ', errat_output_file]))
    # p = subprocess.Popen(['grep', 'Overall quality factor', errat_output_file],
    #                      stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    # errat_out, errat_err = p.communicate()
    try:
        # overall_score = set(errat_out.decode().split('\n'))
        # all_residue_scores = list(map(str.strip, errat_out.split('\n'), 'Residue '))
        # all_residue_scores = errat_out.split('\n')
        overall_score = all_residue_scores.pop(-1)
        return float(overall_score.split()[-1]), \
            np.array([float(score[-1]) for score in map(str.split, all_residue_scores)])
    except (IndexError, AttributeError, ValueError):  # ValueError when returning text instead of float
        self.log.warning(f'{self.name}: Failed to generate ERRAT measurement. Errat returned: {all_residue_scores}')
        return 0., np.array([0. for _ in range(number_of_residues)])

stride

stride(to_file: AnyStr = None, **kwargs)

Calculates the secondary structure using the program Stride

Args to_file: The location of a file to save the Stride output

Sets

Each contained Residue instance .secondary_structure attribute

Source code in symdesign/structure/base.py
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
def stride(self, to_file: AnyStr = None, **kwargs):
    """Calculates the secondary structure using the program Stride

    Args
        to_file: The location of a file to save the Stride output

    Sets:
        Each contained Residue instance `.secondary_structure` attribute
    """
    # REM  -------------------- Secondary structure summary -------------------  XXXX
    # REM                .         .         .         .         .               XXXX
    # SEQ  1    IVQQQNNLLRAIEAQQHLLQLTVWGIKQLQAGGWMEWDREINNYTSLIHS   50          XXXX
    # STR       HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH  HHHHHHHHHHHHHHHHH               XXXX
    # REM                                                                        XXXX
    # SEQ  51   LIEESQN                                              57          XXXX
    # STR       HHHHHH                                                           XXXX
    # REM                                                                        XXXX
    # LOC  AlphaHelix   ILE     3 A      ALA     33 A                            XXXX
    # LOC  AlphaHelix   TRP    41 A      GLN     63 A                            XXXX
    # REM                                                                        XXXX
    # REM  --------------- Detailed secondary structure assignment-------------  XXXX
    # REM                                                                        XXXX
    # REM  |---Residue---|    |--Structure--|   |-Phi-|   |-Psi-|  |-Area-|      XXXX
    # ASG  ILE A    3    1    H    AlphaHelix    360.00    -29.07     180.4      XXXX
    # ASG  VAL A    4    2    H    AlphaHelix    -64.02    -45.93      99.8      XXXX
    # ASG  GLN A    5    3    H    AlphaHelix    -61.99    -39.37      82.2      XXXX

    # ASG    Detailed secondary structure assignment
    # Format:
    #  5-8  Residue type
    #  9-10 Protein chain identifier
    #  11-15 PDB residue number
    #  16-20 Ordinal residue number
    #  24-25 One letter secondary structure code **)
    #  26-39 Full secondary structure name
    #  42-49 Phi angle
    #  52-59 Psi angle
    #  61-69 Residue solvent accessible area
    #
    # -rId1Id2..  Read only Chains Id1, Id2 ...
    # -cId1Id2..  Process only Chains Id1, Id2 ...

    # The Stride based secondary structure names of each unique element where possible values are
    #  H:Alpha helix,
    #  G:3-10 helix,
    #  I:PI-helix,
    #  E:Extended conformation,
    #  B/b:Isolated bridge,
    #  T:Turn,
    #  C:Coil (none of the above)'
    current_struc_file = self.write(out_path=f'stride_input-{self.name}-{random() * 100000}.pdb')
    p = subprocess.Popen([putils.stride_exe_path, current_struc_file],
                         stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    out, err = p.communicate()
    struct_file = Path(current_struc_file)
    struct_file.unlink(missing_ok=True)
    # self.log.debug(f'Stride file is at: {current_struc_file}')

    if out:
        if to_file:
            with open(to_file, 'wb') as f:
                f.write(out)
        stride_output = out.decode('utf-8').split('\n')
    else:
        self.log.warning(f'{self.name}: No secondary structure assignment found with Stride')
        return

    residue_idx = count()
    residues = self.residues
    for line in stride_output:
        # residue_idx = int(line[10:15])
        if line[0:3] == 'ASG':
            # residue_idx = int(line[15:20])  # one-indexed, use in Structure version...
            # line[10:15].strip().isdigit():  # residue number -> line[10:15].strip().isdigit():
            # self.chain(line[9:10]).residue(int(line[10:15].strip())).secondary_structure = line[24:25]
            residues[next(residue_idx)].secondary_structure = line[24:25]

    self.secondary_structure = ''.join(residue.secondary_structure for residue in residues)

is_termini_helical

is_termini_helical(termini: termini_literal = 'n', window: int = 5) -> bool

Using assigned secondary structure, probe for helical termini using a segment of 'window' residues. Will remove any disordered residues from the specified termini before checking, with the assumption that the disordered terminal residues are not integral to the structure

Parameters:

  • termini (termini_literal, default: 'n' ) –

    Either 'n' or 'c' should be specified

  • window (int, default: 5 ) –

    The segment size to search

Returns:

  • bool

    True if the specified terminus has a stretch of helical residues the length of the window

Source code in symdesign/structure/base.py
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
def is_termini_helical(self, termini: stutils.termini_literal = 'n', window: int = 5) -> bool:
    """Using assigned secondary structure, probe for helical termini using a segment of 'window' residues. Will
    remove any disordered residues from the specified termini before checking, with the assumption that the
    disordered terminal residues are not integral to the structure

    Args:
        termini: Either 'n' or 'c' should be specified
        window: The segment size to search

    Returns:
        True if the specified terminus has a stretch of helical residues the length of the window
    """
    # Strip "disorder" from the termini, then use the window to compare against the secondary structure
    search_window = window * 2
    if termini in 'Nn':
        term_window = self.secondary_structure.lstrip(SS_DISORDER_IDENTIFIERS)[:search_window]
    elif termini in 'Cc':
        term_window = self.secondary_structure.rstrip(SS_DISORDER_IDENTIFIERS)[-search_window:]
    else:
        raise ValueError(
            f"The termini value {termini} isn't allowed. Must indicate one of {get_args(stutils.termini_literal)}")

    if 'H' * window in term_window:
        return True
    else:
        return False

calculate_secondary_structure

calculate_secondary_structure(**kwargs)

Perform the secondary structure calculation for the Structure using the DEFAULT_SS_PROGRAM

Other Parameters:

  • to_file

    AnyStr = None - The location of a file to save secondary structure calculations

Source code in symdesign/structure/base.py
5283
5284
5285
5286
5287
5288
5289
def calculate_secondary_structure(self, **kwargs):
    """Perform the secondary structure calculation for the Structure using the DEFAULT_SS_PROGRAM

    Keyword Args:
        to_file: AnyStr = None - The location of a file to save secondary structure calculations
    """
    self.__getattribute__(DEFAULT_SS_PROGRAM)(**kwargs)  # self.stride()

termini_proximity_from_reference

termini_proximity_from_reference(termini: termini_literal = 'n', reference: ndarray = utils.symmetry.origin, **kwargs) -> float

Finds the orientation of the termini from the origin (default) or from a reference point

Parameters:

  • termini (termini_literal, default: 'n' ) –

    Either 'n' or 'c' should be specified

  • reference (ndarray, default: origin ) –

    The reference where the point should be measured from

Returns:

  • float

    When compared to the reference, 1 if the termini is more than halfway from the center of the Structure and -1 if the termini is less than halfway from the center of the Structure

Source code in symdesign/structure/base.py
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
def termini_proximity_from_reference(self, termini: stutils.termini_literal = 'n',
                                     reference: np.ndarray = utils.symmetry.origin, **kwargs) -> float:
    """Finds the orientation of the termini from the origin (default) or from a reference point

    Args:
        termini: Either 'n' or 'c' should be specified
        reference: The reference where the point should be measured from

    Returns:
        When compared to the reference, 1 if the termini is more than halfway from the center of the Structure and
            -1 if the termini is less than halfway from the center of the Structure
    """
    if termini == 'n':
        residue_coords = self.residues[0].n_coords
    elif termini == 'c':
        residue_coords = self.residues[-1].c_coords
    else:
        raise ValueError(
            f"'termini' must be either 'n' or 'c', not {termini}")

    if reference is None:
        reference = utils.symmetry.origin

    max_distance = self.distance_from_reference(reference=reference, measure='max')
    min_distance = self.distance_from_reference(reference=reference, measure='min')
    coord_distance = np.linalg.norm(residue_coords - reference)
    if abs(coord_distance - max_distance) < abs(coord_distance - min_distance):
        return 1  # Termini further from the reference
    else:
        return -1  # Termini closer to the reference

get_atom_record

get_atom_record(**kwargs) -> str

Provides the Structure as a 'PDB' formatted string of Atom records

Other Parameters:

  • chain_id

    str = None - The chain ID to use

  • atom_offset

    int = 0 - How much to offset the atom number by. Default returns one-indexed

Returns:

  • str

    The archived .pdb formatted ATOM records for the Structure

Source code in symdesign/structure/base.py
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
def get_atom_record(self, **kwargs) -> str:
    """Provides the Structure as a 'PDB' formatted string of Atom records

    Keyword Args:
        chain_id: str = None - The chain ID to use
        atom_offset: int = 0 - How much to offset the atom number by. Default returns one-indexed

    Returns:
        The archived .pdb formatted ATOM records for the Structure
    """
    return '\n'.join(residue.__str__(**kwargs) for residue in self.residues)

get_fragments

get_fragments(residues: list[Residue] = None, residue_numbers: list[int] = None, fragment_db: FragmentDatabase = None, **kwargs) -> list[MonoFragment]

From the Structure, find Residues with a matching fragment type as identified in a fragment library

Parameters:

  • residues (list[Residue], default: None ) –

    The specific Residues to search for

  • residue_numbers (list[int], default: None ) –

    The specific residue numbers to search for

  • fragment_db (FragmentDatabase, default: None ) –

    The FragmentDatabase with representative fragment types to query against

Returns:

  • list[MonoFragment]

    The MonoFragments found on the Structure

Source code in symdesign/structure/base.py
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
def get_fragments(self, residues: list[Residue] = None, residue_numbers: list[int] = None,
                  fragment_db: fragment.db.FragmentDatabase = None, **kwargs) -> list[fragment.MonoFragment]:
    """From the Structure, find Residues with a matching fragment type as identified in a fragment library

    Args:
        residues: The specific Residues to search for
        residue_numbers: The specific residue numbers to search for
        fragment_db: The FragmentDatabase with representative fragment types  to query against

    Returns:
        The MonoFragments found on the Structure
    """
    if not residues and not residue_numbers:
        return []

    if fragment_db is None:
        fragment_db = self.fragment_db
        if fragment_db is None:
            raise ValueError("Can't assign fragments without passing 'fragment_db' or setting .fragment_db")
        self.log.warning(f"Without passing 'fragment_db', using the existing .fragment_db={repr(fragment_db)}")

    try:
        fragment_db.representatives
    except AttributeError:
        raise TypeError(
            f"The passed fragment_db is not of the required type "
            f"'{fragment.db.FragmentDatabase.__class__.__name__}'")

    fragment_length = fragment_db.fragment_length
    fragment_range = range(*fragment_db.fragment_range)
    fragments = []
    for residue_number in residue_numbers:
        frag_residues = self.get_residues(numbers=[residue_number + i for i in fragment_range])

        if len(frag_residues) == fragment_length:
            new_fragment = fragment.MonoFragment(residues=frag_residues, fragment_db=fragment_db, **kwargs)
            if new_fragment.i_type:
                fragments.append(new_fragment)

    return fragments

get_fragment_residues

get_fragment_residues(residues: list[Residue] = None, residue_numbers: list[int] = None, fragment_db: FragmentDatabase = None, rmsd_thresh: float = fragment.Fragment.rmsd_thresh, **kwargs) -> list | list[Residue]

Assigns a Fragment type to Residue instances identified from a FragmentDatabase, and returns them

Parameters:

  • residues (list[Residue], default: None ) –

    The specific Residues to search for

  • residue_numbers (list[int], default: None ) –

    The specific residue numbers to search for

  • fragment_db (FragmentDatabase, default: None ) –

    The FragmentDatabase with representative fragment types to query the Residue against

  • rmsd_thresh (float, default: rmsd_thresh ) –

    The threshold for which a rmsd should fail to produce a fragment match

Sets

Each Fragment Residue instance self.guide_coords, self.i_type

Returns:

  • list | list[Residue]

    The Residue instances that match Fragment representatives from the Structure

Source code in symdesign/structure/base.py
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
def get_fragment_residues(self, residues: list[Residue] = None, residue_numbers: list[int] = None,
                          fragment_db: fragment.db.FragmentDatabase = None,
                          rmsd_thresh: float = fragment.Fragment.rmsd_thresh, **kwargs) -> list | list[Residue]:
    """Assigns a Fragment type to Residue instances identified from a FragmentDatabase, and returns them

    Args:
        residues: The specific Residues to search for
        residue_numbers: The specific residue numbers to search for
        fragment_db: The FragmentDatabase with representative fragment types to query the Residue against
        rmsd_thresh: The threshold for which a rmsd should fail to produce a fragment match

    Sets:
        Each Fragment Residue instance self.guide_coords, self.i_type

    Returns:
        The Residue instances that match Fragment representatives from the Structure
    """
    if fragment_db is None:
        fragment_db = self.fragment_db
        if fragment_db is None:
            raise ValueError("Can't assign fragments without passing 'fragment_db' or setting .fragment_db")
        self.log.warning(f"Without passing 'fragment_db', using the existing .fragment_db={repr(fragment_db)}")

    try:
        fragment_db.representatives
    except AttributeError:
        raise TypeError(
            f"The passed fragment_db is not of the required type "
            f"'{fragment.db.FragmentDatabase.__class__.__name__}'")

    if residue_numbers is not None:
        residues = self.get_residues(numbers=residue_numbers)

    # Get iterable of residues
    residues = self.residues if residues is None else residues

    # Get neighboring ca coords on each side by retrieving flanking residues. If not fragment_length, remove
    fragment_length = fragment_db.fragment_length
    frag_lower_range, frag_upper_range = fragment_db.fragment_range

    # Iterate over the residues in reverse to remove any indices that are missing and convert to coordinates
    viable_residues = []
    residues_ca_coords = []
    for residue in residues:
        residue_set = \
            residue.get_upstream(frag_lower_range) + [residue] + residue.get_downstream(frag_upper_range-1)
        if len(residue_set) == fragment_length:
            residues_ca_coords.append([residue.ca_coords for residue in residue_set])
            viable_residues.append(residue)

    residue_ca_coords = np.array(residues_ca_coords)

    # Solve for fragment type (secondary structure classification could be used too)
    found_fragments = []
    for idx, residue in enumerate(viable_residues):
        min_rmsd = float('inf')
        residue_ca_coord_set = residue_ca_coords[idx]
        for fragment_type, representative in fragment_db.representatives.items():
            rmsd, rot, tx = superposition3d(residue_ca_coord_set, representative.ca_coords)
            if rmsd <= rmsd_thresh and rmsd <= min_rmsd:
                residue.frag_type = fragment_type
                min_rmsd = rmsd

        if residue.frag_type:
            residue.fragment_db = fragment_db
            residue._fragment_coords = fragment_db.representatives[residue.frag_type].backbone_coords
            found_fragments.append(residue)

    return found_fragments

find_fragments

find_fragments(fragment_db: FragmentDatabase = None, **kwargs) -> list[tuple[GhostFragment, Fragment, float]]

Search Residue instances to find Fragment instances that are neighbors, returning all Fragment pairs. By default, returns all Residue instances neighboring FragmentResidue instances

Parameters:

  • fragment_db (FragmentDatabase, default: None ) –

    The FragmentDatabase with representative fragment types to query the Residue against

Other Parameters:

  • residues

    list[Residue] = None - The specific Residues to search for

  • residue_numbers

    list[int] = None - The specific residue numbers to search for

  • rmsd_thresh

    float = fragment.Fragment.rmsd_thresh - The threshold for which a rmsd should fail to produce a fragment match

  • distance

    float = 8.0 - The distance to query for neighboring fragments

  • min_match_value

    float = 2 - The minimum value which constitutes an acceptable fragment z_score

  • clash_coords

    np.ndarray = None – The coordinates to use for checking for GhostFragment clashes

Returns:

  • list[tuple[GhostFragment, Fragment, float]]

    The GhostFragment, Fragment pairs, along with their match score

Source code in symdesign/structure/base.py
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
def find_fragments(self, fragment_db: fragment.db.FragmentDatabase = None, **kwargs) \
        -> list[tuple[fragment.GhostFragment, fragment.Fragment, float]]:
    """Search Residue instances to find Fragment instances that are neighbors, returning all Fragment pairs.
    By default, returns all Residue instances neighboring FragmentResidue instances

    Args:
        fragment_db: The FragmentDatabase with representative fragment types to query the Residue against

    Keyword Args:
        residues: list[Residue] = None - The specific Residues to search for
        residue_numbers: list[int] = None - The specific residue numbers to search for
        rmsd_thresh: float = fragment.Fragment.rmsd_thresh - The threshold for which a rmsd should fail to produce
            a fragment match
        distance: float = 8.0 - The distance to query for neighboring fragments
        min_match_value: float = 2 - The minimum value which constitutes an acceptable fragment z_score
        clash_coords: np.ndarray = None – The coordinates to use for checking for GhostFragment clashes

    Returns:
        The GhostFragment, Fragment pairs, along with their match score
    """
    if fragment_db is None:
        fragment_db = self.fragment_db
        if fragment_db is None:
            raise ValueError("Can't assign fragments without passing 'fragment_db' or setting .fragment_db")
        self.log.warning(f"Without passing 'fragment_db', using the existing .fragment_db={repr(fragment_db)}")

    fragment_time_start = time.time()
    frag_residues = self.get_fragment_residues(fragment_db=fragment_db, **kwargs)
    self.log.info(f'Found {len(frag_residues)} fragments on {self.name}')

    frag_residue_indices = [residue.index for residue in frag_residues]
    all_fragment_pairs = []
    for frag_residue in frag_residues:
        # frag_neighbors = frag_residue.get_residue_neighbors(**kwargs)
        neighbors = self.get_residues_by_atom_indices(frag_residue.neighboring_atom_indices(**kwargs))
        # THIS GETS NON-SELF FRAGMENTS TOO
        # frag_neighbors = [residue for residue in neighbors if residue.frag_type]
        # if not frag_neighbors:
        #     continue
        frag_neighbors = [residue for residue in neighbors if residue.index in frag_residue_indices]
        if not frag_neighbors:
            continue
        all_fragment_pairs.extend(fragment.find_fragment_overlap([frag_residue], frag_neighbors, **kwargs))

    self.log.debug(f'Took {time.time() - fragment_time_start:.8f}s')
    return all_fragment_pairs

spatial_aggregation_propensity_per_residue

spatial_aggregation_propensity_per_residue(distance: float = 5.0, **kwargs) -> list[float]

Calculate the spatial aggregation propensity on a per-residue basis using calculated heavy atom contacts to define which Residue instances are in contact.

Caution: Contrasts with published method due to use of relative sasa for each Residue instance instead of relative sasa for each Atom instance

Parameters:

  • distance (float, default: 5.0 ) –

    The distance in angstroms to measure Atom instances in contact

Other Parameters:

  • probe_radius

    float = 1.4 - The radius which surface area should be generated

Returns:

  • list[float]

    The floats representing the spatial aggregation propensity for each Residue in the Structure

Source code in symdesign/structure/base.py
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
def spatial_aggregation_propensity_per_residue(self, distance: float = 5., **kwargs) -> list[float]:
    """Calculate the spatial aggregation propensity on a per-residue basis using calculated heavy atom contacts to
    define which Residue instances are in contact.

    Caution: Contrasts with published method due to use of relative sasa for each Residue instance instead of
    relative sasa for each Atom instance

    Args:
        distance: The distance in angstroms to measure Atom instances in contact

    Keyword Args:
        probe_radius: float = 1.4 - The radius which surface area should be generated

    Returns:
        The floats representing the spatial aggregation propensity for each Residue in the Structure
    """
    # SASA Keyword args that are not reported as available
    # atom: bool = True - Whether the output should be generated for each atom.
    #     If False, will be generated for each Residue
    if not self.sasa:
        self.get_sasa(**kwargs)
    # Set up the hydrophobicity parameters
    hydrophobicity_ = hydrophobicity_values_glycine_centered['black_and_mould']
    # Get heavy Atom coordinates
    heavy_coords = self.heavy_coords
    # Make and query a tree
    tree = BallTree(heavy_coords)
    query = tree.query_radius(heavy_coords, distance)

    residues = self.residues
    # In case this was already called, all should be set to 0.0
    for residue in residues:
        residue.spatial_aggregation_propensity = 0.
        # Set the hydrophobicity_ attribute in a first pass to reduce repetitive lookups
        residue.hydrophobicity_ = hydrophobicity_[residue.type]

    heavy_atom_coords_indexed_residues = self.heavy_coords_indexed_residues
    contacting_pairs = set((heavy_atom_coords_indexed_residues[idx1], heavy_atom_coords_indexed_residues[idx2])
                           for idx2, contacts in enumerate(query.tolist()) for idx1 in contacts.tolist())
    # Residue.spatial_aggregation_propensity starts as 0., so we are adding any observation to that attribute
    for residue1, residue2 in contacting_pairs:
        # Multiply suggested hydrophobicity value by the Residue.relative_sasa
        # Only set on residue1 as this is the "center" of the calculation
        residue1.spatial_aggregation_propensity = residue2.hydrophobicity_ * residue2.relative_sasa

    return [residue.spatial_aggregation_propensity for residue in residues]

contact_order_per_residue

contact_order_per_residue(sequence_distance_cutoff: int = 2, distance: float = 6.0) -> list[float]

Calculate the contact order on a per-residue basis using calculated heavy atom contacts

Parameters:

  • sequence_distance_cutoff (int, default: 2 ) –

    The residue spacing required to count a contact as a true contact

  • distance (float, default: 6.0 ) –

    The distance in angstroms to measure Atom instances in contact

Returns:

  • list[float]

    The floats representing the contact order for each Residue in the Structure

Source code in symdesign/structure/base.py
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
def contact_order_per_residue(self, sequence_distance_cutoff: int = 2, distance: float = 6.) -> list[float]:
    """Calculate the contact order on a per-residue basis using calculated heavy atom contacts

    Args:
        sequence_distance_cutoff: The residue spacing required to count a contact as a true contact
        distance: The distance in angstroms to measure Atom instances in contact

    Returns:
        The floats representing the contact order for each Residue in the Structure
    """
    # Get heavy Atom coordinates
    heavy_coords = self.heavy_coords
    # Make and query a tree
    tree = BallTree(heavy_coords)
    query = tree.query_radius(heavy_coords, distance)

    residues = self.residues
    # In case this was already called, we should set all to 0.0
    for residue in residues:
        residue.contact_order = 0.

    heavy_atom_coords_indexed_residues = self.heavy_coords_indexed_residues
    contacting_pairs = set((heavy_atom_coords_indexed_residues[idx1], heavy_atom_coords_indexed_residues[idx2])
                           for idx2, contacts in enumerate(query.tolist()) for idx1 in contacts.tolist())
    # Residue.contact_order starts as 0., so we are adding any observation to that attribute
    for residue1, residue2 in contacting_pairs:
        # Calculate using number since index might not actually specify the intended distance
        residue_sequence_distance = abs(residue1.number - residue2.number)
        if residue_sequence_distance >= sequence_distance_cutoff:
            # Only set on residue1 so that we don't overcount
            residue1.contact_order += residue_sequence_distance

    number_residues = len(residues)
    for residue in residues:
        residue.contact_order /= number_residues

    return [residue.contact_order for residue in residues]

format_resfile_from_directives

format_resfile_from_directives(residue_directives: dict[int | Residue, str], include: dict[int | Residue, set[str]] = None, background: dict[int | Residue, set[str]] = None, **kwargs) -> list[str]

Format Residue mutational potentials given Residues/residue numbers and corresponding mutation directive. Optionally, include specific amino acids and limit to a specific background. Both dictionaries accessed by same keys as residue_directives

Parameters:

  • residue_directives (dict[int | Residue, str]) –

    {Residue object: 'mutational_directive', ...}

  • include (dict[int | Residue, set[str]], default: None ) –

    Include a set of specific amino acids for each residue

  • background (dict[int | Residue, set[str]], default: None ) –

    The background amino acids to compare possibilities against

Other Parameters:

  • special

    bool = False - Whether to include special residues

Returns:

  • list[str]

    For each Residue, returns the string formatted for a resfile with a 'PIKAA' and amino acid type string

Source code in symdesign/structure/base.py
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
def format_resfile_from_directives(self, residue_directives: dict[int | Residue, str],
                                   include: dict[int | Residue, set[str]] = None,
                                   background: dict[int | Residue, set[str]] = None, **kwargs) -> list[str]:
    """Format Residue mutational potentials given Residues/residue numbers and corresponding mutation directive.
    Optionally, include specific amino acids and limit to a specific background. Both dictionaries accessed by same
    keys as residue_directives

    Args:
        residue_directives: {Residue object: 'mutational_directive', ...}
        include: Include a set of specific amino acids for each residue
        background: The background amino acids to compare possibilities against

    Keyword Args:
        special: bool = False - Whether to include special residues

    Returns:
        For each Residue, returns the string formatted for a resfile with a 'PIKAA' and amino acid type string
    """
    if background is None:
        background = {}
    if include is None:
        include = {}

    res_file_lines = []
    residues = self.residues
    for residue_index, directive in residue_directives.items():
        if isinstance(residue_index, Residue):
            residue = residue_index
            residue_index = residue.index
        else:
            residue = residues[residue_index]

        allowed_aas = residue.mutation_possibilities_from_directive(
            directive, background=background.get(residue_index), **kwargs)
        allowed_aas = {protein_letters_3to1_extended[aa] for aa in allowed_aas}
        allowed_aas = allowed_aas.union(include.get(residue_index, {}))
        res_file_lines.append(f'{residue.number} {residue.chain_id} PIKAA {"".join(sorted(allowed_aas))}')

    return res_file_lines

make_resfile

make_resfile(residue_directives: dict[Residue | int, str], out_path: AnyStr = os.getcwd(), header: list[str] = None, **kwargs) -> AnyStr

Format a resfile for the Rosetta Packer from Residue mutational directives

Parameters:

  • residue_directives (dict[Residue | int, str]) –

    {Residue/int: 'mutational_directive', ...}

  • out_path (AnyStr, default: getcwd() ) –

    Directory to write the file

  • header (list[str], default: None ) –

    A header to constrain all Residues for packing

Other Parameters:

  • include

    dict[Residue | int, set[str]] = None - Include a set of specific amino acids for each residue

  • background

    dict[Residue | int, set[str]] = None - The background amino acids to compare possibilities

  • special

    bool = False - Whether to include special residues

Returns:

  • AnyStr

    The path to the resfile

Source code in symdesign/structure/base.py
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
def make_resfile(self, residue_directives: dict[Residue | int, str], out_path: AnyStr = os.getcwd(),
                 header: list[str] = None, **kwargs) -> AnyStr:
    """Format a resfile for the Rosetta Packer from Residue mutational directives

    Args:
        residue_directives: {Residue/int: 'mutational_directive', ...}
        out_path: Directory to write the file
        header: A header to constrain all Residues for packing

    Keyword Args:
        include: dict[Residue | int, set[str]] = None - Include a set of specific amino acids for each residue
        background: dict[Residue | int, set[str]] = None - The background amino acids to compare possibilities
        special: bool = False - Whether to include special residues

    Returns:
        The path to the resfile
    """
    residue_lines = self.format_resfile_from_directives(residue_directives, **kwargs)
    res_file = os.path.join(out_path, f'{self.name}.resfile')
    with open(res_file, 'w') as f:
        # Format the header
        f.write('%s\n' % ('\n'.join(header + ['start']) if header else 'start'))
        # Start the body
        f.write('%s\n' % '\n'.join(residue_lines))

    return res_file

set_b_factor_by_attribute

set_b_factor_by_attribute(dtype: residue_attributes_literal)

Set the b-factor entry for every Residue to a Residue attribute

Parameters:

  • dtype (residue_attributes_literal) –

    The attribute of interest

Source code in symdesign/structure/base.py
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
def set_b_factor_by_attribute(self, dtype: residue_attributes_literal):
    """Set the b-factor entry for every Residue to a Residue attribute

    Args:
        dtype: The attribute of interest
    """
    if isinstance(dtype, str):
        # self.set_residues_attributes(b_factor=dtype)
        for residue in self.residues:
            residue.b_factor = getattr(residue, dtype)
    else:
        raise TypeError(
            f"The type '{dtype.__class__.__name__}' isn't a string. To {self.set_b_factor_by_attribute.__name__}, "
            "you must provide 'dtype' as a string specifying a Residue attribute")

set_b_factor_data

set_b_factor_data(values: Iterable[float])

Set the b-factor entry for every Residue to a value from an array-like

Parameters:

  • values (Iterable[float]) –

    Array-like of integer types to set each Residue instance 'b_factor' attribute to

Source code in symdesign/structure/base.py
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
def set_b_factor_data(self, values: Iterable[float]):
    """Set the b-factor entry for every Residue to a value from an array-like

    Args:
        values: Array-like of integer types to set each Residue instance 'b_factor' attribute to
    """
    if isinstance(values, Iterable):
        values = list(values)
        if len(values) != self.number_of_residues:
            raise ValueError(
                f"Can't provide a array-like of values with length {len(values)} != {self.number_of_residues}, the "
                "number of residues")
        for residue, value in zip(self.residues, values):
            residue.b_factor = value
    else:
        raise TypeError(
            f"The type '{values.__class__.__name__}' isn't an Iterable. To {self.set_b_factor_data.__name__}, you "
            "must provide the 'values' as an Iterable of integer type with length = number_of_residues")

Structures

Structures(structures: Iterable[ContainsResidues], dtype: str = None, **kwargs)

Bases: ContainsResidues, UserList

A view of a set of Structure instances. This isn't used at the moment

Parameters:

  • structures (Iterable[ContainsResidues]) –

    The Iterable of Structure to set the Structures with

  • dtype (str, default: None ) –

    If an empty Structures, the specific subclass of Structure that Structures contains

Source code in symdesign/structure/base.py
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
def __init__(self, structures: Iterable[ContainsResidues], dtype: str = None, **kwargs):
    """Pass the parent Structure with parent= to initialize .log, .coords, .atoms, and .residues

    Args:
        structures: The Iterable of Structure to set the Structures with
        dtype: If an empty Structures, the specific subclass of Structure that Structures contains
    """
    super().__init__(initlist=structures, **kwargs)  # initlist sets UserList.data to Iterable[Structure]
    raise NotImplementedError("This class isn't functional yet")
    if self.is_parent():
        raise stutils.ConstructionError(
            f"Couldn't create {Structures.__name__} without passing 'parent' argument"
        )

    if not self.data:  # Set up an empty Structures
        self.dtype = dtype if dtype else 'Structure'
    elif all([True if isinstance(structure, ContainsResidues) else False for structure in self]):
        # self.data = [structure for structure in structures]
        self._atom_indices = []
        for structure in self:
            self._atom_indices.extend(structure.atom_indices)
        self._residue_indices = []
        for structure in self:
            self._residue_indices.extend(structure.residue_indices)

        self.dtype = dtype if dtype else type(self.data[0]).__name__
    else:
        raise ValueError(
            f"Can't set {self.__class__.__name__} by passing '{', '.join(type(structure) for structure in self)}, "
            f'must set with type [Structure, ...] or an empty constructor. Ex: Structures()')

    # Overwrite attributes in Structure
    self.name = f'{self.parent.name}-{dtype}Selection'

dtype instance-attribute

dtype: str

The type of Structure in instance

structures property

structures: list[ContainsResidues]

Returns the underlying data in Structures

parse_seqres

parse_seqres(seqres_lines: list[str]) -> dict[str, str]

Convert SEQRES information to single amino acid dictionary format

Parameters:

  • seqres_lines (list[str]) –

    The list of lines containing SEQRES information

Returns:

  • dict[str, str]

    The mapping of each chain to its reference sequence

Source code in symdesign/structure/base.py
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
def parse_seqres(seqres_lines: list[str]) -> dict[str, str]:  # list[str]:
    """Convert SEQRES information to single amino acid dictionary format

    Args:
        seqres_lines: The list of lines containing SEQRES information

    Returns:
        The mapping of each chain to its reference sequence
    """
    # SEQRES   1 A  182  THR THR ALA SER THR SER GLN VAL ARG GLN ASN TYR HIS
    # SEQRES   2 A  182  GLN ASP SER GLU ALA ALA ILE ASN ARG GLN ILE ASN LEU
    # SEQRES   3 A  182  GLU LEU TYR ALA SER TYR VAL TYR LEU SER MET SER TYR
    # SEQRES ...
    # SEQRES  16 C  201  SER TYR ILE ALA GLN GLU
    # In order to account for MultiModel files where the chain names are all the same, using the parsed order
    # instead of a dictionary as later entries would overwrite earlier ones making them inaccurate
    # If the file is screwed up in that it has chains in a different order than the seqres, then this wouldn't work
    # I am opting for the standard .pdb file format and if it is messed up this is the users problem
    reference_sequence = {}
    for line in seqres_lines:
        chain, length, *sequence = line.split()
        if chain in reference_sequence:
            reference_sequence[chain].extend(list(sequence))
        else:
            reference_sequence[chain] = list(sequence)

    # Format the sequences as a one AA letter list
    reference_sequences = {}  # []
    for chain, sequence in reference_sequence.items():
        # Ensure we parse selenomethionine correctly
        one_letter_sequence = [protein_letters_3to1_extended_mse.get(aa, '-')
                               for aa in sequence]
        reference_sequences[chain] = ''.join(one_letter_sequence)
        # reference_sequences.append(''.join(one_letter_sequence))

    return reference_sequences

read_pdb_file

read_pdb_file(file: AnyStr = None, pdb_lines: Iterable[str] = None, separate_coords: bool = True, **kwargs) -> dict[str, Any]

Reads .pdb file and returns structural information pertaining to parsed file

By default, returns the coordinates as a separate numpy.ndarray which is parsed directly by StructureBase. This will be associated with each Atom however, separate parsing is done for efficiency. To include coordinate info with the individual Atom instances, pass separate_coords=False. (Not recommended)

Parameters:

  • file (AnyStr, default: None ) –

    The path to the file to parse

  • pdb_lines (Iterable[str], default: None ) –

    If lines are already read, provide the lines instead

  • separate_coords (bool, default: True ) –

    Whether to separate parsed coordinates from Atom instances. Will be returned as two separate entries in the parsed dictionary, otherwise returned with coords=None

Returns:

  • dict[str, Any]

    The dictionary containing all the parsed structural information

Source code in symdesign/structure/base.py
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
def read_pdb_file(file: AnyStr = None, pdb_lines: Iterable[str] = None, separate_coords: bool = True, **kwargs) -> \
        dict[str, Any]:
    """Reads .pdb file and returns structural information pertaining to parsed file

    By default, returns the coordinates as a separate numpy.ndarray which is parsed directly by StructureBase. This will
    be associated with each Atom however, separate parsing is done for efficiency. To include coordinate info with the
    individual Atom instances, pass separate_coords=False. (Not recommended)

    Args:
        file: The path to the file to parse
        pdb_lines: If lines are already read, provide the lines instead
        separate_coords: Whether to separate parsed coordinates from Atom instances. Will be returned as two separate
            entries in the parsed dictionary, otherwise returned with coords=None

    Returns:
        The dictionary containing all the parsed structural information
    """
    if pdb_lines:
        # path, extension = None, None
        assembly: str | None = None
        name = None
    elif file is not None:
        with open(file, 'r') as f:
            pdb_lines = f.readlines()
        path, extension = os.path.splitext(file)
        name = os.path.basename(path)

        if extension[-1].isdigit():
            # If last character is not a letter, then the file is an assembly, or the extension was provided weird
            assembly: str | None = extension.translate(utils.keep_digit_table)
        else:
            assembly = None
    else:
        raise ValueError(
            f"{read_pdb_file.__name__}: Must provide the argument 'file' or 'pdb_lines'")

    # type to info index:   1    2    3    4    5    6    7     11     12   13   14
    # eventual type:      int, str, str, str, str, int, str, float, float, str, str]] = []
    temp_info: list[tuple[str, str, str, str, str, str, str, str, str, str, str]] = []
    # type to info index:   1    2    3    4    5    6    7 8,9,10     11     12   13   14
    # fields w/ coords   [int, str, str, str, str, int, str, float, float, float, str, str]
    coords: list[list[float]] = []
    cryst_record: str = None
    dbref: dict[str, dict[str, str]] = {}
    entity_info: dict[str, dict[str, dict | list | str]] = {}
    header: list = []
    resolution: float | None = None
    seq_res_lines: list[str] = []
    biomt = []

    entity = None
    current_operation = -1
    alt_loc_str = ' '
    # for line_tokens in map(str.split, pdb_lines):
    #     # 0       1       2          3             4             5      6               7                   8  9
    #     # remark, number, atom_type, alt_location, residue_type, chain, residue_number, code_for_insertion, x, y,
    #     #     10 11   12         13       14
    #     #     z, occ, temp_fact, element, charge = \
    #     #     line[6:11].strip(), int(line[6:11]), line[12:16].strip(), line[16:17].strip(), line[17:20].strip(),
    #     #     line[21:22], int(line[22:26]), line[26:27].strip(), float(line[30:38]), float(line[38:46]), \
    #     #     float(line[46:54]), float(line[54:60]), float(line[60:66]), line[76:78].strip(), line[78:80].strip()
    for line in pdb_lines:
        remark = line[slice_remark]
        if remark == 'ATOM  ' or line[slice_residue_type] == 'MSE' and remark == 'HETATM':
            # if remove_alt_location and alt_location not in ['', 'A']:
            if line[slice_alt_location] not in [alt_loc_str, 'A']:
                continue
            # number = int(line[slice_number])
            residue_type = line[slice_residue_type].strip()
            if residue_type == 'MSE':
                residue_type = 'MET'
                atom_type = line[slice_atom_type].strip()
                if atom_type == 'SE':
                    atom_type = 'SD'  # change type from Selenium to Sulfur delta
            else:
                atom_type = line[slice_atom_type].strip()
            # prepare line information for population of Atom objects
            temp_info.append((line[slice_number], atom_type, alt_loc_str, residue_type, line[slice_chain],
                              line[slice_residue_number], line[slice_code_for_insertion].strip(),
                              line[slice_occ], line[slice_temp_fact],
                              line[slice_element].strip(), line[slice_charge].strip()))
            # temp_info.append((int(line[slice_number]), atom_type, alt_loc_str, residue_type, line[slice_chain],
            #                   int(line[slice_residue_number]), line[slice_code_for_insertion].strip(),
            #                   float(line[slice_occ]), float(line[slice_temp_fact]),
            #                   line[slice_element].strip(), line[slice_charge].strip()))
            # Prepare the atomic coordinates for addition to numpy array
            coords.append([float(line[slice_x]), float(line[slice_y]), float(line[slice_z])])
        elif remark == 'SEQRES':
            seq_res_lines.append(line[11:])
        elif remark == 'REMARK':
            header.append(line.strip())
            remark_number = line[slice_number]
            # elif line[:18] == 'REMARK 350   BIOMT':
            if remark_number == ' 350 ':  # 6:11  '   BIOMT'
                # integration of the REMARK 350 BIOMT
                # REMARK 350
                # REMARK 350 BIOMOLECULE: 1
                # REMARK 350 AUTHOR DETERMINED BIOLOGICAL UNIT: TRIMERIC
                # REMARK 350 SOFTWARE DETERMINED QUATERNARY STRUCTURE: TRIMERIC
                # REMARK 350 SOFTWARE USED: PISA
                # REMARK 350 TOTAL BURIED SURFACE AREA: 6220 ANGSTROM**2
                # REMARK 350 SURFACE AREA OF THE COMPLEX: 28790 ANGSTROM**2
                # REMARK 350 CHANGE IN SOLVENT FREE ENERGY: -42.0 KCAL/MOL
                # REMARK 350 APPLY THE FOLLOWING TO CHAINS: A, B, C
                # REMARK 350   BIOMT1   1  1.000000  0.000000  0.000000        0.00000
                # REMARK 350   BIOMT2   1  0.000000  1.000000  0.000000        0.00000
                # REMARK 350   BIOMT3   1  0.000000  0.000000  1.000000        0.00000
                try:
                    _, _, biomt_indicator, operation_number, x, y, z, tx = line.split()
                except ValueError:  # Not enough values to unpack
                    continue
                if biomt_indicator == 'BIOMT':
                    if operation_number != current_operation:  # Reached a new transformation matrix
                        current_operation = operation_number
                        biomt.append([])
                    # Add the transformation to the current matrix
                    biomt[-1].append(list(map(float, (x, y, z, tx))))
            elif remark_number == '   2 ':  # 6:11 ' RESOLUTION'
                try:
                    resolution = float(line[22:30].strip().split()[0])
                except (IndexError, ValueError):
                    resolution = None
        elif 'DBREF' in remark:
            header.append(line.strip())
            chain = line[12:14].strip().upper()
            if line[5:6] == '2':
                db_accession_id = line[18:40].strip()
            else:
                db = line[26:33].strip()
                if line[5:6] == '1':  # skip grabbing db_accession_id until DBREF2
                    continue
                db_accession_id = line[33:42].strip()
            dbref[chain] = {'db': db, 'accession': db_accession_id}  # implies each chain has only one id
        elif remark == 'COMPND' and 'MOL_ID' in line:
            header.append(line.strip())
            entity = line[line.rfind(':') + 1: line.rfind(';')].strip()
        elif remark == 'COMPND' and 'CHAIN' in line and entity:  # retrieve from standard .pdb file notation
            header.append(line.strip())
            # entity number (starting from 1) = {'chains' : {A, B, C}}
            entity_info[f'{name}_{entity}'] = \
                {'chains': list(map(str.strip, line[line.rfind(':') + 1:].strip().rstrip(';').split(',')))}
            entity = None
        elif remark == 'SCALE ':
            header.append(line.strip())
        elif remark == 'CRYST1':
            header.append(line.strip())
            cryst_record = line  # Don't .strip() so '\n' is attached for output
            # uc_dimensions, space_group = parse_cryst_record(cryst_record)
            # cryst = {'space': space_group, 'a_b_c': tuple(uc_dimensions[:3]), 'ang_a_b_c': tuple(uc_dimensions[3:])}

    if not temp_info:
        if file:
            raise ValueError(
                f'The file {file} has no ATOM records')
        else:
            raise ValueError("The provided 'pdb_lines' have no ATOM records")

    # Combine entity_info with the reference_sequence info and dbref info
    if seq_res_lines:
        reference_sequence = parse_seqres(seq_res_lines)
    else:
        reference_sequence = None

    for entity_name, info in entity_info.items():
        # Grab the first chain from the identified chains, and use it to grab the reference sequence
        chain = info['chains'][0]
        try:
            info['reference_sequence'] = reference_sequence[chain]  # Used when parse_seqres returns dict[str, str]
        except TypeError:  # This is None
            pass
        try:
            info['dbref'] = dbref[chain]
        except KeyError:  # Keys are missing
            pass

    # # Convert the incrementing reference sequence to a list of the sequences
    # reference_sequence = list(reference_sequence.values())

    if biomt:
        biomt = np.array(biomt, dtype=float)
        rotation_matrices = biomt[:, :, :3]
        translation_matrices = biomt[:, :, 3:].squeeze()
    else:
        rotation_matrices = translation_matrices = None

    parsed_info = \
        dict(atoms=[Atom.without_coordinates(idx, *info) for idx, info in enumerate(temp_info)]
             if separate_coords else
             # Initialize with individual coords. Not sure why anyone would do this, but include for compatibility
             [Atom(number=int(number), atom_type=atom_type, alt_location=alt_location, residue_type=residue_type,
                   chain_id=chain_id, residue_number=int(residue_number), code_for_insertion=code_for_insertion,
                   coords=coords[idx], occupancy=float(occupancy), b_factor=float(b_factor), element=element,
                   charge=charge)
              for idx, (number, atom_type, alt_location, residue_type, chain_id, residue_number, code_for_insertion,
                        occupancy, b_factor, element, charge)
              in enumerate(temp_info)],
             biological_assembly=assembly,
             rotation_matrices=rotation_matrices,
             translation_matrices=translation_matrices,
             coords=coords if separate_coords else None,
             cryst_record=cryst_record,
             entity_info=entity_info,
             name=name,
             resolution=resolution,
             reference_sequence=reference_sequence,
             )
    # Explicitly overwrite any parsing if argument was passed to caller
    parsed_info.update(**kwargs)
    return parsed_info

read_mmcif_file

read_mmcif_file(file: AnyStr = None, **kwargs) -> dict[str, Any]

Reads .cif file and returns structural information pertaining to parsed file

By default, returns the coordinates as a separate numpy.ndarray which is parsed directly by StructureBase. This will be associated with each Atom however, separate parsing is done for efficiency. To include coordinate info with the individual Atom instances, pass separate_coords=False. (Not recommended)

Parameters:

  • file (AnyStr, default: None ) –

    The path to the file to parse

Returns:

  • dict[str, Any]

    The dictionary containing all the parsed structural information

Source code in symdesign/structure/base.py
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def read_mmcif_file(file: AnyStr = None, **kwargs) -> dict[str, Any]:
    """Reads .cif file and returns structural information pertaining to parsed file

    By default, returns the coordinates as a separate numpy.ndarray which is parsed directly by StructureBase. This will
    be associated with each Atom however, separate parsing is done for efficiency. To include coordinate info with the
    individual Atom instances, pass separate_coords=False. (Not recommended)

    Args:
        file: The path to the file to parse

    Returns:
        The dictionary containing all the parsed structural information
    """
    # if lines:
    #     # path, extension = None, None
    #     assembly: str | None = None
    #     name = None
    # el
    if file is not None:
        path, extension = os.path.splitext(file)
        name = os.path.basename(path)
        ignore_fields = []
        data: dict[str, dict[str, Any]] = cif_reader.read(file, ignore=ignore_fields)
        if extension[-1].isdigit():
            # If last character is not a letter, then the file is an assembly, or the extension was provided weird
            assembly: str | None = extension.translate(utils.keep_digit_table)
        elif 'assembly' in name:
            assembly = name[name.find('assembly'):].translate(utils.keep_digit_table)
        else:
            assembly = None
    else:
        raise ValueError(
            f"{read_mmcif_file.__name__}: Must provide the argument 'file'"
        )

    #  name = kwargs.pop('name', None)
    #  if not name:
    #      name = os.path.basename(os.path.splitext(file)[0])
    #
    #  input(data.keys())
    #  for k, v_ in data.items():
    #      # input(f'{list(v_.keys())}')
    #      # ['_entry', '_audit_conform', '_database_2', '_pdbx_database_PDB_obs_spr', '_pdbx_database_related',
    #      #  '_pdbx_database_status', '_audit_author', '_citation', '_citation_author', '_cell', '_symmetry',
    #      #  '_entity', '_entity_poly', '_entity_poly_seq', '_entity_src_gen', '_struct_ref', '_struct_ref_seq',
    #      #  '_struct_ref_seq_dif', '_chem_comp', '_exptl', '_exptl_crystal', '_exptl_crystal_grow', '_diffrn',
    #      #  '_diffrn_detector', '_diffrn_radiation', '_diffrn_radiation_wavelength', '_diffrn_source', '_reflns',
    #      #  '_reflns_shell', '_refine', '_refine_hist', '_refine_ls_restr', '_refine_ls_shell', '_pdbx_refine',
    #      #  '_struct', '_struct_keywords', '_struct_asym', '_struct_biol', '_struct_conf', '_struct_conf_type',
    #      #  '_struct_mon_prot_cis', '_struct_sheet', '_struct_sheet_order', '_struct_sheet_range',
    #      #  '_pdbx_struct_sheet_hbond', '_atom_sites', '_atom_type', '_atom_site', '_atom_site_anisotrop',
    #      #  '_pdbx_poly_seq_scheme', '_pdbx_struct_assembly', '_pdbx_struct_assembly_gen',
    #      #  '_pdbx_struct_assembly_prop', '_pdbx_struct_oper_list', '_pdbx_audit_revision_history',
    #      #  '_pdbx_audit_revision_details', '_pdbx_audit_revision_group', '_pdbx_refine_tls',
    #      #  '_pdbx_refine_tls_group', '_pdbx_phasing_MR', '_phasing', '_software', '_pdbx_validate_torsion',
    #      #  '_pdbx_unobs_or_zero_occ_atoms', '_pdbx_unobs_or_zero_occ_residues', '_space_group_symop']
    #      for idx, (k, v) in enumerate(v_.items()):
    #          # if k == '_atom_sites':
    #          #     input(v.keys())
    #          # if k in ['_database_2', '_pdbx_database_PDB_obs_spr', '_pdbx_database_related', '_pdbx_database_status']:
    #          #     print('Database key', k)
    #          #     input(v)
    #          # if k in ['_entity', '_entity_poly', '_entity_poly_seq', '_struct_ref']:  # '_entity_src_gen', '_struct_ref_seq'
    #          #     print('Sequence key', k)
    #          #     input(v)
    #          # if k in ['_cell', '_symmetry',
    #          #          # '_space_group_symop'
    #          #          ]:
    #          #     print('Symmetry key', k)
    #          #     input(v)
    #          # if k in ['_reflns', '_reflns_shell', '_refine', '_refine_hist', '_refine_ls_restr', '_refine_ls_shell', '_pdbx_refine',]:
    #          #     print('Diffraction key', k)
    #          #     input(v)
    #          # if k in [
    #          #     # '_struct', '_struct_keywords', '_struct_asym', '_struct_biol',
    #          #     '_pdbx_struct_assembly', '_pdbx_struct_assembly_gen',
    #          #     # '_pdbx_struct_assembly_prop',
    #          #     '_pdbx_struct_oper_list',
    #          # ]:
    #          #     print('struct key', k)
    #          #     input(v)
    #          # if k == '_atom_site':
    #          #     """
    #          #     key group_PDB
    #          #     values ['ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM', 'ATOM']
    #          #     key id
    #          #     values ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    #          #     key type_symbol
    #          #     values ['N', 'C', 'C', 'O', 'C', 'O', 'N', 'C', 'C', 'O']
    #          #     key label_atom_id
    #          #     values ['N', 'CA', 'C', 'O', 'CB', 'OG', 'N', 'CA', 'C', 'O']
    #          #     key label_alt_id
    #          #     values ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']
    #          #     key label_comp_id
    #          #     values ['SER', 'SER', 'SER', 'SER', 'SER', 'SER', 'VAL', 'VAL', 'VAL', 'VAL']
    #          #     key label_asym_id
    #          #     values ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
    #          #     key label_entity_id
    #          #     values ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']
    #          #     key label_seq_id
    #          #     values ['3', '3', '3', '3', '3', '3', '4', '4', '4', '4']
    #          #     key pdbx_PDB_ins_code
    #          #     values ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
    #          #     key Cartn_x
    #          #     values ['25.947', '25.499', '24.208', '23.310', '26.585', '27.819', '24.126', '22.943', '22.353', '23.081']
    #          #     key Cartn_y
    #          #     values ['8.892', '10.149', '9.959', '10.800', '10.734', '10.839', '8.851', '8.533', '7.200', '6.224']
    #          #     key Cartn_z
    #          #     values ['43.416', '42.828', '42.038', '42.084', '41.925', '42.615', '41.310', '40.519', '40.967', '41.152']
    #          #     key occupancy
    #          #     values ['1.00', '1.00', '1.00', '1.00', '1.00', '1.00', '1.00', '1.00', '1.00', '1.00']
    #          #     key B_iso_or_equiv
    #          #     values ['67.99', '79.33', '61.67', '60.15', '81.39', '86.58', '62.97', '56.54', '56.17', '85.78']
    #          #     key pdbx_formal_charge
    #          #     values ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?']
    #          #     key auth_seq_id
    #          #     values ['3', '3', '3', '3', '3', '3', '4', '4', '4', '4']
    #          #     key auth_comp_id
    #          #     values ['SER', 'SER', 'SER', 'SER', 'SER', 'SER', 'VAL', 'VAL', 'VAL', 'VAL']
    #          #     key auth_asym_id
    #          #     values ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
    #          #     key auth_atom_id
    #          #     values ['N', 'CA', 'C', 'O', 'CB', 'OG', 'N', 'CA', 'C', 'O']
    #          #     key pdbx_PDB_model_num
    #          #     values ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']
    #          #     """
    #          #     for k__, v__ in v.items():
    #          #         # ['group_PDB', 'id', 'type_symbol', 'label_atom_id', 'label_alt_id', 'label_comp_id', 'label_asym_id', 'label_entity_id', 'label_seq_id', 'pdbx_PDB_ins_code', 'Cartn_x', 'Cartn_y', 'Cartn_z', 'occupancy', 'B_iso_or_equiv', 'pdbx_formal_charge', 'auth_seq_id', 'auth_comp_id', 'auth_asym_id', 'auth_atom_id', 'pdbx_PDB_model_num']
    #          #         print('key', k__)
    #          #         input(f'values {v__[:10]}')
    #          #     input('DONE')
    #          pass

    provided_dataname, *_ = data.keys()
    if _:
        raise ValueError(
            f"Found multiple values for the cif 'provided_dataname'={_}")

    # Extract the data of interest as saved by the provided_dataname
    data = data[provided_dataname]

    # def format_mmcif_dict(data: dict[str, Any], name: str = None, **kwargs) -> dict:
    atom_data = data.get('_atom_site')
    atom_numbers = atom_data.get('id')
    number_of_atoms = len(atom_numbers)
    atom_types = atom_data.get('label_atom_id')
    alt_locations = atom_data.get('label_alt_id', repeat(' ', number_of_atoms))
    residue_types = atom_data.get('label_comp_id')
    chains = atom_data.get('label_asym_id')
    residue_numbers = atom_data.get('label_seq_id')
    occupancies = atom_data.get('occupancy')
    code_for_insertion = atom_data.get('', repeat(' ', number_of_atoms))
    b_factors = atom_data.get('B_iso_or_equiv')
    element = atom_data.get('type_symbol', repeat(None, number_of_atoms))
    charge = atom_data.get('pdbx_formal_charge', repeat(None, number_of_atoms))
    alt_locations = ''.join(alt_locations).replace('.', ' ')
    code_for_insertion = ''.join(code_for_insertion).replace('.', ' ')
    charge = ''.join(charge).replace('?', ' ')

    atoms = [Atom.without_coordinates(idx, *info) for idx, info in enumerate(
        zip(atom_numbers, atom_types, alt_locations, residue_types, chains, residue_numbers, code_for_insertion,
            occupancies, b_factors, element, charge))]

    coords = np.array([atom_data.get('Cartn_x'),
                       atom_data.get('Cartn_y'),
                       atom_data.get('Cartn_z')], dtype=float).T
    cell_data = data.get('_cell')
    if cell_data:
        # 'length_a': '124.910', 'length_b': '189.250', 'length_c': '376.830',
        # 'angle_alpha': '90.00', 'angle_beta': '90.02', 'angle_gamma': '90.00'
        # Formatted in Hermann-Mauguin notation
        space_group = data.get('_symmetry', {}).get('space_group_name_H-M')
        cryst_record = utils.symmetry.generate_cryst1_record(
            list(map(float, (cell_data['length_a'], cell_data['length_b'], cell_data['length_c'],
                             cell_data['angle_alpha'], cell_data['angle_beta'], cell_data['angle_gamma']))),
            space_group)
    else:
        cryst_record = None

    reflections_data = data.get('_reflns')
    if reflections_data:
        resolution = reflections_data['d_resolution_high']
    else:
        resolution = None

    # _struct_ref
    # Get the cannonical sequence
    entity_data = data.get('_entity_poly')
    db_data = data.get('_struct_ref')
    if db_data:
        # 'db_name': ['UNP', 'UNP'], 'db_code': ['B0BGB0_9BACT', 'Q4Q413_LEIMA'],
        # 'pdbx_db_accession': ['B0BGB0', 'Q4Q413'], 'entity_id': ['1', '2'],
        # 'pdbx_seq_one_letter_code': ['MESVNTSFLSPSLVTIRDFDNGQFAVLRIGRTGFPADKGDIDLCLDKMKGVRDAQQSIGDDTEFGFKGPHIRIRCVDIDD\nKHTYNAMVYVDLIVGTGASEVERETAEELAKEKLRAALQVDIADEHSCVTQFEMKLREELLSSDSFHPDKDEYYKDFL', 'MPVIQTFVSTPLDHHKRENLAQVYRAVTRDVLGKPEDLVMMTFHDSTPMHFFGSTDPVACVRVEALGGYGPSEPEKVTSI\nVTAAITKECGIVADRIFVLYFSPLHCGWNGTNF']
        entity_info = {f'{name}_{entity_id}': {'chains': [],
                                               'reference_sequence': reference_sequence.replace('\n', ''),
                                               'dbref': {'db': db_name, 'accession': db_accession}}
                       for entity_id, reference_sequence, db_name, db_accession in zip(
                db_data.get('entity_id'),
                entity_data.get('pdbx_seq_one_letter_code_can'),  # db_data.get('pdbx_seq_one_letter_code'),
                db_data.get('db_name'), db_data.get('pdbx_db_accession'))
                       }
    else:
        entity_info = {}
    operations = data.get('_pdbx_struct_oper_list')
    if operations:
        biomt = np.array(
            [operations['matrix[1][1]'], operations['matrix[1][2]'], operations['matrix[1][3]'],
             operations['vector[1]'],
             operations['matrix[2][1]'], operations['matrix[2][2]'], operations['matrix[2][3]'],
             operations['vector[2]'],
             operations['matrix[3][1]'], operations['matrix[3][2]'], operations['matrix[3][3]'],
             operations['vector[3]']], dtype=float)
        # print('biomt', biomt)

        if isinstance(operations['id'], list):
            biomt = biomt.T
        biomt = biomt.reshape(-1, 3, 4).tolist()
        # print('biomt', biomt)
    else:
        biomt = None

    # # Separated...
    # rotations = np.array(
    #     [operations['matrix[1][1]'], operations['matrix[1][2]'], operations['matrix[1][3]'],
    #      operations['matrix[2][1]'], operations['matrix[2][2]'], operations['matrix[2][3]'],
    #      operations['matrix[3][1]'], operations['matrix[3][2]'], operations['matrix[3][3]']], dtype=float)
    # translations = np.array([operations['vector[1]'], operations['vector[2]'], operations['vector[3]']],
    #                         dtype=float)
    # print('rotations', rotations)
    # print('translations', translations)
    # if isinstance(operations['id'], list):
    #     # number_of_operations = len(operations['id'])
    #     rotations = rotations.T  # .reshape(-1, 3, 3)
    #     # rotations = rotations.reshape(-1, number_of_operations)
    #     translations = translations.T
    # # else:
    # #     pass
    # translations = translations.reshape(-1, 3)
    # rotations = rotations.reshape(-1, 3, 3)
    #
    # print('rotations', rotations)
    # print('translations', translations)
    # # biomt = rotations, translations

    # reference_sequence = {chain: reference_sequence}
    formatted_info = dict(
        atoms=atoms,
        biological_assembly=assembly,
        biomt=biomt,
        coords=coords,
        # coords=coords if separate_coords else None,
        cryst_record=cryst_record,
        entity_info=entity_info,
        name=name,
        resolution=resolution,
        # reference_sequence=reference_sequence,
    )
    # Explicitly overwrite any parsing if argument was passed to caller
    formatted_info.update(**kwargs)

    return formatted_info