Skip to content

model

MetricsMixin

Bases: ABC

Perform Metric evaluation for derived classes

Subclasses of Metrics must implement _metrics_table property and calculate_metrics() method

metrics property

metrics: _metrics_table

Metrics as sqlalchemy Mapped class. init: Retrieves all metrics, loads sqlalchemy Mapped class

df property

df: Series

Metrics as a Series. init: Retrieves all metrics, loads pd.Series

calculate_metrics abstractmethod

calculate_metrics(**kwargs) -> dict[str, Any]

Perform Metric calculation for the Entity in question

Source code in symdesign/structure/model.py
131
132
133
@abc.abstractmethod
def calculate_metrics(self, **kwargs) -> dict[str, Any]:
    """Perform Metric calculation for the Entity in question"""

clear_metrics

clear_metrics() -> None

Clear all Metrics.state_attributes for the Entity in question

Source code in symdesign/structure/model.py
167
168
169
170
171
172
173
def clear_metrics(self) -> None:
    """Clear all Metrics.state_attributes for the Entity in question"""
    for attr in MetricsMixin.state_attributes:
        try:
            self.__delattr__(attr)
        except AttributeError:
            continue

ParseStructureMixin

Bases: ABC

from_file classmethod

from_file(file: AnyStr, **kwargs)

Create a new Structure from a file with Atom records

Source code in symdesign/structure/model.py
178
179
180
181
182
183
184
185
186
187
188
189
@classmethod
def from_file(cls, file: AnyStr, **kwargs):
    """Create a new Structure from a file with Atom records"""
    if '.pdb' in file:
        return cls.from_pdb(file, **kwargs)
    elif '.cif' in file:
        return cls.from_mmcif(file, **kwargs)
    else:
        raise NotImplementedError(
            f"{cls.__name__}: The file type {os.path.splitext(file)[-1]} isn't supported for parsing. Please use "
            f"the supported types '.pdb' or '.cif'. Alternatively use those constructors instead (ex: from_pdb(), "
            'from_mmcif()) if the file extension is nonsense, but the file format is respected.')

from_pdb classmethod

from_pdb(file: AnyStr, **kwargs)

Create a new Structure from a .pdb formatted file

Source code in symdesign/structure/model.py
191
192
193
194
195
@classmethod
def from_pdb(cls, file: AnyStr, **kwargs):
    """Create a new Structure from a .pdb formatted file"""
    data = read_pdb_file(file, **kwargs)
    return cls._finish(cls(file_path=file, **data))

from_pdb_lines classmethod

from_pdb_lines(pdb_lines: Iterable[str], **kwargs)

Create a new Structure from already parsed .pdb file lines

Source code in symdesign/structure/model.py
197
198
199
200
201
@classmethod
def from_pdb_lines(cls, pdb_lines: Iterable[str], **kwargs):
    """Create a new Structure from already parsed .pdb file lines"""
    data = read_pdb_file(pdb_lines=pdb_lines, **kwargs)
    return cls._finish(cls(**data))

from_mmcif classmethod

from_mmcif(file: AnyStr, **kwargs)

Create a new Structure from a .cif formatted file

Source code in symdesign/structure/model.py
203
204
205
206
207
@classmethod
def from_mmcif(cls, file: AnyStr, **kwargs):
    """Create a new Structure from a .cif formatted file"""
    data = read_mmcif_file(file, **kwargs)
    return cls._finish(cls(file_path=file, **data))

StructuredGeneEntity

StructuredGeneEntity(metadata: ProteinMetadata = None, uniprot_ids: tuple[str, ...] = None, thermophilicity: bool = None, reference_sequence: str = None, **kwargs)

Bases: ContainsResidues, GeneEntity

Implements methods to map a Structure to a GeneEntity

Parameters:

  • metadata (ProteinMetadata, default: None ) –

    Unique database references

  • uniprot_ids (tuple[str, ...], default: None ) –

    The UniProtID(s) that describe this protein sequence

  • thermophilicity (bool, default: None ) –

    The extent to which the sequence is deemed thermophilic

  • reference_sequence (str, default: None ) –

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

Source code in symdesign/structure/model.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(self, metadata: sql.ProteinMetadata = None, uniprot_ids: tuple[str, ...] = None,
             thermophilicity: bool = None, reference_sequence: str = None, **kwargs):
    """Construct the instance

    Args:
        metadata: Unique database references
        uniprot_ids: The UniProtID(s) that describe this protein sequence
        thermophilicity: The extent to which the sequence is deemed thermophilic
        reference_sequence: The reference sequence (according to expression sequence or reference database)
    """
    super().__init__(**kwargs)  # StructuredGeneEntity
    self._alpha = default_fragment_contribution
    self.alpha = []
    self.fragment_map = None
    self.fragment_profile = None  # fragment specific scoring matrix

    self._api_data = None  # {chain: {'accession': 'Q96DC8', 'db': 'UniProt'}, ...}

    if metadata is None:
        if reference_sequence is not None:
            self._reference_sequence = reference_sequence

        self.thermophilicity = thermophilicity
        if uniprot_ids is not None:
            self.uniprot_ids = uniprot_ids
    else:
        if metadata.reference_sequence is not None:
            self._reference_sequence = metadata.reference_sequence

        self.thermophilicity = metadata.thermophilicity
        if metadata.uniprot_entities is not None:
            self.uniprot_ids = metadata.uniprot_ids

fragment_map instance-attribute

fragment_map: list[dict[int, set[FragmentObservation]]] | None = None

{1: {-2: {FragObservation(), ...}, -1: {}, ...}, 2: {}, ...} Where the outer list indices match Residue.index, and each dictionary holds the various fragment indices (with fragment_length length) for that residue, where each index in the inner set can have multiple observations

uniprot_ids property writable

uniprot_ids: tuple[str | None, ...]

The UniProtID(s) used for accessing external protein level features

reference_sequence property

reference_sequence: str

Return the entire sequence, constituting all described residues, not just structurally modeled ones

Returns:

  • str

    The sequence according to the Entity reference, or the Structure sequence if no reference available

offset_index property

offset_index: int

The starting Residue index for the instance. Zero-indexed

disorder property

disorder: dict[int, dict[str, str]]

Return the Residue number keys where disordered residues are found by comparison of the reference sequence with the structure sequence

Returns:

  • dict[int, dict[str, str]]

    Mutation index to mutations in the format of {1: {'from': 'A', 'to': 'K'}, ...}

clear_api_data

clear_api_data()

Removes any state information from the PDB API

Source code in symdesign/structure/model.py
266
267
268
269
270
def clear_api_data(self):
    """Removes any state information from the PDB API"""
    del self._reference_sequence
    self.uniprot_ids = (None,)
    self.thermophilicity = None

retrieve_api_metadata

retrieve_api_metadata()

Try to set attributes from PDB API

Sets

self._api_data: dict[str, Any] {'chains': [], 'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'}, 'reference_sequence': 'MSLEHHHHHH...', 'thermophilicity': True self._uniprot_id: str | None self._reference_sequence: str self.thermophilicity: bool

Source code in symdesign/structure/model.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def retrieve_api_metadata(self):
    """Try to set attributes from PDB API

    Sets:
        self._api_data: dict[str, Any]
            {'chains': [],
             'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'},
             'reference_sequence': 'MSLEHHHHHH...',
             'thermophilicity': True
        self._uniprot_id: str | None
        self._reference_sequence: str
        self.thermophilicity: bool
    """
    entity_id = self.entity_id
    try:
        retrieve_api_info = resources.wrapapi.api_database_factory().pdb.retrieve_data
    except AttributeError:
        retrieve_api_info = query.pdb.query_pdb_by
    api_return = retrieve_api_info(entity_id=entity_id)
    """Get the data on it's own since retrieve_api_info returns
    {'EntityID':
       {'chains': ['A', 'B', ...],
        'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'},
        'reference_sequence': 'MSLEHHHHHH...',
        'thermophilicity': 1.0},
    ...}
    """
    if api_return:
        if entity_id.lower() in api_return:
            self.name = name = entity_id.lower()

        self._api_data = api_return.get(name, {})
    else:
        self._api_data = {}

    if self._api_data is not None:
        for data_type, data in self._api_data.items():
            # self.log.debug('Retrieving UNP ID for {self.name}\nAPI DATA for chain {chain}:\n{api_data}')
            if data_type == 'reference_sequence':
                self._reference_sequence = data
            elif data_type == 'thermophilicity':
                self.thermophilicity = data
            elif data_type == 'dbref':
                if data.get('db') == query.pdb.UKB:
                    self.uniprot_ids = data.get('accession')
    else:
        self.log.warning(f'{repr(self)}: No information found from PDB API')

add_fragments_to_profile

add_fragments_to_profile(fragments: Iterable[FragmentInfo], alignment_type: alignment_types_literal, **kwargs)

Distribute fragment information to self.fragment_map. Zero-indexed residue array

Parameters:

  • fragments (Iterable[FragmentInfo]) –

    The fragment list to assign to the sequence profile with format [{'mapped': residue_index1 (int), 'paired': residue_index2 (int), 'cluster': tuple(int, int, int), 'match': match_score (float)}]

  • alignment_type (alignment_types_literal) –

    Either 'mapped' or 'paired' indicating how the fragment observation was generated relative to this GeneEntity. Are the fragments mapped to the ContainsResidues or was it paired to it?

Sets

self.fragment_map (list[list[dict[str, str | float]]]): [{-2: {FragObservation(), ...}, -1: {}, ...}, {}, ...] Where the outer list indices match Residue.index, and each dictionary holds the various fragment indices (with fragment_length length) for that residue, where each index in the inner set can have multiple observations

Source code in symdesign/structure/model.py
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
def add_fragments_to_profile(self, fragments: Iterable[FragmentInfo],
                             alignment_type: alignment_types_literal, **kwargs):
    """Distribute fragment information to self.fragment_map. Zero-indexed residue array

    Args:
        fragments: The fragment list to assign to the sequence profile with format
            [{'mapped': residue_index1 (int), 'paired': residue_index2 (int), 'cluster': tuple(int, int, int),
              'match': match_score (float)}]
        alignment_type: Either 'mapped' or 'paired' indicating how the fragment observation was generated relative
            to this GeneEntity. Are the fragments mapped to the ContainsResidues or was it paired to it?

    Sets:
        self.fragment_map (list[list[dict[str, str | float]]]):
            [{-2: {FragObservation(), ...},
              -1: {}, ...},
             {}, ...]
            Where the outer list indices match Residue.index, and each dictionary holds the various fragment indices
            (with fragment_length length) for that residue, where each index in the inner set can have multiple
            observations
    """
    if alignment_type not in alignment_types:
        raise ValueError(
            f"Argument 'alignment_type' must be one of '{', '.join(alignment_types)}' not {alignment_type}")

    fragment_db = self.fragment_db
    fragment_map = self.fragment_map
    if fragment_map is None:
        # Create empty fragment_map to store information about each fragment observation in the profile
        self.fragment_map = fragment_map = [defaultdict(set) for _ in range(self.number_of_residues)]

    # Add frequency information to the fragment profile using parsed cluster information. Frequency information is
    # added in a fragment index dependent manner. If multiple fragment indices are present in a single residue, a
    # new observation is created for that fragment index.
    for fragment in fragments:
        # Offset the specified fragment index to the overall index in the ContainsStructures
        fragment_index = getattr(fragment, alignment_type)
        cluster = fragment.cluster
        match = fragment.match
        residue_index = fragment_index - self.offset_index
        # Retrieve the amino acid frequencies for this fragment cluster, for this alignment side
        aa_freq = getattr(fragment_db.info[cluster], alignment_type)
        for frag_idx, frequencies in aa_freq.items():  # (lower_bound - upper_bound), [freqs]
            _frequencies = frequencies.copy()
            _frag_info = FragmentObservation(source=alignment_type, cluster=cluster, match=match,
                                             weight=_frequencies.pop('weight'), frequencies=_frequencies)
            fragment_map[residue_index + frag_idx][frag_idx].add(_frag_info)

simplify_fragment_profile

simplify_fragment_profile(evo_fill: bool = False, **kwargs)

Take a multi-indexed, a multi-observation fragment_profile and flatten to single frequency for each residue.

Weight the frequency of each observation by the fragment indexed, average observation weight, proportionally scaled by the match score between the fragment database and the observed fragment overlap

From the self.fragment_map data, create a fragment profile and add to the GeneEntity

Parameters:

  • evo_fill (bool, default: False ) –

    Whether to fill missing positions with evolutionary profile values

Other Parameters:

  • alpha

    float = 0.5 - The maximum contribution of the fragment profile to use, bounded between (0, 1]. 0 means no use of fragments in the .profile, while 1 means only use fragments

Sets

self.fragment_profile (Profile) [{'A': 0.23, 'C': 0.01, ..., stats': (1, 0.37)}, {...}, ...] list of profile_entry that combines all fragment information at a single residue using a weighted average. 'count' is number of fragment observations at each residue, and 'weight' is the total fragment weight over the entire residue

Source code in symdesign/structure/model.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def simplify_fragment_profile(self, evo_fill: bool = False, **kwargs):
    """Take a multi-indexed, a multi-observation fragment_profile and flatten to single frequency for each residue.

    Weight the frequency of each observation by the fragment indexed, average observation weight, proportionally
    scaled by the match score between the fragment database and the observed fragment overlap

    From the self.fragment_map data, create a fragment profile and add to the GeneEntity

    Args:
        evo_fill: Whether to fill missing positions with evolutionary profile values

    Keyword Args:
        alpha: float = 0.5 - The maximum contribution of the fragment profile to use, bounded between (0, 1].
            0 means no use of fragments in the .profile, while 1 means only use fragments

    Sets:
        self.fragment_profile (Profile)
            [{'A': 0.23, 'C': 0.01, ..., stats': (1, 0.37)}, {...}, ...]
            list of profile_entry that combines all fragment information at a single residue using a weighted
            average. 'count' is number of fragment observations at each residue, and 'weight' is the total
            fragment weight over the entire residue
    """
    # keep_extras: Whether to keep values for all positions that are missing data
    fragment_db = self.fragment_db
    fragment_map = self.fragment_map
    if fragment_map is None:  # Need this for _calculate_alpha()
        raise RuntimeError(
            f'Must {self.add_fragments_to_profile.__name__}() before '
            f'{self.simplify_fragment_profile.__name__}(). No fragments were set')
    elif not fragment_db:
        raise AttributeError(
            f"{self.simplify_fragment_profile.__name__}: No '.fragment_db'. Can't calculate "
            'fragment contribution without one')

    database_bkgnd_aa_freq = fragment_db.aa_frequencies
    # Fragment profile is correct size for indexing all STRUCTURAL residues
    #  self.reference_sequence is not used for this. Instead, self.sequence is used in place since the use
    #  of a disorder indicator that removes any disordered residues from input evolutionary profiles is calculated
    #  on the full reference sequence. This ensures that the profile is the right length of the structure and
    #  captures disorder specific evolutionary signals that could be important in the calculation of profiles
    sequence = self.sequence
    no_design = []
    fragment_profile = [[{} for _ in range(fragment_db.fragment_length)]
                        for _ in range(self.number_of_residues)]
    indexed_observations: dict[int, set[FragmentObservation]]
    for residue_index, indexed_observations in enumerate(fragment_map):
        total_fragment_observations = total_fragment_weight_x_match = total_fragment_weight = 0

        # Sum the weight for each fragment observation
        for index, observations in indexed_observations.items():
            for observation in observations:
                total_fragment_observations += 1
                observation_weight = observation.weight
                total_fragment_weight += observation_weight
                total_fragment_weight_x_match += observation_weight * observation.match

        # New style, consolidated
        residue_frequencies = {'count': total_fragment_observations,
                               'weight': total_fragment_weight,
                               'info': 0.,
                               'type': sequence[residue_index],
                               }
        if total_fragment_weight_x_match > 0:
            # Combine all amino acid frequency distributions for all observations at each index
            residue_frequencies.update(**aa_counts_alph3)  # {'A': 0, 'R': 0, ...}
            for index, observations in indexed_observations.items():
                for observation in observations:
                    # Multiply weight associated with observations by the match of the observation, then
                    # scale the observation weight by the total. If no weight, side chain isn't significant.
                    scaled_frag_weight = observation.weight * observation.match / total_fragment_weight_x_match
                    # Add all occurrences to summed frequencies list
                    for aa, frequency in observation.frequencies.items():
                        residue_frequencies[aa] += frequency * scaled_frag_weight

            residue_frequencies['lod'] = get_lod(residue_frequencies, database_bkgnd_aa_freq)
        else:  # Add to list for removal from the profile
            no_design.append(residue_index)
            # {'A': 0, 'R': 0, ...}
            residue_frequencies.update(lod=aa_nan_counts_alph3.copy(), **aa_nan_counts_alph3)

        # Add results to final fragment_profile residue position
        fragment_profile[residue_index] = residue_frequencies
        # Since self.evolutionary_profile is copied or removed, an empty dictionary is fine here
        # If this changes, maybe the == 0 condition needs an aa_counts_alph3.copy() instead of {}

    if evo_fill and self.evolutionary_profile:
        # If not an empty dictionary, add the corresponding value from evolution
        # For Rosetta, the packer palette is subtractive so the use of an overlapping evolution and
        # null fragment would result in nothing allowed during design...
        evolutionary_profile = self.evolutionary_profile
        for residue_index in no_design:
            fragment_profile[residue_index] = evolutionary_profile.get(residue_index + ZERO_OFFSET)

    # Format into fragment_profile Profile object
    self.fragment_profile = Profile(fragment_profile, dtype='fragment')

    self._calculate_alpha(**kwargs)

calculate_profile

calculate_profile(favor_fragments: bool = False, boltzmann: bool = True, **kwargs)

Combine weights for profile PSSM and fragment SSM using fragment significance value to determine overlap

Using self.evolutionary_profile (ProfileDict): HHblits - {1: {'A': 0.04, 'C': 0.12, ..., 'lod': {'A': -5, 'C': -9, ...}, 'type': 'W', 'info': 0.00, 'weight': 0.00}, {...}} PSIBLAST - {1: {'A': 0.13, 'R': 0.12, ..., 'lod': {'A': -5, 'R': 2, ...}, 'type': 'W', 'info': 3.20, 'weight': 0.73}, {...}} self.fragment_profile (dict[int, dict[str, float | list[float]]]): {48: {'A': 0.167, 'D': 0.028, 'E': 0.056, ..., 'count': 4, 'weight': 0.274}, 50: {...}, ...} self.alpha (list[float]): [0., 0., 0., 0.5, 0.321, ...]

Parameters:

  • favor_fragments (bool, default: False ) –

    Whether to favor fragment profile in the lod score of the resulting profile Currently this routine is only used for Rosetta designs where the fragments should be favored by a particular weighting scheme. By default, the boltzmann weighting scheme is applied

  • boltzmann (bool, default: True ) –

    Whether to weight the fragment profile by a Boltzmann probability scaling using the formula lods = exp(lods[i]/kT)/Z, where Z = sum(exp(lods[i]/kT)), and kT is 1 by default. If False, residues are weighted by the residue local maximum lod score in a linear fashion All lods are scaled to a maximum provided in the Rosetta REF2015 per residue reference weight.

Sets

self.profile: (ProfileDict) {1: {'A': 0.04, 'C': 0.12, ..., 'lod': {'A': -5, 'C': -9, ...}, 'type': 'W', 'info': 0.00, 'weight': 0.00}, ...}, ...}

Source code in symdesign/structure/model.py
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
756
757
758
759
760
761
762
def calculate_profile(self, favor_fragments: bool = False, boltzmann: bool = True, **kwargs):
    """Combine weights for profile PSSM and fragment SSM using fragment significance value to determine overlap

    Using self.evolutionary_profile
        (ProfileDict): HHblits - {1: {'A': 0.04, 'C': 0.12, ..., 'lod': {'A': -5, 'C': -9, ...},
                                             'type': 'W', 'info': 0.00, 'weight': 0.00}, {...}}
                       PSIBLAST - {1: {'A': 0.13, 'R': 0.12, ..., 'lod': {'A': -5, 'R': 2, ...},
                                       'type': 'W', 'info': 3.20, 'weight': 0.73}, {...}}
    self.fragment_profile
        (dict[int, dict[str, float | list[float]]]):
            {48: {'A': 0.167, 'D': 0.028, 'E': 0.056, ..., 'count': 4, 'weight': 0.274}, 50: {...}, ...}
    self.alpha
        (list[float]): [0., 0., 0., 0.5, 0.321, ...]

    Args:
        favor_fragments: Whether to favor fragment profile in the lod score of the resulting profile
            Currently this routine is only used for Rosetta designs where the fragments should be favored by a
            particular weighting scheme. By default, the boltzmann weighting scheme is applied
        boltzmann: Whether to weight the fragment profile by a Boltzmann probability scaling using the formula
            lods = exp(lods[i]/kT)/Z, where Z = sum(exp(lods[i]/kT)), and kT is 1 by default.
            If False, residues are weighted by the residue local maximum lod score in a linear fashion
            All lods are scaled to a maximum provided in the Rosetta REF2015 per residue reference weight.

    Sets:
        self.profile: (ProfileDict)
            {1: {'A': 0.04, 'C': 0.12, ..., 'lod': {'A': -5, 'C': -9, ...},
                 'type': 'W', 'info': 0.00, 'weight': 0.00}, ...}, ...}
    """
    if self._alpha == 0:
        # Round up to avoid division error
        self.log.warning(f'{self.calculate_profile.__name__}: _alpha set with 1e-5 tolerance due to 0 value')
        self._alpha = 0.000001

    # Copy the evolutionary profile to self.profile (structure specific scoring matrix)
    self.profile = profile = deepcopy(self.evolutionary_profile)
    if sum(self.alpha) == 0:  # No fragments to combine
        return

    # Combine fragment and evolutionary probability profile according to alpha parameter
    fragment_profile = self.fragment_profile
    # log_string = []
    for entry_idx, weight in enumerate(self.alpha):
        # Weight will be 0 if the fragment_profile is empty
        if weight:
            # log_string.append(f'Residue {entry + 1:5d}: {weight * 100:.0f}% fragment weight')
            frag_profile_entry = fragment_profile[entry_idx]
            inverse_weight = 1 - weight
            _profile_entry = profile[entry_idx + ZERO_OFFSET]
            _profile_entry.update({aa: weight * frag_profile_entry[aa] + inverse_weight * _profile_entry[aa]
                                   for aa in protein_letters_alph3})
    # if log_string:
    #     # self.log.info(f'At {self.name}, combined evolutionary and fragment profiles into Design Profile with:'
    #     #               f'\n\t%s' % '\n\t'.join(log_string))
    #     pass

    if favor_fragments:
        fragment_db = self.fragment_db
        boltzman_energy = 1
        favor_seqprofile_score_modifier = 0.2 * utils.rosetta.reference_average_residue_weight
        if not fragment_db:
            raise AttributeError(
                f"{self.calculate_profile.__name__}: No fragment database connected. Can't 'favor_fragments' "
                'without one')
        database_bkgnd_aa_freq = fragment_db.aa_frequencies

        null_residue = get_lod(database_bkgnd_aa_freq, database_bkgnd_aa_freq, as_int=False)
        # This was needed in the case of domain errors with lod
        # null_residue = {aa: float(frequency) for aa, frequency in null_residue.items()}

        # Set all profile entries to a null entry first
        for entry, data in self.profile.items():
            data['lod'] = null_residue  # Caution, all reference same object

        alpha = self.alpha
        for entry, data in self.profile.items():
            data['lod'] = get_lod(fragment_profile[entry - ZERO_OFFSET], database_bkgnd_aa_freq, as_int=False)
            # Adjust scores with particular weighting scheme
            partition = 0.
            for aa, value in data['lod'].items():
                if boltzmann:  # Boltzmann scaling, sum for the partition function
                    value = math.exp(value / boltzman_energy)
                    partition += value
                else:  # if value < 0:
                    # With linear scaling, remove any lod penalty
                    value = max(0, value)

                data['lod'][aa] = value

            # Find the maximum/residue (local) lod score
            max_lod = max(data['lod'].values())
            # Takes the percent of max alpha for each entry multiplied by the standard residue scaling factor
            modified_entry_alpha = (alpha[entry - ZERO_OFFSET] / self._alpha) * favor_seqprofile_score_modifier
            if boltzmann:
                # lods = e ** odds[i]/Z, Z = sum(exp(odds[i]/kT))
                modifier = partition
                modified_entry_alpha /= (max_lod / partition)
            else:
                modifier = max_lod

            # Weight the final lod score by the modifier and the scaling factor for the chosen method
            data['lod'] = {aa: value / modifier * modified_entry_alpha for aa, value in data['lod'].items()}

format_missing_loops_for_design

format_missing_loops_for_design(max_loop_length: int = 12, exclude_n_term: bool = True, ignore_termini: bool = False, **kwargs) -> tuple[list[tuple], dict[int, int], int]

Process missing residue information to prepare for loop modeling files. Assumes residues in pose numbering!

Parameters:

  • max_loop_length (int, default: 12 ) –

    The max length for loop modeling. 12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014

  • exclude_n_term (bool, default: True ) –

    Whether to exclude the N-termini from modeling due to Remodel Bug

  • ignore_termini (bool, default: False ) –

    Whether to ignore terminal loops in the loop file

Returns:

  • tuple[list[tuple], dict[int, int], int]

    Pairs of indices where each loop starts and ends, adjacent indices (not all indices are disordered) mapped to their disordered residue indices, and the n-terminal residue index

Source code in symdesign/structure/model.py
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
def format_missing_loops_for_design(
    self, max_loop_length: int = 12, exclude_n_term: bool = True, ignore_termini: bool = False, **kwargs
) -> tuple[list[tuple], dict[int, int], int]:
    """Process missing residue information to prepare for loop modeling files. Assumes residues in pose numbering!

    Args:
        max_loop_length: The max length for loop modeling.
            12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014
        exclude_n_term: Whether to exclude the N-termini from modeling due to Remodel Bug
        ignore_termini: Whether to ignore terminal loops in the loop file

    Returns:
        Pairs of indices where each loop starts and ends, adjacent indices (not all indices are disordered) mapped
            to their disordered residue indices, and the n-terminal residue index
    """
    disordered_residues = self.disorder
    # Formatted as {residue_number: {'from': aa, 'to': aa}, ...}
    reference_sequence_length = len(self.reference_sequence)
    loop_indices = []
    loop_to_disorder_indices = {}  # Holds the indices that should be inserted into the total residues to be modeled
    n_terminal_idx = 0  # Initialize as an impossible value
    excluded_disorder_len = 0  # Total residues excluded from loop modeling. Needed for pose numbering translation
    segment_length = 0  # Iterate each missing residue
    n_term = False
    loop_start = loop_end = None
    for idx, residue_number in enumerate(disordered_residues.keys(), 1):
        segment_length += 1
        if residue_number - 1 not in disordered_residues:  # indicate that this residue_number starts disorder
            # print('Residue number -1 not in loops', residue_number)
            loop_start = residue_number - 1 - excluded_disorder_len  # - 1 as loop modeling needs existing residue
            if loop_start < 1:
                n_term = True

        if residue_number + 1 not in disordered_residues:
            # The segment has ended
            if residue_number != reference_sequence_length:
                # Not the c-terminus
                # logger.debug('f{residue_number=} +1 not in loops. Adding loop with {segment_length=}')
                if segment_length <= max_loop_length:
                    # Modeling useful, add to loop_indices
                    if n_term and (ignore_termini or exclude_n_term):
                        # The n-terminus should be included
                        excluded_disorder_len += segment_length
                        n_term = False  # No more n_term considerations
                    else:  # Include the segment in the disorder_indices
                        loop_end = residue_number + 1 - excluded_disorder_len
                        loop_indices.append((loop_start, loop_end))
                        for it, residue_index in enumerate(range(loop_start + 1, loop_end), 1):
                            loop_to_disorder_indices[residue_index] = residue_number - (segment_length - it)
                        # Set the start and end indices as out of bounds numbers
                        loop_to_disorder_indices[loop_start], loop_to_disorder_indices[loop_end] = -1, -1
                        if n_term and idx != 1:  # If this is the n-termini and not start Met
                            n_terminal_idx = loop_end  # Save idx of last n-term insertion
                else:  # Modeling not useful, sum the exclusion length
                    excluded_disorder_len += segment_length

                # After handling disordered segment, reset increment and loop indices
                segment_length = 0
                loop_start = loop_end = None
            # Residue number is the c-terminal residue
            elif ignore_termini:
                if segment_length <= max_loop_length:
                    # loop_end = loop_start + 1 + segment_length  # - excluded_disorder
                    loop_end = residue_number - excluded_disorder_len
                    loop_indices.append((loop_start, loop_end))
                    for it, residue_index in enumerate(range(loop_start + 1, loop_end), 1):
                        loop_to_disorder_indices[residue_index] = residue_number - (segment_length - it)
                    # Don't include start index in the loop_to_disorder map since c-terminal doesn't have attachment
                    loop_to_disorder_indices[loop_end] = -1

    return loop_indices, loop_to_disorder_indices, n_terminal_idx

make_loop_file

make_loop_file(out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr | None

Format a loops file according to Rosetta specifications. Assumes residues in pose numbering!

The loop file format consists of one line for each specified loop with the format:

LOOP 779 784 0 0 1

Where LOOP specifies a loop line, start idx, end idx, cut site (0 lets Rosetta choose), skip rate, and extended

All indices should refer to existing locations in the structure file so if a loop should be inserted into missing density, the density needs to be modeled first before the loop file would work to be modeled. You can't therefore specify that a loop should be between 779 and 780 if the loop is 12 residues long since there is no specification about how to insert those residues. This type of task requires a blueprint file.

Parameters:

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

    The location the file should be written

Other Parameters:

  • max_loop_length=12 (int) –

    The max length for loop modeling. 12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014

  • exclude_n_term=True (bool) –

    Whether to exclude the N-termini from modeling due to Remodel Bug

  • ignore_termini=False (bool) –

    Whether to ignore terminal loops in the loop file

Returns:

  • AnyStr | None

    The path of the file if one was written

Source code in symdesign/structure/model.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def make_loop_file(self, out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr | None:
    """Format a loops file according to Rosetta specifications. Assumes residues in pose numbering!

    The loop file format consists of one line for each specified loop with the format:

    LOOP 779 784 0 0 1

    Where LOOP specifies a loop line, start idx, end idx, cut site (0 lets Rosetta choose), skip rate, and extended

    All indices should refer to existing locations in the structure file so if a loop should be inserted into
    missing density, the density needs to be modeled first before the loop file would work to be modeled. You
    can't therefore specify that a loop should be between 779 and 780 if the loop is 12 residues long since there is
     no specification about how to insert those residues. This type of task requires a blueprint file.

    Args:
        out_path: The location the file should be written

    Keyword Args:
        max_loop_length=12 (int): The max length for loop modeling.
            12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014
        exclude_n_term=True (bool): Whether to exclude the N-termini from modeling due to Remodel Bug
        ignore_termini=False (bool): Whether to ignore terminal loops in the loop file

    Returns:
        The path of the file if one was written
    """
    loop_indices, _, _ = self.format_missing_loops_for_design(**kwargs)
    if not loop_indices:
        return None

    loop_file = os.path.join(out_path, f'{self.name}.loops')
    with open(loop_file, 'w') as f:
        f.write('%s\n' % '\n'.join(f'LOOP {start} {stop} 0 0 1' for start, stop in loop_indices))

    return loop_file

make_blueprint_file

make_blueprint_file(out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr | None

Format a blueprint file according to Rosetta specifications. Assumes residues in pose numbering!

The blueprint file format is described nicely here

https://www.rosettacommons.org/docs/latest/application_documentation/design/rosettaremodel

In a gist, a blueprint file consists of entries describing the type of design available at each position.

Ex

1 x L PIKAA M <- Extension

1 x L PIKAA V <- Extension

1 V L PIKAA V <- Attachment point

2 D .

3 K .

4 I .

5 L N PIKAA N <- Attachment point

0 x I NATAA <- Insertion

0 x I NATAA <- Insertion

6 N A PIKAA A <- Attachment point

7 G .

0 X L PIKAA Y <- Extension

0 X L PIKAA P <- Extension

All structural indices must be specified in "pose numbering", i.e. starting with 1 ending with the last residue. If you have missing density in the middle, you should not specify those residues that are missing, but keep continuous numbering. You can specify an inclusion by specifying the entry index as 0 followed by the blueprint directive. For missing density at the n- or c-termini, the file should still start 1, however, the n-termini should be extended by prepending extra entries to the structurally defined n-termini entry 1. These blueprint entries should also have 1 as the residue index. For c-termini, extra entries should be appended with the indices as 0 like in insertions. For all unmodeled entries for which design should be performed, there should be flanking attachment points that are also capable of design. Designable entries are seen above with the PIKAA directive. Other directives are available. The only location this isn't required is at the c-terminal attachment point

Parameters:

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

    The location the file should be written

Other Parameters:

  • max_loop_length=12 (int) –

    The max length for loop modeling. 12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014

  • exclude_n_term=True (bool) –

    Whether to exclude the N-termini from modeling due to Remodel Bug

  • ignore_termini=False (bool) –

    Whether to ignore terminal loops in the loop file

Returns:

  • AnyStr | None

    The path of the file if one was written

Source code in symdesign/structure/model.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
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
def make_blueprint_file(self, out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr | None:
    """Format a blueprint file according to Rosetta specifications. Assumes residues in pose numbering!

    The blueprint file format is described nicely here:
        https://www.rosettacommons.org/docs/latest/application_documentation/design/rosettaremodel

    In a gist, a blueprint file consists of entries describing the type of design available at each position.

    Ex:
        1 x L PIKAA M   <- Extension

        1 x L PIKAA V   <- Extension

        1 V L PIKAA V   <- Attachment point

        2 D .

        3 K .

        4 I .

        5 L N PIKAA N   <- Attachment point

        0 x I NATAA     <- Insertion

        0 x I NATAA     <- Insertion

        6 N A PIKAA A   <- Attachment point

        7 G .

        0 X L PIKAA Y   <- Extension

        0 X L PIKAA P   <- Extension

    All structural indices must be specified in "pose numbering", i.e. starting with 1 ending with the last residue.
    If you have missing density in the middle, you should not specify those residues that are missing, but keep
    continuous numbering. You can specify an inclusion by specifying the entry index as 0 followed by the blueprint
    directive. For missing density at the n- or c-termini, the file should still start 1, however, the n-termini
    should be extended by prepending extra entries to the structurally defined n-termini entry 1. These blueprint
    entries should also have 1 as the residue index. For c-termini, extra entries should be appended with the
    indices as 0 like in insertions. For all unmodeled entries for which design should be performed, there should
    be flanking attachment points that are also capable of design. Designable entries are seen above with the PIKAA
    directive. Other directives are available. The only location this isn't required is at the c-terminal attachment
    point

    Args:
        out_path: The location the file should be written

    Keyword Args:
        max_loop_length=12 (int): The max length for loop modeling.
            12 is the max for accurate KIC as of benchmarks from T. Kortemme, 2014
        exclude_n_term=True (bool): Whether to exclude the N-termini from modeling due to Remodel Bug
        ignore_termini=False (bool): Whether to ignore terminal loops in the loop file

    Returns:
        The path of the file if one was written
    """
    disordered_residues = self.disorder
    # Formatted as {residue_number: {'from': aa, 'to': aa}, ...}
    # trying to remove tags at this stage runs into a serious indexing problem where tags need to be deleted from
    # disordered_residues and then all subsequent indices adjusted.

    # # look for existing tag to remove from sequence and save identity
    # available_tags = find_expression_tags(self.reference_sequence)
    # if available_tags:
    #     loop_sequences = ''.join(mutation['from'] for mutation in disordered_residues)
    #     remove_loop_pairs = []
    #     for tag in available_tags:
    #         tag_location = loop_sequences.find(tag['sequences'])
    #         if tag_location != -1:
    #             remove_loop_pairs.append((tag_location, len(tag['sequences'])))
    #     for tag_start, tag_length in remove_loop_pairs:
    #         for
    #
    #     # untagged_seq = remove_terminal_tags(loop_sequences, [tag['sequence'] for tag in available_tags])

    _, disorder_indices, start_idx = self.format_missing_loops_for_design(**kwargs)
    if not disorder_indices:
        return

    residues = self.residues
    # for residue_number in sorted(disorder_indices):  # ensure ascending order, insert dependent on prior inserts
    for residue_index, disordered_residue in disorder_indices.items():
        mutation = disordered_residues.get(disordered_residue)
        if mutation:  # add disordered residue to residues list if they exist
            residues.insert(residue_index - 1, mutation['from'])  # offset to match residues zero-index

    #                 index AA SS Choice AA
    # structure_str   = '%d %s %s'
    # loop_str        = '%d X %s PIKAA %s'
    blueprint_lines = []
    for idx, residue in enumerate(residues, 1):
        if isinstance(residue, Residue):  # use structure_str template
            residue_type = protein_letters_3to1_extended.get(residue.type)
            blueprint_lines.append(f'{residue.number} {residue_type} '
                                   f'{f"L PIKAA {residue_type}" if idx in disorder_indices else "."}')
        else:  # residue is the residue type from above insertion, use loop_str template
            blueprint_lines.append(f'{1 if idx < start_idx else 0} X {"L"} PIKAA {residue}')

    blueprint_file = os.path.join(out_path, f'{self.name}.blueprint')
    with open(blueprint_file, 'w') as f:
        f.write('%s\n' % '\n'.join(blueprint_lines))
    return blueprint_file

Structure

Structure(metadata: ProteinMetadata = None, uniprot_ids: tuple[str, ...] = None, thermophilicity: bool = None, reference_sequence: str = None, **kwargs)

Bases: StructuredGeneEntity, ParseStructureMixin

The base class to handle structural manipulation of groups of Residue instances

Parameters:

  • metadata (ProteinMetadata, default: None ) –

    Unique database references

  • uniprot_ids (tuple[str, ...], default: None ) –

    The UniProtID(s) that describe this protein sequence

  • thermophilicity (bool, default: None ) –

    The extent to which the sequence is deemed thermophilic

  • reference_sequence (str, default: None ) –

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

Source code in symdesign/structure/model.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(self, metadata: sql.ProteinMetadata = None, uniprot_ids: tuple[str, ...] = None,
             thermophilicity: bool = None, reference_sequence: str = None, **kwargs):
    """Construct the instance

    Args:
        metadata: Unique database references
        uniprot_ids: The UniProtID(s) that describe this protein sequence
        thermophilicity: The extent to which the sequence is deemed thermophilic
        reference_sequence: The reference sequence (according to expression sequence or reference database)
    """
    super().__init__(**kwargs)  # StructuredGeneEntity
    self._alpha = default_fragment_contribution
    self.alpha = []
    self.fragment_map = None
    self.fragment_profile = None  # fragment specific scoring matrix

    self._api_data = None  # {chain: {'accession': 'Q96DC8', 'db': 'UniProt'}, ...}

    if metadata is None:
        if reference_sequence is not None:
            self._reference_sequence = reference_sequence

        self.thermophilicity = thermophilicity
        if uniprot_ids is not None:
            self.uniprot_ids = uniprot_ids
    else:
        if metadata.reference_sequence is not None:
            self._reference_sequence = metadata.reference_sequence

        self.thermophilicity = metadata.thermophilicity
        if metadata.uniprot_entities is not None:
            self.uniprot_ids = metadata.uniprot_ids

ContainsStructures

ContainsStructures(**kwargs)

Bases: Structure

Implements methods to interact with a Structure which contains other Structure instances

Parameters:

  • **kwargs
Source code in symdesign/structure/model.py
1001
1002
1003
1004
1005
1006
1007
1008
def __init__(self, **kwargs):
    """Construct the instance

    Args:
        **kwargs:
    """
    super().__init__(**kwargs)  # ContainsStructures
    self.structure_containers = []

biological_assembly property

biological_assembly: str | None

The integer which maps the structure to an assembly state from the PDB

file_path property

file_path: str | None

The integer which maps the structure to an assembly state from the PDB

resolution property

resolution: float | None

The integer which maps the structure to an assembly state from the PDB

reset_and_reindex_structures staticmethod

reset_and_reindex_structures(structs: Sequence[ContainsResidues] | Structures)

Given ContainsResidues instances, reset the states and renumber indices in the order passed

Source code in symdesign/structure/model.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
@staticmethod
def reset_and_reindex_structures(structs: Sequence[ContainsResidues] | Structures):
    """Given ContainsResidues instances, reset the states and renumber indices in the order passed"""
    struct: ContainsResidues
    other_structs: tuple[ContainsResidues]

    struct, *other_structs = structs
    struct.reset_state()
    struct._start_indices(at=0, dtype='atom')
    struct._start_indices(at=0, dtype='residue')
    prior_struct = struct
    for struct in other_structs:
        struct.reset_state()
        struct._start_indices(at=prior_struct.end_index + 1, dtype='atom')
        struct._start_indices(at=prior_struct.residue_indices[-1] + 1, dtype='residue')
        prior_struct = struct

fragment_db

fragment_db(fragment_db: FragmentDatabase)

Set the Structure FragmentDatabase to assist with Fragment creation, manipulation, and profiles. Sets .fragment_db for each dependent Structure in 'structure_containers'

Source code in symdesign/structure/model.py
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
@ContainsResidues.fragment_db.setter
def fragment_db(self, fragment_db: FragmentDatabase):
    """Set the Structure FragmentDatabase to assist with Fragment creation, manipulation, and profiles.
    Sets .fragment_db for each dependent Structure in 'structure_containers'
    """
    # Set this instance then set all dependents
    super(Structure, Structure).fragment_db.fset(self, fragment_db)
    _fragment_db = self._fragment_db
    if _fragment_db is not None:
        for structure_type in self.structure_containers:
            for structure in self.__getattribute__(structure_type):
                structure.fragment_db = _fragment_db
    else:  # This is likely the RELOAD_DB token. Just return.
        return

format_header

format_header(**kwargs) -> str

Returns any super().format_header() along with the SEQRES records

Returns:

  • str

    The .pdb file header string

Source code in symdesign/structure/model.py
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
def format_header(self, **kwargs) -> str:
    """Returns any super().format_header() along with the SEQRES records

    Returns:
        The .pdb file header string
    """
    if self.is_parent() and isinstance(self.metadata.cryst_record, str):
        _header = self.metadata.cryst_record
    else:
        _header = ''

    return super().format_header(**kwargs) + self._format_seqres(**kwargs) + _header

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/model.py
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
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
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
    """
    delete_indices = super().mutate_residue(residue=residue, index=index, number=number, to=to)
    if self.is_dependent() or not delete_indices:  # Probably an empty list, there are no indices to delete
        return delete_indices
    structure: Structure

    # Remove delete_indices from each Structure _atom_indices
    # If subsequent structures, update their _atom_indices accordingly
    delete_length = len(delete_indices)
    for structure_type in self.structure_containers:
        residue_found = False
        # Iterate over each Structure in each structure_container
        for structure in self.__getattribute__(structure_type):
            if residue_found:  # The Structure the Residue belongs to is already accounted for, just offset
                structure._offset_indices(start_at=0, offset=-delete_length, dtype='atom')
            else:
                try:
                    structure_atom_indices = structure.atom_indices
                    atom_delete_index = structure_atom_indices.index(delete_indices[0])
                except ValueError:  # When delete_indices[0] isn't in structure_atom_indices
                    continue  # Haven't reached the correct Structure yet
                else:
                    try:
                        for idx in iter(delete_indices):
                            structure_atom_indices.pop(atom_delete_index)
                    except IndexError:  # When atom_delete_index isn't in structure_atom_indices
                        raise IndexError(
                            f"{self.mutate_residue.__name__}: The index {idx} isn't in the {repr(self)}")
                        # structure._offset_indices(start_at=0, offset=-delete_indices.index(idx), dtype='atom')
                    else:
                        structure._offset_indices(start_at=atom_delete_index, offset=-delete_length, dtype='atom')
                        residue_found = True

            structure.reset_state()

    return delete_indices

delete_residues

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

Deletes Residue instances from the Structure

Parameters:

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

    Residue instances to delete

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

    Residue indices to select the Residue instances of interest

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

    Residue numbers to select the Residue instances of interest

Returns:

  • list[Residue] | list

    Each deleted Residue

Source code in symdesign/structure/model.py
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def delete_residues(self, residues: Iterable[Residue] | None = None, indices: Iterable[int] | None = None,
                    numbers: Container[int] | None = 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
    """
    residues = super().delete_residues(residues=residues, numbers=numbers, indices=indices)
    if self.is_dependent() or not residues:  # There are no Residue instances to delete
        return residues
    structure: Structure

    # The routine below assumes the Residue instances are sorted in ascending order
    atom_index_offset_amount = 0
    for residue_idx, residue in enumerate(residues):
        # Find the Residue, Atom indices to delete
        # Offset these indices if prior indices have already been removed
        atom_delete_indices = [idx - atom_index_offset_amount for idx in residue.atom_indices]
        delete_length = len(atom_delete_indices)
        residue_index = residue.index - residue_idx
        # Offset the next Residue Atom indices by the incrementing amount
        atom_index_offset_amount += delete_length
        for structure_type in self.structure_containers:
            residue_found = False
            # Iterate over each Structure in each structure_container
            for structure in self.__getattribute__(structure_type):
                if residue_found:
                    # The Structure the Residue belongs to is already accounted for, just offset the indices
                    structure._offset_indices(start_at=0, offset=-delete_length, dtype='atom')
                    structure._offset_indices(start_at=0, offset=-1, dtype='residue')
                # try:  # Remove atom_delete_indices, residue_indices from Structure
                elif residue_index not in structure._residue_indices:
                    pass  # This structure is not the one of interest
                else:  # Remove atom_delete_indices, residue_index from Structure
                    structure._delete_indices(atom_delete_indices, dtype='atom')
                    structure._delete_indices([residue_index], dtype='residue')
                    residue_found = True

                structure.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 based on Pose numbering (1 to N) at the origin. No structural alignment is performed.

Parameters:

  • index (int) –

    The pose numbered location which 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

Source code in symdesign/structure/model.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
def insert_residue_type(self, index: int, residue_type: str, chain_id: str = None) -> Residue:
    """Insert a standard Residue type into the Structure based on Pose numbering (1 to N) at the origin.
    No structural alignment is performed.

    Args:
        index: The pose numbered location which 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
    """
    new_residue = super().insert_residue_type(index, residue_type, chain_id=chain_id)
    if self.is_dependent():
        return new_residue

    new_residue_atom_indices = new_residue.atom_indices
    structure: Structure

    # Must update other Structures indices
    for structure_type in self.structure_containers:
        structures = self.__getattribute__(structure_type)
        idx = 0
        # Iterate over Structures in each structure_container
        for idx, structure in enumerate(structures, idx):
            try:  # Update each Structure _residue_indices and _atom_indices with additional indices
                structure._insert_indices(
                    structure.residue_indices.index(index), [index], dtype='residue')
                structure._insert_indices(
                    structure.atom_indices.index(new_residue.start_index), new_residue_atom_indices, dtype='atom')
            except (ValueError, IndexError):
                # This should happen if the index isn't in the StructureBase.*_indices of interest
                # Edge case where the index is being appended to the c-terminus
                if index - 1 == structure.residue_indices[-1] and new_residue.chain_id == structure.chain_id:
                    structure._insert_indices(structure.number_of_residues, [index], dtype='residue')
                    structure._insert_indices(structure.number_of_atoms, new_residue_atom_indices, dtype='atom')
                else:
                    continue

            # This was the Structure with insertion and insert_indices proceeded successfully
            structure.reset_state()
            break
        else:  # No matching structure found. The structure_type container should be empty...
            continue
        # For each subsequent structure in the structure container, update the indices with the last index from
        # the prior structure
        prior_structure = structure
        for structure in structures[idx + 1:]:
            structure._start_indices(at=prior_structure.atom_indices[-1] + 1, dtype='atom')
            structure._start_indices(at=prior_structure.residue_indices[-1] + 1, dtype='residue')
            structure.reset_state()
            prior_structure = structure

    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 newly inserted Residue instances

Source code in symdesign/structure/model.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
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 newly inserted Residue instances
    """
    new_residues = super().insert_residues(index, new_residues, chain_id=chain_id)
    if self.is_dependent():
        return new_residues

    number_new_residues = len(new_residues)
    first_new_residue = new_residues[0]
    new_residues_chain_id = first_new_residue.chain_id
    atom_start_index = first_new_residue.start_index
    new_residue_atom_indices = list(range(atom_start_index, new_residues[-1].end_index))
    new_residue_indices = list(range(index, index + number_new_residues))
    structure: Structure
    structures: Iterable[Structure]

    # Must update other Structures indices
    for structure_type in self.structure_containers:
        structures = self.__getattribute__(structure_type)
        idx = 0
        # Iterate over Structures in each structure_container
        for idx, structure in enumerate(structures, idx):
            try:  # Update each Structure _residue_indices and _atom_indices with additional indices
                structure._insert_indices(
                    structure.residue_indices.index(index), [index], dtype='residue')
                structure._insert_indices(
                    structure.atom_indices.index(atom_start_index), new_residue_atom_indices, dtype='atom')
                break  # Move to the next container to update the indices by a set increment
            except (ValueError, IndexError):
                # This should happen if the index isn't in the StructureBase.*_indices of interest
                # Edge case where the index is being appended to the c-terminus
                if index - 1 == structure.residue_indices[-1] and new_residues_chain_id == structure.chain_id:
                    structure._insert_indices(structure.number_of_residues, new_residue_indices, dtype='residue')
                    structure._insert_indices(structure.number_of_atoms, new_residue_atom_indices, dtype='atom')
                else:
                    continue

            # This was the Structure with insertion and insert_indices proceeded successfully
            structure.reset_state()
            break
        else:  # The target structure wasn't found
            raise DesignError(
                f"{self.insert_residues.__name__}: Couldn't locate the Structure to be modified by the inserted "
                f"residues")
        # For each subsequent structure in the structure container, update the indices with the last index from
        # the prior structure
        prior_structure = structure
        for structure in structures[idx + 1:]:
            structure._start_indices(at=prior_structure.atom_indices[-1] + 1, dtype='atom')
            structure._start_indices(at=prior_structure.residue_indices[-1] + 1, dtype='residue')
            structure.reset_state()
            prior_structure = structure

    # self.log.debug(f'Deleted {number_new_residues} Residue instances')

    return new_residues

ContainsChains

ContainsChains(chains: bool | Sequence[Chain] = True, chain_ids: Iterable[str] = None, rename_chains: bool = False, as_mates: bool = False, **kwargs)

Bases: ContainsStructures

Implements methods to interact with a Structure which contains Chain instances

Parameters:

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

    A list of identifiers to assign to each Chain instance

  • chains (bool | Sequence[Chain], default: True ) –

    Whether to create Chain instances from passed Structure container instances, or existing Chain instances to create the Model with

  • rename_chains (bool, default: False ) –

    Whether to name each chain an incrementally new Alphabetical character

  • as_mates (bool, default: False ) –

    Whether Chain instances should be controlled by a captain (True), or be dependents

Source code in symdesign/structure/model.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
def __init__(self, chains: bool | Sequence[Chain] = True, chain_ids: Iterable[str] = None,
             rename_chains: bool = False, as_mates: bool = False, **kwargs):
    """Construct the instance

    Args:
        chain_ids: A list of identifiers to assign to each Chain instance
        chains: Whether to create Chain instances from passed Structure container instances, or existing Chain
            instances to create the Model with
        rename_chains: Whether to name each chain an incrementally new Alphabetical character
        as_mates: Whether Chain instances should be controlled by a captain (True), or be dependents
    """
    super().__init__(**kwargs)  # ContainsChains
    # Use the same list as default to save parsed chain ids
    self.original_chain_ids = self.chain_ids = []
    if chains:  # Populate chains
        self.structure_containers.append('_chains')
        if isinstance(chains, Sequence):
            # Set the chains accordingly, copying them to remove prior relationships
            self._chains = list(chains)
            self._copy_structure_containers()  # Copy each Chain in chains
            if as_mates:
                if self.residues is None:
                    raise DesignError(
                        f"Couldn't initialize {self.__class__.__name__}.chains as it is missing '.residues' while "
                        f"{as_mates=}"
                    )
            else:  # Create the instance from existing chains
                self.assign_residues_from_structures(chains)
                # Reindex all residue and atom indices
                self.reset_and_reindex_structures(self._chains)
                # Set the parent attribute for all containers
                self._update_structure_container_attributes(_parent=self)

            if chain_ids:
                for chain, id_ in zip(self.chains, chain_ids):
                    chain.chain_id = id_
            # By using extend, self.original_chain_ids are set as well
            self.chain_ids.extend([chain.chain_id for chain in self.chains])
        else:  # Create Chain instances from Residues
            self._chains = []
            self._create_chains(chain_ids=chain_ids)
            if as_mates:
                for chain in self.chains:
                    chain.make_parent()

        if rename_chains or not self.are_chain_ids_pdb_compatible():
            self.rename_chains()

        self.log.debug(f'Original chain_ids: {",".join(self.original_chain_ids)} | '
                       f'Loaded chain_ids: {",".join(self.chain_ids)}')
    else:
        self._chains = []

    if self.is_parent():
        reference_sequence = self.metadata.reference_sequence
        if isinstance(reference_sequence, dict):  # Was parsed from file
            self.set_reference_sequence_from_seqres(reference_sequence)

chains property

chains: list[Chain]

Returns the Chain instances which are contained in the instance

number_of_chains property

number_of_chains: int

Return the number of Chain instances in the Structure

chain_breaks property

chain_breaks: list[int]

Return the index where each of the Chain instances ends, i.e. at the c-terminal Residue

from_chains classmethod

from_chains(chains: Sequence[Chain], **kwargs)

Create an instance from a Sequence of Chain objects. Automatically renames all chains

Source code in symdesign/structure/model.py
1342
1343
1344
1345
@classmethod
def from_chains(cls, chains: Sequence[Chain], **kwargs):
    """Create an instance from a Sequence of Chain objects. Automatically renames all chains"""
    return cls(chains=chains, rename_chains=True, **kwargs)

has_dependent_chains

has_dependent_chains() -> bool

Returns True if the .chains are dependents, otherwise Returns False if .chains are symmetry mates

Source code in symdesign/structure/model.py
1410
1411
1412
def has_dependent_chains(self) -> bool:
    """Returns True if the .chains are dependents, otherwise Returns False if .chains are symmetry mates"""
    return '_chains' in self.structure_containers

is_parsed_multimodel

is_parsed_multimodel() -> bool

Returns True if parsing located multiple MODEL records, aka a 'multimodel' or multistate Structure

Source code in symdesign/structure/model.py
1414
1415
1416
def is_parsed_multimodel(self) -> bool:
    """Returns True if parsing located multiple MODEL records, aka a 'multimodel' or multistate Structure"""
    return self.chain_ids != self.original_chain_ids

are_chain_ids_pdb_compatible

are_chain_ids_pdb_compatible() -> bool

Returns True if the chain_ids are compatible with legacy PDB format

Source code in symdesign/structure/model.py
1486
1487
1488
1489
1490
1491
1492
def are_chain_ids_pdb_compatible(self) -> bool:
    """Returns True if the chain_ids are compatible with legacy PDB format"""
    for chain_id in self.chain_ids:
        if len(chain_id) > 1:
            return False

    return True

rename_chains

rename_chains(exclude_chains: Sequence = None)

Renames each chain an incrementally new Alphabetical character using Structure.available_letters

Parameters:

  • exclude_chains (Sequence, default: None ) –

    The chains which shouldn't be modified

Sets

self.chain_ids (list[str])

Source code in symdesign/structure/model.py
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
def rename_chains(self, exclude_chains: Sequence = None):
    """Renames each chain an incrementally new Alphabetical character using Structure.available_letters

    Args:
        exclude_chains: The chains which shouldn't be modified

    Sets:
        self.chain_ids (list[str])
    """
    if exclude_chains is None:
        exclude_chains = []

    # Update chain_ids, then each chain
    available_chain_ids = chain_id_generator()
    self.chain_ids = []
    for chain in self.chains:
        chain_id = next(available_chain_ids)
        while chain_id in exclude_chains:
            chain_id = next(available_chain_ids)
        chain.chain_id = chain_id
        self.chain_ids.append(chain_id)

renumber_residues_by_chain

renumber_residues_by_chain()

For each Chain instance, renumber Residue objects sequentially starting with 1

Source code in symdesign/structure/model.py
1516
1517
1518
1519
def renumber_residues_by_chain(self):
    """For each Chain instance, renumber Residue objects sequentially starting with 1"""
    for chain in self.chains:
        chain.renumber_residues()

get_chain

get_chain(chain_id: str) -> Chain | None

Return the Chain object specified by the passed ChainID from the Structure

Parameters:

  • chain_id (str) –

    The name of the Chain to query

Returns:

  • Chain | None

    The Chain if one was found

Source code in symdesign/structure/model.py
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
def get_chain(self, chain_id: str) -> Chain | None:
    """Return the Chain object specified by the passed ChainID from the Structure

    Args:
        chain_id: The name of the Chain to query

    Returns:
        The Chain if one was found
    """
    for idx, id_ in enumerate(self.chain_ids):
        if id_ == chain_id:
            try:
                return self.chains[idx]
            except IndexError:
                raise IndexError(
                    f'The number of chains in {repr(self)}, {self.number_of_chains} != {len(self.chain_ids)}, '
                    'the number of .chain_ids')
    return None

set_reference_sequence_from_seqres

set_reference_sequence_from_seqres(reference_sequence: dict[str, str])

If SEQRES was parsed, set the reference_sequence attribute from each parsed chain_id. Ensure that this is called after self._create_chains()

Source code in symdesign/structure/model.py
1540
1541
1542
1543
1544
1545
1546
1547
1548
def set_reference_sequence_from_seqres(self, reference_sequence: dict[str, str]):
    """If SEQRES was parsed, set the reference_sequence attribute from each parsed chain_id. Ensure that this is
    called after self._create_chains()
    """
    for original_chain, chain in zip(self.original_chain_ids, self.chains):
        try:
            chain._reference_sequence = reference_sequence[original_chain]
        except KeyError:  # original_chain not parsed in SEQRES
            pass

chain_id_generator staticmethod

chain_id_generator() -> Generator[str, None, None]

Provide a generator which produces all combinations of chain ID strings

Returns The generator producing a maximum 2 character string where single characters are exhausted, first in uppercase, then in lowercase

Source code in symdesign/structure/model.py
1558
1559
1560
1561
1562
1563
1564
1565
1566
@staticmethod
def chain_id_generator() -> Generator[str, None, None]:
    """Provide a generator which produces all combinations of chain ID strings

    Returns
        The generator producing a maximum 2 character string where single characters are exhausted,
            first in uppercase, then in lowercase
    """
    return chain_id_generator()

orient

orient(symmetry: str = None)

Orient a symmetric Structure at the origin with symmetry axis set on canonical axes defined by symmetry file

Sets the Structure with coordinates as described by a canonical orientation

Parameters:

  • symmetry (str, default: None ) –

    The symmetry of the Structure

Raises: SymmetryError: When the specified symmetry is incompatible with the Structure StructureException: When the orient program fails

Source code in symdesign/structure/model.py
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
def orient(self, symmetry: str = None):
    """Orient a symmetric Structure at the origin with symmetry axis set on canonical axes defined by symmetry file

    Sets the Structure with coordinates as described by a canonical orientation

    Args:
        symmetry: The symmetry of the Structure
    Raises:
        SymmetryError: When the specified symmetry is incompatible with the Structure
        StructureException: When the orient program fails
    """
    # These notes are obviated by the use of the below protocol with from_file() constructor
    # orient_oligomer.f program notes
    # C		Will not work in any of the infinite situations where a PDB file is f***ed up,
    # C		in ways such as but not limited to:
    # C     equivalent residues in different chains don't have the same numbering; different subunits
    # C		are all listed with the same chain ID (e.g. with incremental residue numbering) instead
    # C		of separate IDs; multiple conformations are written out for the same subunit structure
    # C		(as in an NMR ensemble), negative residue numbers, etc. etc.
    try:
        subunit_number = utils.symmetry.valid_subunit_number[symmetry]
    except KeyError:
        raise SymmetryError(
            f"{self.orient.__name__}: Symmetry {symmetry} isn't a valid symmetry. Please try one of: "
            f'{", ".join(utils.symmetry.valid_symmetries)}')

    number_of_subunits = self.number_of_chains
    multicomponent = False
    if symmetry == 'C1':
        self.log.debug("C1 symmetry doesn't have a canonical orientation. Translating to the origin")
        self.translate(-self.center_of_mass)
        return
    elif number_of_subunits > 1:
        if number_of_subunits != subunit_number:
            if number_of_subunits in utils.symmetry.multicomponent_valid_subunit_number.get(symmetry):
                multicomponent = True
            else:
                raise SymmetryError(
                    f"{self.name} couldn't be oriented: It has {number_of_subunits} subunits while a multiple of "
                    f'{subunit_number} are expected for symmetry={symmetry}')
    else:
        raise SymmetryError(
            f"{self.name}: Can't orient a Structure with only a single chain. No symmetry present")

    orient_input = Path(putils.orient_exe_dir, 'input.pdb')
    orient_output = Path(putils.orient_exe_dir, 'output.pdb')

    def clean_orient_input_output():
        orient_input.unlink(missing_ok=True)
        orient_output.unlink(missing_ok=True)

    clean_orient_input_output()
    orient_kwargs = {'out_path': str(orient_input)}
    if multicomponent:
        if not isinstance(self, ContainsEntities):
            raise SymmetryError(
                f"Couldn't {repr(self)}.{self.orient.__name__} as the symmetry is {multicomponent=}, however, there"
                f" are no .entities in the class {self.__class__.__name__}"
            )
        self.entities[0].write(assembly=True, **orient_kwargs)
    else:
        self.write(**orient_kwargs)

    name = self.name
    p = subprocess.Popen([putils.orient_exe_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, cwd=putils.orient_exe_dir)
    in_symm_file = os.path.join(putils.orient_exe_dir, 'symm_files', symmetry)
    stdout, stderr = p.communicate(input=in_symm_file.encode('utf-8'))
    self.log.debug(name + stdout.decode()[28:])
    self.log.debug(stderr.decode()) if stderr else None
    if not orient_output.exists() or orient_output.stat().st_size == 0:
        try:
            log_file = getattr(self.log.handlers[0], 'baseFilename', None)
        except IndexError:  # No handlers attached
            log_file = None
        log_message = f'. Check {log_file} for more information' if log_file else \
            f': {stderr.decode()}' if stderr else ''
        clean_orient_input_output()
        raise StructureException(
            f"{putils.orient_exe_path} couldn't orient {name}{log_message}")

    oriented_pdb = Model.from_file(str(orient_output), name=self.name, log=self.log)
    orient_fixed_struct = oriented_pdb.chains[0]
    if multicomponent:
        moving_struct = self.entities[0]
    else:
        moving_struct = self.chains[0]

    orient_fixed_seq = orient_fixed_struct.sequence
    moving_seq = moving_struct.sequence

    fixed_coords = orient_fixed_struct.ca_coords
    moving_coords = moving_struct.ca_coords
    if orient_fixed_seq != moving_seq:
        # Do an alignment, get selective indices, then follow with superposition
        self.log.debug(f'{self.orient.__name__}(): existing Chain {moving_struct.chain_id} and '
                       f'oriented Chain {orient_fixed_struct.chain_id} are being aligned for superposition')
        fixed_indices, moving_indices = get_equivalent_indices(orient_fixed_seq, moving_seq)
        fixed_coords = fixed_coords[fixed_indices]
        moving_coords = moving_coords[moving_indices]

    _, rot, tx = superposition3d(fixed_coords, moving_coords)

    self.transform(rotation=rot, translation=tx)
    clean_orient_input_output()

ContainsEntities

ContainsEntities(entities: bool | Sequence[Entity] = True, entity_info: dict[str, dict[dict | list | str]] = None, **kwargs)

Bases: ContainsChains

Implements methods to interact with a Structure which contains Entity instances

Parameters:

  • entities (bool | Sequence[Entity], default: True ) –

    Existing Entity instances used to construct the Structure, or evaluates False to skip creating Entity instances from the existing '.chains' Chain instances

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

    Metadata describing the Entity instances

  • **kwargs
Source code in symdesign/structure/model.py
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
def __init__(self, entities: bool | Sequence[Entity] = True, entity_info: dict[str, dict[dict | list | str]] = None,
             **kwargs):
    """Construct the instance

    Args:
        entities: Existing Entity instances used to construct the Structure, or evaluates False to skip creating
            Entity instances from the existing '.chains' Chain instances
        entity_info: Metadata describing the Entity instances
        **kwargs:
    """
    super().__init__(**kwargs)  # ContainsEntities

    self.entity_info = {} if entity_info is None else entity_info

    if entities:
        self.structure_containers.append('_entities')
        if isinstance(entities, Sequence):
            # Create the instance from existing entities
            self.assign_residues_from_structures(entities)
            # Set the entities accordingly, first copying, then resetting, and finally updating the parent
            self._entities = entities
            self._copy_structure_containers()
            self.reset_and_reindex_structures(self._entities)
            self._update_structure_container_attributes(_parent=self)
            rename_chains = kwargs.get('rename_chains')
            if rename_chains:  # Set each successive Entity to have an incrementally higher chain id
                available_chain_ids = chain_id_generator()
                for entity in self.entities:
                    entity.chain_id = next(available_chain_ids)
                    # If the full structure wanted contiguous chain_ids, this should be used
                    # for _ in range(entity.number_of_symmetry_mates):
                    #     # Discard ids
                    #     next(available_chain_ids)
                    # self.log.debug(f'Entity {entity.name} new chain identifier {entity.chain_id}')
                # self.chain_ids.extend([entity.chain_id for entity in self.entities])
        else:  # Provided as True
            self._entities = []
            self._create_entities(**kwargs)

        if not self.chain_ids:
            # Set chain_ids according to self.entities as it wasn't set by self.chains (probably False)
            self.chain_ids.extend([entity.chain_id for entity in self.entities])
    else:
        self._entities = []

    # If any of the entities are symmetric, ensure the new Model is aware they are
    for entity in self.entities:
        if entity.is_symmetric():
            self.symmetric_dependents = '_entities'
            break

entity_info instance-attribute property writable

entity_info: dict[str, dict[dict | list | str]] | dict = {} if entity_info is None else entity_info

Mapping of the Entity name to Metadata describing the Entity instance

entities property

entities: list[Entity]

Returns each of the Entity instances in the Structure

number_of_entities property

number_of_entities: int

Return the number of Entity instances in the Structure

entity_breaks property

entity_breaks: list[int]

Return the index where each of the Entity instances ends, i.e. at the c-terminal Residue

sequence property

sequence: str

Return the sequence of structurally modeled residues for every Entity instance

Returns:

  • str

    The concatenated sequence for all Entity instances combined

reference_sequence property

reference_sequence: str

Return the sequence for every Entity instance, constituting all Residues, not just structurally modeled ones

Returns:

  • str

    The concatenated reference sequences for all Entity instances combined

atom_indices_per_entity property

atom_indices_per_entity: list[list[int]]

Return the atom indices for each Entity

from_entities classmethod

from_entities(entities: list[Entity] | Structures, rename_chains: bool = True, **kwargs)

Construct a Structure instance from a container of Entity objects

Source code in symdesign/structure/model.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
@classmethod
def from_entities(cls, entities: list[Entity] | Structures, rename_chains: bool = True, **kwargs):
    """Construct a Structure instance from a container of Entity objects"""
    if not isinstance(entities, (list, Structures)):
        raise ValueError(
            f"{cls.__name__}.{cls.from_entities.__name__}() constructor received "
            f"'entities'={type(entities).__name__}. Expected list[Entity]"  # or Structures
        )
    return cls(entities=entities, chains=False, rename_chains=rename_chains, **kwargs)

format_header

format_header(**kwargs) -> str

Return any super().format_header()

Other Parameters:

  • assembly

    bool = False - Whether to write header details for the assembly

Returns:

  • str

    The .pdb file header string

Source code in symdesign/structure/model.py
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
def format_header(self, **kwargs) -> str:
    """Return any super().format_header()

    Keyword Args:
        assembly: bool = False - Whether to write header details for the assembly

    Returns:
        The .pdb file header string
    """
    return super().format_header(**kwargs)

retrieve_metadata_from_pdb

retrieve_metadata_from_pdb(biological_assembly: int = None) -> dict[str, Any] | dict

Query the PDB API for information on the PDB code found at the Model.name attribute

For each new instance, makes one call to the PDB API, plus an additional call for each Entity, and one more if biological_assembly is passed. If this has been loaded before, it uses the persistent wrapapi.APIDatabase

Parameters:

  • biological_assembly (int, default: None ) –

    The number of the biological assembly that is associated with this structural state

Sets

self.api_entry (dict[str, dict[Any] | float] | dict): {'assembly': [['A', 'B'], ...], 'entity': {'EntityID': {'chains': ['A', 'B', ...], 'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'} 'reference_sequence': 'MSLEHHHHHH...', 'thermophilicity': 1.0}, ...}, 'res': resolution, 'struct': {'space': space_group, 'a_b_c': (a, b, c), 'ang_a_b_c': (ang_a, ang_b, ang_c)} }

Source code in symdesign/structure/model.py
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
def retrieve_metadata_from_pdb(self, biological_assembly: int = None) -> dict[str, Any] | dict:
    """Query the PDB API for information on the PDB code found at the Model.name attribute

    For each new instance, makes one call to the PDB API, plus an additional call for each Entity, and one more
    if biological_assembly is passed. If this has been loaded before, it uses the persistent wrapapi.APIDatabase

    Args:
        biological_assembly: The number of the biological assembly that is associated with this structural state

    Sets:
        self.api_entry (dict[str, dict[Any] | float] | dict):
            {'assembly': [['A', 'B'], ...],
             'entity': {'EntityID':
                            {'chains': ['A', 'B', ...],
                             'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'}
                             'reference_sequence': 'MSLEHHHHHH...',
                             'thermophilicity': 1.0},
                        ...},
             'res': resolution,
             'struct': {'space': space_group, 'a_b_c': (a, b, c),
                        'ang_a_b_c': (ang_a, ang_b, ang_c)}
            }
    """
    # api_entry = self.api_entry
    # if api_entry is not None:  # Already tried to solve this
    #     return

    # if self.api_db:
    try:
        # retrieve_api_info = self.api_db.pdb.retrieve_data
        retrieve_api_info = resources.wrapapi.api_database_factory().pdb.retrieve_data
    except AttributeError:
        retrieve_api_info = query.pdb.query_pdb_by

    # if self.name:  # Try to solve API details from name
    parsed_name = self.name
    splitter_iter = iter('_-')  # 'entity, assembly'
    idx = count(-1)
    extra = None
    while len(parsed_name) != 4:
        try:  # To parse the name using standard PDB API entry ID's
            parsed_name, *extra = parsed_name.split(next(splitter_iter))
        except StopIteration:
            # We didn't find an EntryID in parsed_name from splitting typical PDB formatted strings
            self.log.debug(f"The name '{self.name}' can't be coerced to PDB API format")
            # api_entry = {}
            return {}
        else:
            next(idx)
    # Set the index to the index that was stopped at
    idx = next(idx)

    # At some point, len(parsed_name) == 4
    if biological_assembly is not None:
        # query_args.update(assembly_integer=self.assembly)
        # # self.api_entry.update(_get_assembly_info(self.name))
        api_entry = retrieve_api_info(entry=parsed_name) or {}
        api_entry['assembly'] = retrieve_api_info(entry=parsed_name, assembly_integer=biological_assembly)
        # ^ returns [['A', 'A', 'A', ...], ...]
    elif extra:  # Extra not None or []
        # Try to parse any found extra to an integer denoting entity or assembly ID
        integer, *non_sense = extra
        if integer.isdigit() and not non_sense:
            integer = int(integer)
            if idx == 0:  # Entity integer, such as 1ABC_1.pdb
                api_entry = dict(entity=retrieve_api_info(entry=parsed_name, entity_integer=integer))
                # retrieve_api_info returns
                # {'EntityID': {'chains': ['A', 'B', ...],
                #               'dbref': {'accession': ('Q96DC8',), 'db': 'UniProt'}
                #               'reference_sequence': 'MSLEHHHHHH...',
                #               'thermophilicity': 1.0},
                #  ...}
                parsed_name = f'{parsed_name}_{integer}'
            else:  # Get entry alone. This is an assembly or unknown conjugation. Either way entry info is needed
                api_entry = retrieve_api_info(entry=parsed_name) or {}

                if idx == 1:  # This is an assembly integer, such as 1ABC-1.pdb
                    api_entry['assembly'] = retrieve_api_info(entry=parsed_name, assembly_integer=integer)
        else:  # This isn't an integer or there are extra characters
            # It's likely they are extra characters that won't be of help
            # Tod0, try to collect anyway?
            self.log.debug(
                f"The name '{self.name}' contains extra info that can't be coerced to PDB API format")
            api_entry = {}
    elif extra is None:  # Nothing extra as it was correct length to begin with, just query entry
        api_entry = retrieve_api_info(entry=parsed_name)
    else:
        raise RuntimeError(
            f"This logic wasn't expected and shouldn't be allowed to persist: "
            f'self.name={self.name}, parse_name={parsed_name}, extra={extra}, idx={idx}')
    if api_entry:
        self.log.debug(f'Found PDB API information: '
                       f'{", ".join(f"{k}={v}" for k, v in api_entry.items())}')
        # Set the identified name to lowercase
        self.name = parsed_name.lower()
        for entity in self.entities:
            entity.name = entity.name.lower()

    return api_entry

get_entity

get_entity(entity_id: str) -> Entity | None

Retrieve an Entity by name

Parameters:

  • entity_id (str) –

    The name of the Entity to query

Returns:

  • Entity | None

    The Entity if one was found

Source code in symdesign/structure/model.py
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
def get_entity(self, entity_id: str) -> Entity | None:
    """Retrieve an Entity by name

    Args:
        entity_id: The name of the Entity to query

    Returns:
        The Entity if one was found
    """
    for entity in self.entities:
        if entity_id == entity.name:
            return entity
    return None

entity_from_chain

entity_from_chain(chain_id: str) -> Entity | None

Returns the entity associated with a particular chain id

Source code in symdesign/structure/model.py
2310
2311
2312
2313
2314
2315
def entity_from_chain(self, chain_id: str) -> Entity | None:
    """Returns the entity associated with a particular chain id"""
    for entity in self.entities:
        if chain_id == entity.chain_id:
            return entity
    return None

match_entity_by_seq

match_entity_by_seq(other_seq: str = None, force_closest: bool = True, tolerance: float = 0.7) -> Entity | None

From another sequence, returns the first matching chain from the corresponding Entity

Uses a local alignment to produce the match score

Parameters:

  • other_seq (str, default: None ) –

    The sequence to query

  • force_closest (bool, default: True ) –

    Whether to force the search if a perfect match isn't identified

  • tolerance (float, default: 0.7 ) –

    The acceptable difference between sequences to consider them the same Entity. Tuning this parameter is necessary if you have sequences which should be considered different entities, but are fairly similar

Returns:

  • Entity | None

    The matching Entity if one was found

Source code in symdesign/structure/model.py
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
def match_entity_by_seq(
    self, other_seq: str = None, force_closest: bool = True, tolerance: float = 0.7
) -> Entity | None:
    """From another sequence, returns the first matching chain from the corresponding Entity

    Uses a local alignment to produce the match score

    Args:
        other_seq: The sequence to query
        force_closest: Whether to force the search if a perfect match isn't identified
        tolerance: The acceptable difference between sequences to consider them the same Entity.
            Tuning this parameter is necessary if you have sequences which should be considered different entities,
            but are fairly similar

    Returns:
        The matching Entity if one was found
    """
    for entity in self.entities:
        if other_seq == entity.sequence:
            return entity

    # We didn't find an ideal match
    if force_closest:
        entity_alignment_scores = {}
        for entity in self.entities:
            alignment = generate_alignment(other_seq, entity.sequence, local=True)
            entity_alignment_scores[entity] = alignment.score

        max_score, max_score_entity = 0, None
        for entity, score in entity_alignment_scores.items():
            normalized_score = score / len(entity.sequence)
            if normalized_score > max_score:
                max_score = normalized_score  # alignment_score_d[entity]
                max_score_entity = entity

        if max_score > tolerance:
            return max_score_entity

    return None

SymmetryOpsMixin

SymmetryOpsMixin(sym_entry: SymEntry | int = None, symmetry: str = None, transformations: list[TransformationMapping] = None, uc_dimensions: list[float] = None, symmetry_operators: ndarray | list = None, rotation_matrices: ndarray | list = None, translation_matrices: ndarray | list = None, surrounding_uc: bool = True, **kwargs)

Bases: ABC

Implements methods to interact with symmetric Structure instances

Parameters:

  • sym_entry (SymEntry | int, default: None ) –

    The SymEntry which specifies all symmetry parameters

  • symmetry (str, default: None ) –

    The name of a symmetry to be searched against compatible symmetries

  • transformations (list[TransformationMapping], default: None ) –

    Transformation operations that reproduce the oligomeric/assembly for each Entity

  • rotation_matrices (ndarray | list, default: None ) –

    Rotation operations that create the symmetric state

  • translation_matrices (ndarray | list, default: None ) –

    Translation operations that create the symmetric state

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

    The unit cell dimensions for the crystalline symmetry

  • symmetry_operators (ndarray | list, default: None ) –

    A set of custom expansion matrices

  • surrounding_uc (bool, default: True ) –

    Whether the 3x3 layer group, or 3x3x3 space group should be generated

Source code in symdesign/structure/model.py
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
def __init__(self, sym_entry: utils.SymEntry.SymEntry | int = None, symmetry: str = None,
             transformations: list[types.TransformationMapping] = None, uc_dimensions: list[float] = None,
             symmetry_operators: np.ndarray | list = None, rotation_matrices: np.ndarray | list = None,
             translation_matrices: np.ndarray | list = None, surrounding_uc: bool = True, **kwargs):
    """Construct the instance

    Args:
        sym_entry: The SymEntry which specifies all symmetry parameters
        symmetry: The name of a symmetry to be searched against compatible symmetries
        transformations: Transformation operations that reproduce the oligomeric/assembly for each Entity
        rotation_matrices: Rotation operations that create the symmetric state
        translation_matrices: Translation operations that create the symmetric state
        uc_dimensions: The unit cell dimensions for the crystalline symmetry
        symmetry_operators: A set of custom expansion matrices
        surrounding_uc: Whether the 3x3 layer group, or 3x3x3 space group should be generated
    """
    super().__init__(**kwargs)  # SymmetryOpsMixin
    self._expand_matrices = self._expand_translations = None
    self.set_symmetry(sym_entry=sym_entry, symmetry=symmetry, uc_dimensions=uc_dimensions,
                      operators=symmetry_operators, rotations=rotation_matrices, translations=translation_matrices,
                      transformations=transformations, surrounding_uc=surrounding_uc)

sym_entry property writable

sym_entry: SymEntry | None

The SymEntry specifies the symmetric parameters for the utilized symmetry

point_group_symmetry property

point_group_symmetry: str | None

The point group underlying the resulting SymEntry

dimension property

dimension: int | None

The dimension of the symmetry from None, 0, 2, or 3

uc_dimensions property

uc_dimensions: tuple[float, float, float, float, float, float] | None

The unit cell dimensions for the lattice specified by lengths a, b, c and angles alpha, beta, gamma

Returns:

  • tuple[float, float, float, float, float, float] | None

    length a, length b, length c, angle alpha, angle beta, angle gamma

cryst_record property writable

cryst_record: str | None

Return the symmetry parameters as a CRYST1 entry

expand_matrices property

expand_matrices: ndarray

The symmetry rotations to generate each of the symmetry mates

expand_translations property

expand_translations: ndarray

The symmetry translations to generate each of the symmetry mates

chain_transforms property

chain_transforms: list[TransformationMapping]

Returns the transformation operations for each of the symmetry mates (excluding the ASU)

number_of_symmetric_residues property

number_of_symmetric_residues: int

Describes the number of Residues when accounting for symmetry mates

number_of_symmetry_mates property

number_of_symmetry_mates: int

Describes the number of symmetric copies present in the coordinates

number_of_uc_symmetry_mates property

number_of_uc_symmetry_mates: int

Describes the number of symmetry mates present in the unit cell

asu_model_index property

asu_model_index: int

The asu equivalent model in the SymmetricModel. Zero-indexed

asu_indices property

asu_indices: slice

Return the ASU indices

symmetric_coords property

symmetric_coords: ndarray | None

Return a view of the symmetric Coords

symmetric_coords_split property

symmetric_coords_split: list[ndarray]

A view of the symmetric coords split at different symmetric models

center_of_mass_symmetric property

center_of_mass_symmetric: ndarray

The center of mass for the symmetric system with shape (3,)

center_of_mass_symmetric_models property

center_of_mass_symmetric_models: ndarray

The center of mass points for each symmetry mate in the symmetric system with shape (number_of_symmetry_mates, 3)

format_biomt

format_biomt(**kwargs) -> str

Return the SymmetricModel expand_matrices as a BIOMT record

Returns:

  • str

    The BIOMT REMARK 350 with PDB file formatting

Source code in symdesign/structure/model.py
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
def format_biomt(self, **kwargs) -> str:
    """Return the SymmetricModel expand_matrices as a BIOMT record

    Returns:
        The BIOMT REMARK 350 with PDB file formatting
    """
    if self.is_symmetric():
        if self.dimension < 2:
            return '%s\n' % '\n'.join(
                'REMARK 350   BIOMT{:1d}{:4d}{:10.6f}{:10.6f}{:10.6f}{:15.5f}            '.format(
                    v_idx, m_idx, *vec, point)
                for m_idx, (mat, tx) in enumerate(
                    zip(self.expand_matrices.tolist(), self.expand_translations.tolist()), 1)
                for v_idx, (vec, point) in enumerate(zip(mat, tx), 1)
            )
    return ''

format_header

format_header(**kwargs) -> str

Returns any super().format_header() along with the BIOMT record

Returns:

  • str

    The .pdb file header string

Source code in symdesign/structure/model.py
2443
2444
2445
2446
2447
2448
2449
def format_header(self, **kwargs) -> str:
    """Returns any super().format_header() along with the BIOMT record

    Returns:
        The .pdb file header string
    """
    return super().format_header(**kwargs) + self.format_biomt()

set_symmetry

set_symmetry(sym_entry: SymEntry | int = None, symmetry: str = None, crystal: bool = False, cryst_record: str = None, uc_dimensions: list[float] = None, **kwargs)

Set the model symmetry using the CRYST1 record, or the unit cell dimensions and the Hermann-Mauguin symmetry notation (in CRYST1 format, ex P432) for the Model assembly. If the assembly is a point group, only the symmetry notation is required

Parameters:

  • sym_entry (SymEntry | int, default: None ) –

    The SymEntry which specifies all symmetry parameters

  • symmetry (str, default: None ) –

    The name of a symmetry to be searched against compatible symmetries

  • crystal (bool, default: False ) –

    Whether crystalline symmetry should be used

  • cryst_record (str, default: None ) –

    If a CRYST1 record is known and should be used

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

    The unit cell dimensions for the crystalline symmetry

Source code in symdesign/structure/model.py
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
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
def set_symmetry(self, sym_entry: utils.SymEntry.SymEntry | int = None, symmetry: str = None,
                 crystal: bool = False, cryst_record: str = None, uc_dimensions: list[float] = None,
                 **kwargs):
    """Set the model symmetry using the CRYST1 record, or the unit cell dimensions and the Hermann-Mauguin symmetry
    notation (in CRYST1 format, ex P432) for the Model assembly. If the assembly is a point group, only the symmetry
    notation is required

    Args:
        sym_entry: The SymEntry which specifies all symmetry parameters
        symmetry: The name of a symmetry to be searched against compatible symmetries
        crystal: Whether crystalline symmetry should be used
        cryst_record: If a CRYST1 record is known and should be used
        uc_dimensions: The unit cell dimensions for the crystalline symmetry
    """
    # Try to solve for symmetry as uc_dimensions are needed for cryst ops, if available
    crystal_symmetry = None
    if symmetry is not None:
        # Ensure conversion to Hermann–Mauguin notation. ex: P23 not P 2 3
        symmetry = ''.join(symmetry.split())

    if cryst_record:
        self.cryst_record = cryst_record
        crystal = True
    else:
        cryst_record = self.cryst_record  # Populated above or from file parsing
        if uc_dimensions and symmetry:
            crystal_symmetry = symmetry
            crystal = True

    if cryst_record:  # Populated above or from file parsing
        self.log.debug(f'Parsed record: {cryst_record.strip()}')
        if uc_dimensions is None and symmetry is None:  # Only if didn't provide either
            uc_dimensions, crystal_symmetry = parse_cryst_record(cryst_record)
            crystal_symmetry = ''.join(crystal_symmetry)
        self.log.debug(f'Found uc_dimensions={uc_dimensions}, symmetry={crystal_symmetry}')

    if crystal:  # CRYST in symmetry.upper():
        if sym_entry is None:
            sym_entry = utils.SymEntry.CrystRecord

    number_of_entities = self.number_of_entities
    if sym_entry is not None:
        if isinstance(sym_entry, utils.SymEntry.SymEntry):
            if sym_entry.needs_cryst_record():  # Replace with relevant info from the CRYST1 record
                if sym_entry.is_token():
                    # Create a new SymEntry
                    sym_entry = utils.SymEntry.CrystSymEntry(
                        space_group=crystal_symmetry,
                        sym_map=[crystal_symmetry] + ['C1' for _ in range(number_of_entities)])
                    # Set the uc_dimensions as they must be parsed or provided
                    self.log.critical(f'Setting {self}.sym_entry to new crystalline symmetry {sym_entry}')
                elif sym_entry.resulting_symmetry == crystal_symmetry:
                    # This is already the specified SymEntry, use the CRYST record to set cryst_record
                    self.log.critical(f'Setting {self}.sym_entry to {sym_entry}')
                else:
                    raise SymmetryError(
                        f"The parsed CRYST record with symmetry '{crystal_symmetry}' doesn't match the symmetry "
                        f"'{sym_entry.resulting_symmetry}' specified by the provided {type(sym_entry).__name__}"
                    )
                sym_entry.uc_dimensions = uc_dimensions
                sym_entry.cryst_record = self.cryst_record
            # else:  # SymEntry is set up properly
            #     self.sym_entry = sym_entry
        else:  # Try to solve using sym_entry as integer and any info in symmetry.
            sym_entry = utils.SymEntry.parse_symmetry_to_sym_entry(
                sym_entry_number=sym_entry, symmetry=symmetry)
    elif symmetry:  # Provided without uc_dimensions, crystal=True, or cryst_record. Assuming point group
        sym_entry = utils.SymEntry.parse_symmetry_to_sym_entry(
            symmetry=symmetry,
            # The below fails as most of the time entity.symmetry isn't set up at this point
            # sym_map=[symmetry] + [entity.symmetry for entity in self.entities]
        )
    else:  # No symmetry was provided
        # self.sym_entry/self.symmetry can be None
        return

    # Ensure the number of Entity instances matches the SymEntry groups
    n_groups = sym_entry.number_of_groups
    if number_of_entities != n_groups:
        if n_groups == 1:
            verb = 'was'
        else:
            verb = 'were'

        raise SymmetryError(
            f'The {self.__class__.__name__} has {number_of_entities} entities. '
            f'{n_groups} {verb} expected based on the {repr(sym_entry)} specified'
        )
    self.sym_entry = sym_entry

reset_mates

reset_mates()

Remove oligomeric chains. They should be generated fresh

Source code in symdesign/structure/model.py
2547
2548
2549
def reset_mates(self):
    """Remove oligomeric chains. They should be generated fresh"""
    self._chains.clear()

is_surrounding_uc

is_surrounding_uc() -> bool

Returns True if the current coordinates contains symmetry mates from the surrounding unit cells

Source code in symdesign/structure/model.py
2655
2656
2657
2658
2659
2660
2661
def is_surrounding_uc(self) -> bool:
    """Returns True if the current coordinates contains symmetry mates from the surrounding unit cells"""
    if self.dimension > 0:
        # This is True if self.number_of_symmetry_mates was set to a larger value
        return self.number_of_symmetry_mates > self.number_of_uc_symmetry_mates
    else:
        return False

make_indices_symmetric

make_indices_symmetric(indices: Iterable[int], dtype: atom_or_residue_literal = 'atom') -> list[int]

Extend asymmetric indices using the symmetry state across atom or residue indices

Parameters:

  • indices (Iterable[int]) –

    The asymmetric indices to symmetrize

  • dtype (atom_or_residue_literal, default: 'atom' ) –

    The type of indices to perform symmetrization with

Returns:

  • list[int]

    The symmetric indices of the asymmetric input

Source code in symdesign/structure/model.py
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
def make_indices_symmetric(self, indices: Iterable[int], dtype: atom_or_residue_literal = 'atom') -> list[int]:
    """Extend asymmetric indices using the symmetry state across atom or residue indices

    Args:
        indices: The asymmetric indices to symmetrize
        dtype: The type of indices to perform symmetrization with

    Returns:
        The symmetric indices of the asymmetric input
    """
    try:
        jump_size = getattr(self, f'number_of_{dtype}s')
    except AttributeError:
        raise AttributeError(
            f"The dtype 'number_of_{dtype}' wasn't found in the {self.__class__.__name__} object. "
            "'Possible values of dtype are 'atom' or 'residue'")

    model_jumps = [jump_size * model_num for model_num in range(self.number_of_symmetry_mates)]
    return [idx + model_jump for model_jump in model_jumps for idx in indices]

return_symmetric_copies

return_symmetric_copies(structure: StructureBase, **kwargs) -> list[StructureBase]

Expand the provided Structure using self.symmetry for the symmetry specification

Parameters:

  • structure (StructureBase) –

    A StructureBase instance containing .coords method/attribute

Returns:

  • list[StructureBase]

    The symmetric copies of the input structure

Source code in symdesign/structure/model.py
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
def return_symmetric_copies(self, structure: StructureBase, **kwargs) -> list[StructureBase]:
    """Expand the provided Structure using self.symmetry for the symmetry specification

    Args:
        structure: A StructureBase instance containing .coords method/attribute

    Returns:
        The symmetric copies of the input structure
    """
    number_of_symmetry_mates = self.number_of_symmetry_mates
    sym_coords = self.return_symmetric_coords(structure.coords)

    sym_mates = []
    for coord_set in np.split(sym_coords, number_of_symmetry_mates):
        symmetry_mate = structure.copy()
        symmetry_mate.coords = coord_set
        sym_mates.append(symmetry_mate)

    return sym_mates

generate_symmetric_coords

generate_symmetric_coords(surrounding_uc: bool = True)

Expand the asu using self.symmetry for the symmetry specification, and optional unit cell dimensions if self.dimension > 0. Expands assembly to complete point group, unit cell, or surrounding unit cells

Parameters:

  • surrounding_uc (bool, default: True ) –

    Whether the 3x3 layer group, or 3x3x3 space group should be generated

Source code in symdesign/structure/model.py
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
def generate_symmetric_coords(self, surrounding_uc: bool = True):
    """Expand the asu using self.symmetry for the symmetry specification, and optional unit cell dimensions if
    self.dimension > 0. Expands assembly to complete point group, unit cell, or surrounding unit cells

    Args:
        surrounding_uc: Whether the 3x3 layer group, or 3x3x3 space group should be generated
    """
    self.log.debug('Generating symmetric coords')
    if surrounding_uc:
        if self.dimension > 0:
            if self.dimension == 3:
                uc_number = 27
            elif self.dimension == 2:
                uc_number = 9
            else:
                assert_never(self.dimension)
            # Set the number_of_symmetry_mates to account for the unit cell number
            # This results in is_surrounding_uc() being True during return_symmetric_coords()
            self._number_of_symmetry_mates = self.number_of_uc_symmetry_mates * uc_number

    # Set the self.symmetric_coords property
    self._symmetric_coords = Coordinates(self.return_symmetric_coords(self.coords))

cart_to_frac

cart_to_frac(cart_coords: ndarray | Iterable | int | float) -> ndarray

Return fractional coordinates from cartesian coordinates From http://www.ruppweb.org/Xray/tutorial/Coordinate%20system%20transformation.htm

Parameters:

  • cart_coords (ndarray | Iterable | int | float) –

    The cartesian coordinates of a unit cell

Returns:

  • ndarray

    The fractional coordinates of a unit cell

Source code in symdesign/structure/model.py
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
def cart_to_frac(self, cart_coords: np.ndarray | Iterable | int | float) -> np.ndarray:
    """Return fractional coordinates from cartesian coordinates
    From http://www.ruppweb.org/Xray/tutorial/Coordinate%20system%20transformation.htm

    Args:
        cart_coords: The cartesian coordinates of a unit cell

    Returns:
        The fractional coordinates of a unit cell
    """
    if self.uc_dimensions is None:
        raise ValueError(
            "Can't manipulate the unit cell. No unit cell dimensions were passed")

    return np.matmul(cart_coords, np.transpose(self.sym_entry.deorthogonalization_matrix))

frac_to_cart

frac_to_cart(frac_coords: ndarray | Iterable | int | float) -> ndarray

Return cartesian coordinates from fractional coordinates From http://www.ruppweb.org/Xray/tutorial/Coordinate%20system%20transformation.htm

Parameters:

  • frac_coords (ndarray | Iterable | int | float) –

    The fractional coordinates of a unit cell

Returns:

  • ndarray

    The cartesian coordinates of a unit cell

Source code in symdesign/structure/model.py
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
def frac_to_cart(self, frac_coords: np.ndarray | Iterable | int | float) -> np.ndarray:
    """Return cartesian coordinates from fractional coordinates
    From http://www.ruppweb.org/Xray/tutorial/Coordinate%20system%20transformation.htm

    Args:
        frac_coords: The fractional coordinates of a unit cell

    Returns:
        The cartesian coordinates of a unit cell
    """
    if self.uc_dimensions is None:
        raise ValueError(
            "Can't manipulate the unit cell. No unit cell dimensions were passed")

    return np.matmul(frac_coords, np.transpose(self.sym_entry.orthogonalization_matrix))

return_symmetric_coords

return_symmetric_coords(coords: list | ndarray) -> ndarray

Provided an input set of coordinates, return the symmetrized coordinates corresponding to the SymmetricModel

Parameters:

  • coords (list | ndarray) –

    The coordinates to symmetrize

Returns:

  • ndarray

    The symmetrized coordinates

Source code in symdesign/structure/model.py
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
def return_symmetric_coords(self, coords: list | np.ndarray) -> np.ndarray:
    """Provided an input set of coordinates, return the symmetrized coordinates corresponding to the SymmetricModel

    Args:
        coords: The coordinates to symmetrize

    Returns:
        The symmetrized coordinates
    """
    # surrounding_uc: bool = True
    #   surrounding_uc: Whether the 3x3 layer group, or 3x3x3 space group should be generated
    if self.dimension > 0:
        if self.is_surrounding_uc():
            shift_3d = [0., 1., -1.]
            if self.dimension == 3:
                z_shifts = shift_3d
            elif self.dimension == 2:
                z_shifts = [0.]
            else:
                assert_never(self.dimension)

            uc_frac_coords = self.return_unit_cell_coords(coords, fractional=True)
            surrounding_frac_coords = \
                np.concatenate([uc_frac_coords + [x, y, z] for x in shift_3d for y in shift_3d for z in z_shifts])
            return self.frac_to_cart(surrounding_frac_coords)
        else:
            return self.return_unit_cell_coords(coords)
    else:  # self.dimension = 0 or None
        return (np.matmul(np.tile(coords, (self.number_of_symmetry_mates, 1, 1)),
                          self._expand_matrices) + self._expand_translations).reshape(-1, 3)

return_unit_cell_coords

return_unit_cell_coords(coords: ndarray, fractional: bool = False) -> ndarray

Return the unit cell coordinates from a set of coordinates for the specified SymmetricModel

Parameters:

  • coords (ndarray) –

    The cartesian coordinates to expand to the unit cell

  • fractional (bool, default: False ) –

    Whether to return coordinates in fractional or cartesian (False) unit cell frame

Returns:

  • ndarray

    All unit cell coordinates

Source code in symdesign/structure/model.py
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
def return_unit_cell_coords(self, coords: np.ndarray, fractional: bool = False) -> np.ndarray:
    """Return the unit cell coordinates from a set of coordinates for the specified SymmetricModel

    Args:
        coords: The cartesian coordinates to expand to the unit cell
        fractional: Whether to return coordinates in fractional or cartesian (False) unit cell frame

    Returns:
        All unit cell coordinates
    """
    model_coords = (np.matmul(np.tile(self.cart_to_frac(coords), (self.number_of_uc_symmetry_mates, 1, 1)),
                              self._expand_matrices) + self._expand_translations).reshape(-1, 3)
    if fractional:
        return model_coords
    else:
        return self.frac_to_cart(model_coords)

find_contacting_asu

find_contacting_asu(distance: float = 8.0, **kwargs) -> list[Entity]

Find the maximally contacting symmetry mate for each Entity and return the corresponding Entity instances

Parameters:

  • distance (float, default: 8.0 ) –

    The distance to check for contacts

Returns:

  • list[Entity]

    The minimal set of Entities containing the maximally touching configuration

Source code in symdesign/structure/model.py
2874
2875
2876
2877
2878
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
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
def find_contacting_asu(self, distance: float = 8., **kwargs) -> list[Entity]:
    """Find the maximally contacting symmetry mate for each Entity and return the corresponding Entity instances

    Args:
        distance: The distance to check for contacts

    Returns:
        The minimal set of Entities containing the maximally touching configuration
    """
    entities = self.entities
    if not entities:
        # The SymmetricModel was probably set without them. Create them, then try to find the asu
        self._create_entities()
        entities = self.entities

    number_of_entities = len(entities)
    if number_of_entities != 1:
        idx = count()
        chain_combinations: list[tuple[Entity, Entity]] = []
        entity_combinations: list[tuple[Entity, Entity]] = []
        contact_count = \
            np.zeros(sum(map(math.prod, combinations((entity.number_of_symmetry_mates for entity in entities), 2))))
        for entity1, entity2 in combinations(entities, 2):
            for chain1 in entity1.chains:
                chain_cb_coord_tree = BallTree(chain1.cb_coords)
                for chain2 in entity2.chains:
                    entity_combinations.append((entity1, entity2))
                    chain_combinations.append((chain1, chain2))
                    contact_count[next(idx)] = \
                        chain_cb_coord_tree.two_point_correlation(chain2.cb_coords, [distance])[0]

        max_contact_idx = contact_count.argmax()
        additional_chains = []
        max_chains = list(chain_combinations[max_contact_idx])
        if len(max_chains) != number_of_entities:  # We found 2 entities at this point
            # find the indices where either of the maximally contacting chains are utilized
            selected_chain_indices = {idx for idx, chain_pair in enumerate(chain_combinations)
                                      if max_chains[0] in chain_pair or max_chains[1] in chain_pair}
            remaining_entities = set(entities).difference(entity_combinations[max_contact_idx])
            for entity in remaining_entities:  # get the max contacts and the associated entity and chain indices
                # find the indices where the missing entity is utilized
                remaining_indices = \
                    {idx for idx, entity_pair in enumerate(entity_combinations) if entity in entity_pair}
                # pair_position = [0 if entity_pair[0] == entity else 1
                #                  for idx, entity_pair in enumerate(entity_combinations) if entity in entity_pair]
                # only use those where found asu chains already occur
                viable_remaining_indices = list(remaining_indices.intersection(selected_chain_indices))
                # out of the viable indices where the selected chains are matched with the missing entity,
                # find the highest contact
                max_idx = contact_count[viable_remaining_indices].argmax()
                for entity_idx, entity_in_combo in enumerate(
                        entity_combinations[viable_remaining_indices[max_idx]]):
                    if entity == entity_in_combo:
                        additional_chains.append(chain_combinations[viable_remaining_indices[max_idx]][entity_idx])

        new_entities = max_chains + additional_chains
        # Rearrange the entities to have the same order as provided
        entities = [new_entity for entity in entities for new_entity in new_entities if entity == new_entity]

    return entities

get_contacting_asu

get_contacting_asu(distance: float = 8.0, **kwargs) -> SymmetricModel

Find the maximally contacting symmetry mate for each Entity and return the corresponding Entity instances as a new Pose

If the chain IDs of the asu are the same, then chain IDs will automatically be renamed

Parameters:

  • distance (float, default: 8.0 ) –

    The distance to check for contacts

Returns:

  • SymmetricModel

    A new Model with the minimal set of Entity instances. Will also be symmetric

Source code in symdesign/structure/model.py
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
def get_contacting_asu(self, distance: float = 8., **kwargs) -> SymmetricModel:  # Todo -> Self python 3.11
    """Find the maximally contacting symmetry mate for each Entity and return the corresponding Entity instances as
     a new Pose

    If the chain IDs of the asu are the same, then chain IDs will automatically be renamed

    Args:
        distance: The distance to check for contacts

    Returns:
        A new Model with the minimal set of Entity instances. Will also be symmetric
    """
    if self.number_of_entities == 1:
        return self.copy()

    entities = self.find_contacting_asu(distance=distance, **kwargs)

    if len({entity.chain_id for entity in entities}) != len(entities):
        rename = True
    else:
        rename = False

    cls = type(self)
    # assert cls is Pose, f"Can't {self.get_contacting_asu.__name__} for the class={cls}. Only for Pose"
    return cls.from_entities(
        entities, name=f'{self.name}-asu', log=self.log, sym_entry=self.sym_entry, rename_chains=rename,
        cryst_record=self.cryst_record, **kwargs)  # , biomt_header=self.format_biomt(),

set_contacting_asu

set_contacting_asu(from_assembly: bool = False, **kwargs)

Find the maximally contacting symmetry mate for each Entity, then set the Pose with this info

Parameters:

  • from_assembly (bool, default: False ) –

    Whether the ASU should be set fresh from the entire assembly instances

Other Parameters:

  • distance

    float = 8.0 - The distance to check for contacts

Sets

self: To a SymmetricModel with the minimal set of Entities containing the maximally touching configuration

Source code in symdesign/structure/model.py
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
def set_contacting_asu(self, from_assembly: bool = False, **kwargs):
    """Find the maximally contacting symmetry mate for each Entity, then set the Pose with this info

    Args:
        from_assembly: Whether the ASU should be set fresh from the entire assembly instances

    Keyword Args:
        distance: float = 8.0 - The distance to check for contacts

    Sets:
        self: To a SymmetricModel with the minimal set of Entities containing the maximally touching configuration
    """
    number_of_entities = self.number_of_entities
    if not self.is_symmetric():
        raise SymmetryError(
            f"Couldn't {self.set_contacting_asu.__name__}() with the asymmetric {repr(self)}"
        )
    elif number_of_entities == 1:
        return  # This can't be set any better

    # Check to see if the parsed Model is already represented symmetrically
    if from_assembly or self.has_dependent_chains():  # and self.is_asymmetric_mates() and not preserve_asymmetry:
        # If .from_chains() or .from_file(), ensure the SymmetricModel is an asu
        self.log.debug(f'Setting the {repr(self)} to an ASU from a symmetric representation. '
                       "This method hasn't been thoroughly debugged")
        # Essentially performs,
        # self.assign_residues_from_structures(self.entities)
        # however, without _assign_residues(), the containers are not updated.
        # Set base Structure attributes
        new_coords = []
        new_atoms = []
        new_residues = []
        for entity in enumerate(self.entities):
            new_coords.append(entity.coords)
            new_atoms.extend(entity.atoms)
            new_residues.extend(entity.residues)

        self._coords = Coordinates(np.concatenate(new_coords))
        self._atom_indices = list(range(len(new_atoms)))
        self._atoms.set(new_atoms)
        self._residue_indices = list(range(len(new_residues)))
        self._residues.set(new_residues)

        # Remove extra chains by creating fresh
        self._create_chains()
        # Update entities to reflect new indices
        self.reset_structures_states(self.entities)
        # Recurse this call to ensure that the entities are contacting
        self.set_contacting_asu(**kwargs)
        # else:
        #     raise SymmetryError(
        #         f"Couldn't {self.set_contacting_asu.__name__}() with the number of parsed chains, "
        #         f"{self.number_of_chains}. When symmetry={self.symmetry} and the number of entities is "
        #         f"{self.number_of_entities}, the number of symmetric chains should be "
        #         f'{number_of_entities * self.number_of_symmetry_mates}'
        #     )
    else:  # number_of_entities == number_of_chains:
        self.log.debug(f'Finding the ASU with the most contacting interface')
        entities = self.find_contacting_asu(**kwargs)

        # With perfect symmetry, v this is sufficient
        self._no_reset = True
        self.coords = np.concatenate([entity.coords for entity in entities])
        del self._no_reset

Chain

Chain(chain_id: str = None, name: str = None, **kwargs)

Bases: Structure, MetricsMixin

A grouping of Atom, Coordinates, and Residue instances, typically from a connected polymer

Parameters:

  • chain_id (str, default: None ) –

    The name of the Chain identifier to use for this instance

  • name (str, default: None ) –

    The name of the Chain identifier to use for this instance. Typically used by Entity subclasses.

Source code in symdesign/structure/model.py
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
def __init__(self, chain_id: str = None, name: str = None, **kwargs):
    """Construct the instance

    Args:
        chain_id: The name of the Chain identifier to use for this instance
        name: The name of the Chain identifier to use for this instance. Typically used by Entity subclasses.
    """
    kwargs['name'] = name = name if name else chain_id
    super().__init__(**kwargs)  # Chain
    if type(self) is Chain and name is not None:
        # Only if this instance is a Chain, not Entity, set the chain_id
        self.chain_id = name

chain_id property writable

chain_id: str

The Chain ID for the instance

entity property

entity: Entity | None

The Entity associated with the instance

entity_id property

entity_id: str

The Entity ID associated with the instance

reference_sequence property

reference_sequence: str

Return the entire sequence, constituting all described residues, not just structurally modeled ones

Returns:

  • str

    The sequence according to the Entity reference, or the Structure sequence if no reference available

calculate_metrics

calculate_metrics(**kwargs) -> dict[str, Any]
Source code in symdesign/structure/model.py
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
def calculate_metrics(self, **kwargs) -> dict[str, Any]:
    """"""
    self.log.warning(f"{self.calculate_metrics.__name__} doesn't calculate anything yet...")
    return {
        # 'name': self.name,
        # 'n_terminal_helix': self.is_termini_helical(),
        # 'c_terminal_helix': self.is_termini_helical(termini='c'),
        # 'thermophile': thermophile
        # 'number_of_residues': self.number_of_residues,
    }

Entity

Entity(operators: tuple[ndarray | list[list[float]], ndarray | list[float]] | ndarray = None, rotations: ndarray | list[list[float]] = None, translations: ndarray | list[float] = None, **kwargs)

Bases: SymmetryOpsMixin, ContainsChains, Chain

Maps a biological instance of a Structure which ContainsChains(1-N) and is a Complex, to a single GeneProduct

Parameters:

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

    A set of symmetry operations to designate how to apply symmetry

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

    A set of rotation matrices used to recapitulate the SymmetricModel from the asymmetric unit

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

    A set of translation vectors used to recapitulate the SymmetricModel from the asymmetric unit

Source code in symdesign/structure/model.py
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
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
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
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
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
3335
3336
3337
3338
def __init__(self,
             operators: tuple[np.ndarray | list[list[float]], np.ndarray | list[float]] | np.ndarray = None,
             rotations: np.ndarray | list[list[float]] = None, translations: np.ndarray | list[float] = None,
             # transformations: list[types.TransformationMapping] = None, surrounding_uc: bool = True,
             **kwargs):
    """When init occurs chain_ids are set if chains were passed. If not, then they are auto generated

    Args:
        operators: A set of symmetry operations to designate how to apply symmetry
        rotations: A set of rotation matrices used to recapitulate the SymmetricModel from the asymmetric unit
        translations: A set of translation vectors used to recapitulate the SymmetricModel from the asymmetric unit
    """
    self._is_captain = True
    super().__init__(**kwargs,  # Entity
                     as_mates=True)  # <- needed when .from_file() w/ self.is_parent()
    self._captain = None
    self.dihedral_chain = None
    self.mate_rotation_axes = []

    chains = self.chains
    if not chains:
        raise DesignError(
            f"Can't construct {self.__class__.__name__} instance without 'chains'. "
            "Ensure that you didn't construct with chains=False | None"
        )

    representative, *additional_chains = chains
    if self.is_parent():
        # When this instance is the parent (.from_file(), .from_chains(parent=None))
        # Set attributes from representative now that _chains is parsed
        self._coords.set(representative.coords)
        self._assign_residues(representative.residues, atoms=representative.atoms)

    # Set up the chain copies
    number_of_symmetry_mates = len(chains)
    symmetry = None
    if number_of_symmetry_mates > 1:
        if self.is_dihedral():
            symmetry = f'D{int(number_of_symmetry_mates / 2)}'
        elif self.is_cyclic():
            symmetry = f'C{number_of_symmetry_mates}'
        else:  # Higher than D, probably T, O, I, or asymmetric
            try:
                symmetry = utils.symmetry.subunit_number_to_symmetry[number_of_symmetry_mates]
            except KeyError:
                self.log.warning(f"Couldn't find a compatible symmetry for the Entity with "
                                 f"{number_of_symmetry_mates} chain copies")
                # symmetry = None
                # self.symmetry = "Unknown-symmetry"
    self.set_symmetry(symmetry=symmetry)

    if not self.is_symmetric():
        # No symmetry keyword args were passed
        if operators is not None or rotations is not None or translations is not None:
            passed_args = []
            if operators:
                passed_args.append('operators')
            if rotations:
                passed_args.append('rotations')
            if translations:
                passed_args.append('translations')
            raise ConstructionError(
                f"Couldn't set_symmetry() using {', '.join(passed_args)} without explicitly passing "
                "'symmetry' or 'sym_entry'"
            )
        return

    # Set rotations and translations to the correct symmetry operations
    # where operators, rotations, and translations are user provided from some sort of BIOMT (fiber, other)
    if operators is not None:
        symmetry_source_arg = "'operators' "

        num_operators = len(operators)
        if isinstance(operators, tuple) and num_operators == 2:
            self.log.warning("Providing custom symmetry 'operators' may result in improper symmetric "
                             'configuration. Proceed with caution')
            rotations, translations = operators
        elif isinstance(operators, Sequence) and num_operators == number_of_symmetry_mates:
            rotations = []
            translations = []
            try:
                for rot, tx in operators:
                    rotations.append(rot)
                    translations.append(tx)
            except TypeError:  # Unpack failed
                raise ValueError(
                    f"Couldn't parse the 'operators'={repr(operators)}.\n\n"
                    "Expected a Sequence[rotation shape=(3,3). translation shape=(3,)] pairs."
                )
        elif isinstance(operators, np.ndarray):
            if operators.shape[1:] == (3, 4):
                # Parse from a single input of 3 row by 4 column style, like BIOMT
                rotations = operators[:, :, :3]
                translations = operators[:, :, 3:].squeeze()
            elif operators.shape[1:] == 3:  # Assume just rotations
                rotations = operators
                translations = np.tile(utils.symmetry.origin, len(rotations))
            else:
                raise ConstructionError(
                    f"The 'operators' form {repr(operators)} isn't supported.")
        else:
            raise ConstructionError(
                f"The 'operators' form {repr(operators)} isn't supported. Must provide a tuple of "
                'array-like objects with the order (rotation matrices, translation vectors) or use the '
                "'rotations' and 'translations' keyword args")
    else:
        symmetry_source_arg = ''

    # Now that symmetry is set, check if the Structure parsed all symmetric chains
    if len(chains) == self.number_of_entities * number_of_symmetry_mates:
        parsed_assembly = True
    else:
        parsed_assembly = False

    # Set the symmetry operations
    if rotations is not None and translations is not None:
        if not isinstance(rotations, np.ndarray):
            rotations = np.ndarray(rotations)
        if rotations.ndim == 3:
            # Assume operators were provided in a standard orientation and transpose for subsequent efficiency
            # Using .swapaxes(-2, -1) call here instead of .transpose() for safety
            self._expand_matrices = rotations.swapaxes(-2, -1)
        else:
            raise SymmetryError(
                f"Expected {symmetry_source_arg}rotation matrices with 3 dimensions, not {rotations.ndim} "
                "dimensions. Ensure the passed rotation matrices have a shape of (N symmetry operations, 3, 3)"
            )

        if not isinstance(translations, np.ndarray):
            translations = np.ndarray(translations)
        if translations.ndim == 2:
            # Assume operators were provided in a standard orientation each vector needs to be in own array on dim=2
            self._expand_translations = translations[:, None, :]
        else:
            raise SymmetryError(
                f"Expected {symmetry_source_arg}translation vectors with 2 dimensions, not {translations.ndim} "
                "dimensions. Ensure the passed translations have a shape of (N symmetry operations, 3)"
            )
    else:
        symmetry_source_arg = "'chains' "
        if self.dimension == 0:
            # The _expand_matrices rotation matrices are pre-transposed to avoid repetitive operations
            _expand_matrices = utils.symmetry.point_group_symmetry_operatorsT[self.symmetry]
            # The _expand_translations vectors are pre-sliced to enable numpy operations
            _expand_translations = \
                np.tile(utils.symmetry.origin, (number_of_symmetry_mates, 1))[:, None, :]

            if parsed_assembly:
                # The Structure should have symmetric chains
                # This routine is essentially orient(). However, with one Entity, no extra need for orient
                _expand_matrices = [utils.symmetry.identity_matrix]
                _expand_translations = [utils.symmetry.origin]
                self_seq = self.sequence
                ca_coords = self.ca_coords
                # Todo match this mechanism with the symmetric chain index
                for chain in additional_chains:
                    chain_seq = chain.sequence
                    additional_chain_coords = chain.ca_coords
                    first_chain_coords = ca_coords
                    if chain_seq != self_seq:
                        # Get aligned indices, then follow with superposition
                        self.log.debug(f'{repr(chain)} and {repr(self)} require alignment to symmetrize')
                        fixed_indices, moving_indices = get_equivalent_indices(chain_seq, self_seq)
                        additional_chain_coords = additional_chain_coords[fixed_indices]
                        first_chain_coords = first_chain_coords[moving_indices]

                    _, rot, tx = superposition3d(additional_chain_coords, first_chain_coords)
                    _expand_matrices.append(rot)
                    _expand_translations.append(tx)

                self._expand_matrices = np.array(_expand_matrices).swapaxes(-2, -1)
                self._expand_translations = np.array(_expand_translations)[:, None, :]
            else:
                self._expand_matrices = _expand_matrices
                self._expand_translations = _expand_translations
        else:
            self._expand_matrices, self._expand_translations = \
                utils.symmetry.space_group_symmetry_operatorsT[self.symmetry]

    # Removed parsed chain information
    self.reset_mates()

mate_rotation_axes instance-attribute

mate_rotation_axes: list[dict[str, int | ndarray]] | list = []

Maps mate entities to their rotation matrix

entity_id property writable

entity_id: str

The Entity ID associated with the instance

number_of_entities property

number_of_entities: int

Return the number of distinct entities (Gene/Protein products) found in the PoseMetadata

entities property

entities: list[Entity]

Returns the Entity instance as a list

chains property

chains: list[Entity]

The mate Chain instances of the instance. If not created, returns transformed copies of the instance

assembly property

assembly: Model

Access the oligomeric Structure which is a copy of the Entity plus any additional symmetric mate chains

Returns:

  • Model

    Structures object with the underlying chains in the oligomer

max_symmetry_chain_idx property

max_symmetry_chain_idx: int

The maximum symmetry order present

max_symmetry property

max_symmetry: int

The maximum symmetry order present

from_chains classmethod

from_chains(chains: list[Chain] | Structures, residue_indices: list[int] = None, **kwargs)

Initialize an Entity from Chain instances

Parameters:

  • chains (list[Chain] | Structures) –

    A list of Chain instances that match the Entity

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

    The indices which the new Entity should contain

Source code in symdesign/structure/model.py
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
@classmethod
def from_chains(cls, chains: list[Chain] | Structures, residue_indices: list[int] = None, **kwargs):
    """Initialize an Entity from Chain instances

    Args:
        chains: A list of Chain instances that match the Entity
        residue_indices: The indices which the new Entity should contain
    """
    operators = kwargs.get('operators')
    if residue_indices is None:
        asymmetry = False
        if asymmetry:
            pass
        # No check
        else:
            representative, *additional_chains = chains

        residue_indices = representative.residue_indices

    return cls(chains=chains, residue_indices=residue_indices, operators=operators, **kwargs)

coords

coords(coords: ndarray | list[list[float]])

Set the Coords object while propagating changes to symmetric "mate" chains

Source code in symdesign/structure/model.py
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
@StructureBase.coords.setter
def coords(self, coords: np.ndarray | list[list[float]]):
    """Set the Coords object while propagating changes to symmetric "mate" chains"""
    if self.is_symmetric() and self._is_captain:
        # **This routine handles imperfect symmetry**
        self.log.debug('Entity captain is updating coords')
        # Must do these before super().coords.fset()
        # Populate .chains (if not already) with current coords and transformation
        self_, *mate_chains = self.chains
        # Set current .ca_coords as prior_ca_coords
        prior_ca_coords = self.ca_coords.copy()

        # Set coords with new coords
        super(ContainsAtoms, ContainsAtoms).coords.fset(self, coords)
        if self.is_dependent():
            _parent = self.parent
            if _parent.is_symmetric() and not self._parent_is_updating:
                _parent._dependent_is_updating = True
                # Update the parent which propagates symmetric updates
                _parent.coords = _parent.coords
                _parent._dependent_is_updating = False

        # Find the transformation from the old coordinates to the new
        new_ca_coords = self.ca_coords
        _, new_rot, new_tx = superposition3d(new_ca_coords, prior_ca_coords)

        new_rot_t = np.transpose(new_rot)
        # Remove prior transforms by setting a fresh container
        _expand_matrices = [utils.symmetry.identity_matrix]
        _expand_translations = [utils.symmetry.origin]
        # Find the transform between the new coords and the current mate chain coords
        # for chain, transform in zip(mate_chains, current_chain_transforms):
        for chain in mate_chains:
            # self.log.debug(f'Updated transform of mate {chain.chain_id}')
            # In liu of using chain.coords as lengths might be different
            # Transform prior_coords to chain.coords position, then transform using new_rot and new_tx
            # new_chain_ca_coords = \
            #     np.matmul(np.matmul(prior_ca_coords,
            #                         np.transpose(transform['rotation'])) + transform['translation'],
            #               np.transpose(new_rot)) + new_tx
            new_chain_ca_coords = np.matmul(chain.ca_coords, new_rot_t) + new_tx
            # Find the transform from current coords and the new mate chain coords
            _, rot, tx = superposition3d(new_chain_ca_coords, new_ca_coords)
            # Save transform
            # self._chain_transforms.append(dict(rotation=rot, translation=tx))
            rot_t = np.transpose(rot)
            _expand_matrices.append(rot_t)
            _expand_translations.append(tx)
            # Transform existing mate chain
            chain.coords = np.matmul(coords, rot_t) + tx
            # self.log.debug(f'Setting coords on mate chain {chain.chain_id}')

        self._expand_matrices = np.array(_expand_matrices)
        self._expand_translations = np.array(_expand_translations)[:, None, :]
    else:  # Accept the new coords
        super(ContainsAtoms, ContainsAtoms).coords.fset(self, coords)

is_captain

is_captain() -> bool

Is the Entity instance the captain?

Source code in symdesign/structure/model.py
3536
3537
3538
def is_captain(self) -> bool:
    """Is the Entity instance the captain?"""
    return self._is_captain

is_mate

is_mate() -> bool

Is the Entity instance a mate?

Source code in symdesign/structure/model.py
3540
3541
3542
def is_mate(self) -> bool:
    """Is the Entity instance a mate?"""
    return not self._is_captain

has_mates

has_mates() -> bool

Returns True if this Entity is a captain and has mates

Source code in symdesign/structure/model.py
3554
3555
3556
def has_mates(self) -> bool:
    """Returns True if this Entity is a captain and has mates"""
    return len(self._chains) > 1

remove_mate_chains

remove_mate_chains()

Clear the Entity of all Chain and Oligomer information

Source code in symdesign/structure/model.py
3591
3592
3593
3594
3595
3596
def remove_mate_chains(self):
    """Clear the Entity of all Chain and Oligomer information"""
    self._expand_matrices = self._expand_translations = []
    self.reset_mates()
    self._is_captain = False
    self.chain_ids = [self.chain_id]

make_oligomer

make_oligomer(symmetry: str = None, rotation: list[list[float]] | ndarray = None, translation: list[float] | ndarray = None, rotation2: list[list[float]] | ndarray = None, translation2: list[float] | ndarray = None, **kwargs)

Given a symmetry and transformational mapping, generate oligomeric copies of the Entity

Assumes that the symmetric system treats the canonical symmetric axis as the Z-axis, and if the Entity is not at the origin, that a transformation describing its current position relative to the origin is passed so that it can be moved to the origin. At the origin, makes the required oligomeric rotations, to generate an oligomer where symmetric copies are stored in the .chains attribute then reverses the operations back to original reference frame if any was provided

Parameters:

  • symmetry (str, default: None ) –

    The symmetry to set the Entity to

  • 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,)

Sets

self.symmetry (str) self.sym_entry (SymEntry) self.number_of_symmetry_mates (int) self._expand_matrices self._expand_translations

Source code in symdesign/structure/model.py
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
def make_oligomer(self, symmetry: str = None, 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):
    """Given a symmetry and transformational mapping, generate oligomeric copies of the Entity

    Assumes that the symmetric system treats the canonical symmetric axis as the Z-axis, and if the Entity is not at
    the origin, that a transformation describing its current position relative to the origin is passed so that it
    can be moved to the origin. At the origin, makes the required oligomeric rotations, to generate an oligomer
    where symmetric copies are stored in the .chains attribute then reverses the operations back to original
    reference frame if any was provided

    Args:
        symmetry: The symmetry to set the Entity to
        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,)

    Sets:
        self.symmetry (str)
        self.sym_entry (SymEntry)
        self.number_of_symmetry_mates (int)
        self._expand_matrices
        self._expand_translations
    """
    self.set_symmetry(symmetry=symmetry)
    if not self.is_symmetric():
        return

    symmetry = self.symmetry
    degeneracy_matrices = None
    if symmetry in utils.symmetry.cubic_point_groups:
        rotation_matrices = utils.symmetry.point_group_symmetry_operators[symmetry]
    elif 'D' in symmetry:  # Provide a 180-degree rotation along x (all D orient symmetries have axis here)
        rotation_matrices = \
            utils.SymEntry.get_rot_matrices(
                utils.symmetry.rotation_range[symmetry.replace('D', 'C')],
                'z', 360
            )
        degeneracy_matrices = [utils.symmetry.identity_matrix, utils.symmetry.flip_x_matrix]
    else:  # Symmetry is cyclic
        rotation_matrices = utils.SymEntry.get_rot_matrices(utils.symmetry.rotation_range[symmetry], 'z')

    degeneracy_rotation_matrices = utils.SymEntry.make_rotations_degenerate(
        rotation_matrices, degeneracy_matrices)

    assert self.number_of_symmetry_mates == len(degeneracy_rotation_matrices), \
        (f"The number of symmetry mates, {self.number_of_symmetry_mates} != {len(degeneracy_rotation_matrices)}, "
         "the number of operations")

    if rotation is None:
        rotation = inv_rotation = utils.symmetry.identity_matrix
    else:
        inv_rotation = np.linalg.inv(rotation)
    if translation is None:
        translation = utils.symmetry.origin

    if rotation2 is None:
        rotation2 = inv_rotation2 = utils.symmetry.identity_matrix
    else:
        inv_rotation2 = np.linalg.inv(rotation2)
    if translation2 is None:
        translation2 = utils.symmetry.origin
    # this is helpful for dihedral symmetry as entity must be transformed to origin to get canonical dihedral
    # entity_inv = entity.get_transformed_copy(rotation=inv_expand_matrix, rotation2=inv_set_matrix[group])
    # need to reverse any external transformation to the entity coords so rotation occurs at the origin...
    # and undo symmetry expansion matrices
    # centered_coords = transform_coordinate_sets(self.coords, translation=-translation2,
    # centered_coords = transform_coordinate_sets(self._coords.coords, translation=-translation2)
    cb_coords = self.cb_coords
    centered_coords = transform_coordinate_sets(cb_coords, translation=-translation2)

    centered_coords_inv = transform_coordinate_sets(centered_coords, rotation=inv_rotation2,
                                                    translation=-translation, rotation2=inv_rotation)
    _expand_matrices = [utils.symmetry.identity_matrix]
    _expand_translations = [utils.symmetry.origin]
    subunit_count = count()
    for rotation_matrix in degeneracy_rotation_matrices:
        if next(subunit_count) == 0 and np.all(rotation_matrix == utils.symmetry.identity_matrix):
            self.log.debug(f'Skipping {self.make_oligomer.__name__} transformation 1 as it is identity')
            continue
        rot_centered_coords = transform_coordinate_sets(centered_coords_inv, rotation=rotation_matrix)
        new_coords = transform_coordinate_sets(rot_centered_coords, rotation=rotation, translation=translation,
                                               rotation2=rotation2, translation2=translation2)
        _, rot, tx = superposition3d(new_coords, cb_coords)
        _expand_matrices.append(rot)
        _expand_translations.append(tx)

    self._expand_matrices = np.array(_expand_matrices).swapaxes(-2, -1)
    self._expand_translations = np.array(_expand_translations)[:, None, :]

    # Set the new properties
    self.reset_mates()
    self._set_chain_ids()

get_transformed_mate

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

Make a semi-deep copy of the Entity, stripping any captain attributes, transforming the coordinates

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:

  • Entity

    A transformed copy of the original object

Source code in symdesign/structure/model.py
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
def get_transformed_mate(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) -> Entity:
    """Make a semi-deep copy of the Entity, stripping any captain attributes, transforming the coordinates

    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))
    else:
        new_coords = self.coords

    if translation is not None:  # required for np.ndarray or None checks
        new_coords += np.array(translation)

    if rotation2 is not None:  # required for np.ndarray or None checks
        np.matmul(new_coords, np.transpose(rotation2), out=new_coords)

    if translation2 is not None:  # required for np.ndarray or None checks
        new_coords += np.array(translation2)

    new_structure = self.copy()
    new_structure._make_mate(self)
    new_structure.coords = new_coords

    return new_structure

write

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

Write Entity Structure to a file specified by out_path or with a passed file_handle

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

  • assembly (bool, default: False ) –

    Whether to write the oligomeric form of the Entity

Other Parameters:

  • increment_chains

    bool = False - Whether to write each Structure with a new chain name, otherwise write as a new Model

  • 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. Not used if assembly=True

Returns:

  • AnyStr | None

    The name of the written file if out_path is used

Source code in symdesign/structure/model.py
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
def write(self, out_path: bytes | str = os.getcwd(), file_handle: IO = None, header: str = None,
          assembly: bool = False, **kwargs) -> AnyStr | None:
    """Write Entity Structure to a file specified by out_path or with a passed file_handle

    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
        assembly: Whether to write the oligomeric form of the Entity

    Keyword Args:
        increment_chains: bool = False - Whether to write each Structure with a new chain name, otherwise write as
            a new Model
        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.
            Not used if assembly=True

    Returns:
        The name of the written file if out_path is used
    """
    self.log.debug(f'{Entity.__name__} is writing {repr(self)}')

    def _write(handle) -> None:
        if assembly:
            kwargs.pop('atom_offset', None)
            # if 'increment_chains' not in kwargs:
            #     kwargs['increment_chains'] = True
            # assembly_models = self._generate_assembly_models(**kwargs)
            assembly_models = Models(self.chains)
            assembly_models.write(file_handle=handle, multimodel=False, **kwargs)
        else:
            super(Structure, Structure).write(self, file_handle=handle, **kwargs)

    if file_handle:
        return _write(file_handle)
    else:  # out_path always has default argument current working directory
        # assembly=True implies all chains will be written, so asu=False to write each SEQRES record
        _header = self.format_header(assembly=assembly, **kwargs)
        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)
            _write(outfile)

        return out_path

calculate_metrics

calculate_metrics(**kwargs) -> dict[str, Any]
Source code in symdesign/structure/model.py
3829
3830
3831
3832
def calculate_metrics(self, **kwargs) -> dict[str, Any]:
    """"""
    self.log.debug(f"{self.calculate_spatial_orientation_metrics.__name__} missing argument 'reference'")
    return self.calculate_spatial_orientation_metrics()

calculate_spatial_orientation_metrics

calculate_spatial_orientation_metrics(reference: ndarray = utils.symmetry.origin) -> dict[str, Any]

Calculate metrics for the instance

Parameters:

  • reference (ndarray, default: origin ) –

    The reference where the point should be measured from

Returns:

  • dict[str, Any]

    {'radius' 'min_radius' 'max_radius' 'n_terminal_orientation' 'c_terminal_orientation'

  • dict[str, Any]

    }

Source code in symdesign/structure/model.py
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
def calculate_spatial_orientation_metrics(self, reference: np.ndarray = utils.symmetry.origin) -> dict[str, Any]:
    """Calculate metrics for the instance

    Args:
        reference: The reference where the point should be measured from

    Returns:
        {'radius'
         'min_radius'
         'max_radius'
         'n_terminal_orientation'
         'c_terminal_orientation'
        }
    """
    return {
        'radius': self.assembly.distance_from_reference(reference=reference),
        'min_radius': self.assembly.distance_from_reference(measure='min', reference=reference),
        'max_radius': self.assembly.distance_from_reference(measure='max', reference=reference),
        'n_terminal_orientation': self.termini_proximity_from_reference(reference=reference),
        'c_terminal_orientation': self.termini_proximity_from_reference(termini='c', reference=reference),
    }

get_alphafold_features

get_alphafold_features(symmetric: bool = False, heteromer: bool = False, msas: Sequence = tuple(), no_msa: bool = False, templates: bool = False, **kwargs) -> FeatureDict

Retrieve the required feature dictionary for this instance to use in Alphafold inference

Parameters:

  • symmetric (bool, default: False ) –

    Whether the symmetric Entity should be used for feature production. If True, this function will fully process the FeatureDict in the symmetric form compatible with Alphafold multimer

  • heteromer (bool, default: False ) –

    Whether Alphafold should be run as a heteromer. Features directly used in Alphafold from this instance should never be used with heteromer=True

  • msas (Sequence, default: tuple() ) –

    A sequence of multiple sequence alignments if they should be included in the features

  • no_msa (bool, default: False ) –

    Whether multiple sequence alignments should be included in the features

  • templates (bool, default: False ) –

    Whether the Entity should be returned with it's template features

Returns:

  • FeatureDict

    The Alphafold FeatureDict which is essentially a dictionary with dict[str, np.ndarray]

Source code in symdesign/structure/model.py
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
def get_alphafold_features(self, symmetric: bool = False, heteromer: bool = False, msas: Sequence = tuple(),
                           no_msa: bool = False, templates: bool = False, **kwargs) -> FeatureDict:
    # multimer: bool = False,
    """Retrieve the required feature dictionary for this instance to use in Alphafold inference

    Args:
        symmetric: Whether the symmetric Entity should be used for feature production. If True, this function will
            fully process the FeatureDict in the symmetric form compatible with Alphafold multimer
        heteromer: Whether Alphafold should be run as a heteromer. Features directly used in
            Alphafold from this instance should never be used with heteromer=True
        msas: A sequence of multiple sequence alignments if they should be included in the features
        no_msa: Whether multiple sequence alignments should be included in the features
        templates: Whether the Entity should be returned with it's template features

    Returns:
        The Alphafold FeatureDict which is essentially a dictionary with dict[str, np.ndarray]
    """
    if heteromer:
        if symmetric:
            raise ValueError(
                f"Couldn't {self.get_alphafold_features.__name__} with both 'symmetric' and "
                f"'heteromer' True. Only run with symmetric True if this {self.__class__.__name__} "
                "instance alone should be predicted as a multimer")
    # if templates:
    #     if symmetric:
    #         # raise ValueError(f"Couldn't {self.get_alphafold_features.__name__} with both 'symmetric' and "
    #         logger.warning(f"Couldn't {self.get_alphafold_features.__name__} with both 'symmetric' and "
    #                        f"'templates' True. Templates not set up for multimer")
    # elif symmetric:
    #     # Set multimer True as we need to make_msa_features_multimeric
    #     multimer = True

    # # IS THIS NECESSARY. DON'T THINK SO IF I HAVE MSA
    # chain_features = alphafold.alphafold.data.pipeline.DataPipeline.process(input_fasta_path=P, msa_output_dir=P)
    # This ^ runs
    number_of_residues = self.number_of_residues
    sequence = self.sequence
    sequence_features = af_pipeline.make_sequence_features(
        sequence=sequence, description=self.name, num_res=number_of_residues)
    # sequence_features = {
    #     'aatype': ,  # MAKE ONE HOT with X i.e.unknown are X
    #     'between_segment_residues': np.zeros((number_of_residues,), dtype=np.int32),
    #     'domain_name': np.array([input_description.encode('utf-8')], dtype=np.object_),
    #     'residue_index': np.arange(number_of_residues, dtype=np.int32),
    #     'seq_length': np.full(number_of_residues, number_of_residues, dtype=np.int32),
    #     'sequence': np.array([sequence.encode('utf-8')], dtype=np.object_)
    # }

    def make_msa_features_multimeric(msa_feats: FeatureDict) -> FeatureDict:
        """Create the feature names for Alphafold heteromeric inputs run in multimer mode"""
        valid_feats = af_msa_pairing.MSA_FEATURES + ('msa_species_identifiers',)
        return {f'{k}_all_seq': v for k, v in msa_feats.items() if k in valid_feats}

    # Multiple sequence alignment processing
    if msas:
        msa_features = af_pipeline.make_msa_features(msas)
        # Can use a single one...
        # Other types from AlphaFold include: (uniref90_msa, bfd_msa, mgnify_msa)
        if heteromer:
            # Todo ensure that uniref90 runner was used...
            #  OR equivalent so that each sequence in a multimeric msa is paired
            # Stockholm format looks like
            # #=GF DE                          path/to/profiles/entity_id
            # #=GC RF                          AY--R...
            # 2gtr_1                           AY--R...
            # UniRef100_A0A455ABB#2            NC--R...
            # UniRef100_UPI00106966C#3         CI--L...
            raise NotImplementedError('No uniprot90 database hooked up...')
            # with open(self.msa_file, 'r') as f:
            #     uniref90_lines = f.read()

            uniref90_msa = af_data_parsers.parse_stockholm(uniref90_lines)
            msa_features = af_pipeline.make_msa_features((uniref90_msa,))
            msa_features.update(make_msa_features_multimeric(msa_features))
    else:
        msa = self.msa
        if no_msa or msa is None:  # or self.msa_file is None:
            # When no msa_used, construct our own
            num_sequences = 1
            deletion_matrix = np.zeros((num_sequences, number_of_residues), dtype=np.int32)
            species_ids = ['']  # Must include an empty '' as the first "reference" sequence
            msa_numeric = sequences_to_numeric(
                [sequence], translation_table=numerical_translation_alph1_unknown_gaped_bytes
            ).astype(dtype=np.int32)
        elif msa:
            deletion_matrix = msa.deletion_matrix.astype(np.int32)  # [:, msa.query_indices]
            num_sequences = msa.length
            species_ids = msa.sequence_identifiers
            # Set the msa.alphabet_type to ensure the numerical_alignment is embedded correctly
            msa.alphabet_type = protein_letters_alph1_unknown_gaped
            msa_numeric = msa.numerical_alignment[:, msa.query_indices]
            # self.log.critical(f'982 Found {len(np.flatnonzero(msa.query_indices))} indices utilized in design')
        # Todo
        #  move to additional AlphaFold set up function...
        #  elif os.path.exists(self.msa_file):
        #      with open(self.msa_file, 'r') as f:
        #          uniclust_lines = f.read()
        #      file, extension = os.path.splitext(self.msa_file)
        #      if extension == '.sto':
        #          uniclust30_msa = af_data_parsers.parse_stockholm(uniclust_lines)
        #      else:
        #          raise ValueError(
        #              f"Currently, the multiple sequence alignment file type '{extension}' isn't supported\n"
        #              f"\tOffending file located at: {self.msa_file}")
        #      msas = (uniclust30_msa,)
        else:
            raise ValueError("Couldn't acquire AlphaFold msa features")

        self.log.debug(f"Found the first 5 species_ids: {species_ids[:5]}")
        msa_features = {
            'deletion_matrix_int': deletion_matrix,
            # When not single sequence, GET THIS FROM THE MATRIX PROBABLY USING CODE IN COLLAPSE PROFILE cumcount...
            # 'msa': sequences_to_numeric([sequence], translation_table=HHBLITS_AA_TO_ID).astype(dtype=np.int32),
            'msa': msa_numeric,
            'num_alignments': np.full(number_of_residues, num_sequences, dtype=np.int32),
            # Fill by the number of residues how many sequences are in the MSA
            'msa_species_identifiers': np.array([id_.encode('utf-8') for id_ in species_ids], dtype=np.object_)
        }
        # Debug features
        for feat, values in msa_features.items():
            self.log.debug(f'For feature {feat}, found shape {values.shape}')

        if heteromer:
            # Make a deepcopy just incase this screws up something
            msa_features.update(make_msa_features_multimeric(deepcopy(msa_features)))

    # Template processing
    if templates:
        template_features = self.get_alphafold_template_features()  # symmetric=symmetric, heteromer=heteromer)
    else:
        template_features = empty_placeholder_template_features(num_templates=0, num_res=number_of_residues)
    # Debug template features
    for feat, values in template_features.items():
        self.log.debug(f'For feature {feat}, found shape {values.shape}')

    entity_features = {
        **msa_features,
        **sequence_features,
        **template_features
    }
    if symmetric and self.is_symmetric():
        # Hard code in chain_id as we are using a multimeric predict on the oligomeric version
        chain_id = 'A'
        entity_features = af_pipeline_multimer.convert_monomer_features(entity_features, chain_id=chain_id)

        chain_count = count(1)
        entity_integer = 1
        entity_id = af_pipeline_multimer.int_id_to_str_id(entity_integer)
        all_chain_features = {}
        for sym_idx in range(1, 1 + self.number_of_symmetry_mates):
            # chain_id = next(available_chain_ids_iter)  # The mmCIF formatted chainID with 'AB' type notation
            this_entity_features = deepcopy(entity_features)
            # Where chain_id increments for each new chain instance i.e. A_1 is 1, A_2 is 2, ...
            # Where entity_id increments for each new Entity instance i.e. A_1 is 1, A_2 is 1, ...
            # Where sym_id increments for each new Entity instance regardless of chain i.e. A_1 is 1, A_2 is 2, ...,
            # B_1 is 1, B2 is 2
            this_entity_features.update({'asym_id': next(chain_count) * np.ones(number_of_residues),
                                         'sym_id': sym_idx * np.ones(number_of_residues),
                                         'entity_id': entity_integer * np.ones(number_of_residues)})
            chain_name = f'{entity_id}_{sym_idx}'
            all_chain_features[chain_name] = this_entity_features

        # Alternative to pair_and_merge using hhblits a3m output
        # See PMID:36224222 "Structural predictions of dimeric and trimeric subcomponents" methods section
        # The first of the two MSAs is constructed by extracting the organism identifiers (OX) from the resulting
        # a3m file and pairing sequences using the top hit from each OX. The second is constructed by block
        # diagonalizing the resulting a3m file.
        np_example = af_feature_processing.pair_and_merge(all_chain_features=all_chain_features)
        # Pad MSA to avoid zero-sized extra_msa.
        np_example = af_pipeline_multimer.pad_msa(np_example, 512)

        return np_example  # This is still a FeatureDict and could be named entity_features
    else:
        return entity_features

find_chain_symmetry

find_chain_symmetry()

Search for the chain symmetry by using quaternion geometry to solve the symmetric order of the rotations which superimpose chains on the Entity. Translates the Entity to the origin using center of mass, then the axis of rotation only needs to be translated to the center of mass to recapitulate the specific symmetry operation

Requirements - all chains are the same length

Sets

self.mate_rotation_axes (list[dict[str, int | np.ndarray]]) self._max_symmetry (int) self.max_symmetry_chain_idx (int)

Returns:

  • The name of the file written for symmetry definition file creation

Source code in symdesign/structure/model.py
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
def find_chain_symmetry(self):
    """Search for the chain symmetry by using quaternion geometry to solve the symmetric order of the rotations
     which superimpose chains on the Entity. Translates the Entity to the origin using center of mass, then the axis
    of rotation only needs to be translated to the center of mass to recapitulate the specific symmetry operation

    Requirements - all chains are the same length

    Sets:
        self.mate_rotation_axes (list[dict[str, int | np.ndarray]])
        self._max_symmetry (int)
        self.max_symmetry_chain_idx (int)

    Returns:
        The name of the file written for symmetry definition file creation
    """
    # Find the superposition from the Entity to every mate chain
    # center_of_mass = self.center_of_mass
    # symmetric_center_of_mass = self.center_of_mass_symmetric
    # self.log.debug(f'symmetric_center_of_mass={symmetric_center_of_mass}')
    self.mate_rotation_axes.clear()
    self.mate_rotation_axes.append({'sym': 1, 'axis': utils.symmetry.origin})
    self.log.debug(f'Reference chain is {self.chain_id}')
    if self.is_symmetric():

        def _get_equivalent_coords(
            self_ca_coords: np.ndarray, self_seq: str, chain_: Chain
        ) -> tuple[np.ndarray, np.ndarray]:
            return self_ca_coords, chain_.ca_coords
    else:

        def _get_equivalent_coords(
            self_ca_coords: np.ndarray, self_seq: str, chain_: Chain
        ) -> tuple[np.ndarray, np.ndarray]:
            chain_seq = chain_.sequence
            additional_chain_coords = chain_.ca_coords
            if chain_seq != self_seq:
                # Get aligned indices, then follow with superposition
                self.log.debug(f'{repr(chain_)} and {repr(self)} require alignment to symmetrize')
                fixed_indices, moving_indices = get_equivalent_indices(chain_seq, self_seq)
                additional_chain_coords = additional_chain_coords[fixed_indices]
                self_ca_coords = self_ca_coords[moving_indices]

            return self_ca_coords, additional_chain_coords

    ca_coords = self.ca_coords
    sequence = self.sequence
    for chain in self.chains[1:]:
        self_coords, chain_coords = _get_equivalent_coords(ca_coords, sequence, chain)
        rmsd, quat, tx = superposition3d_quat(self_coords, chain_coords)
        # rmsd, quat, tx = superposition3d_quat(cb_coords-center_of_mass, chain.cb_coords-center_of_mass)
        self.log.debug(f'rmsd={rmsd} quaternion={quat} translation={tx}')
        w = abs(quat[3])
        omega = math.acos(w)
        try:
            symmetry_order = int(math.pi/omega + .5)  # Round to the nearest integer
        except ZeroDivisionError:  # w is 1, omega is 0
            # No axis of symmetry here
            symmetry_order = 1
            self.log.warning(f"Couldn't find any symmetry order for {self.name} mate Chain {chain.chain_id}. "
                             f'Setting symmetry_order={symmetry_order}')
        self.log.debug(f'{chain.chain_id}:{symmetry_order}-fold axis')
        self.mate_rotation_axes.append({'sym': symmetry_order, 'axis': quat[:3]})

    # Find the highest order symmetry in the Structure
    max_sym = 0
    max_chain_idx = None
    for chain_idx, data in enumerate(self.mate_rotation_axes):
        if data['sym'] > max_sym:
            max_sym = data['sym']
            max_chain_idx = chain_idx

    self._max_symmetry = max_sym
    self._max_symmetry_chain_idx = max_chain_idx

is_cyclic

is_cyclic() -> bool

Report whether the symmetry is cyclic

Returns:

  • bool

    True if the Structure is cyclic, False if not

Source code in symdesign/structure/model.py
4154
4155
4156
4157
4158
4159
4160
def is_cyclic(self) -> bool:
    """Report whether the symmetry is cyclic

    Returns:
        True if the Structure is cyclic, False if not
    """
    return self.number_of_symmetry_mates == self.max_symmetry

is_dihedral

is_dihedral() -> bool

Report whether the symmetry is dihedral

Returns:

  • bool

    True if the Structure is dihedral, False if not

Source code in symdesign/structure/model.py
4162
4163
4164
4165
4166
4167
4168
def is_dihedral(self) -> bool:
    """Report whether the symmetry is dihedral

    Returns:
        True if the Structure is dihedral, False if not
    """
    return self.number_of_symmetry_mates / self.max_symmetry == 2

find_dihedral_chain

find_dihedral_chain() -> Entity | None

From the symmetric system, find a dihedral chain and return the instance

Returns:

  • Entity | None

    The dihedral mate Chain

Source code in symdesign/structure/model.py
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
def find_dihedral_chain(self) -> Entity | None:  # Todo python 3.11 self
    """From the symmetric system, find a dihedral chain and return the instance

    Returns:
        The dihedral mate Chain
    """
    if not self.is_dihedral():
        return None

    # Ensure if the structure is dihedral a selected dihedral_chain is orthogonal to the maximum symmetry axis
    max_symmetry_axis = self.mate_rotation_axes[self.max_symmetry_chain_idx]['axis']
    for chain_idx, data in enumerate(self.mate_rotation_axes):
        this_chain_axis = data['axis']
        if data['sym'] == 2:
            axis_dot_product = np.dot(max_symmetry_axis, this_chain_axis)
            if axis_dot_product < 0.01:
                if np.allclose(this_chain_axis, [1, 0, 0]):
                    self.log.debug(f'The relation between {self.max_symmetry_chain_idx} and {chain_idx} would '
                                   'result in a malformed .sdf file')
                    pass  # This won't work in the make_symmdef.pl script, should choose orthogonal y-axis
                else:
                    return self.chains[chain_idx]
    return None

make_sdf

make_sdf(struct_file: AnyStr = None, out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr

Use the make_symmdef_file.pl script from Rosetta to make a symmetry definition file on the Structure

perl $ROSETTA/source/src/apps/public/symmetry/make_symmdef_file.pl -p filepath/to/pdb.pdb -i B -q

Parameters:

  • struct_file (AnyStr, default: None ) –

    The location of the input .pdb file

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

    The location the symmetry definition file should be written

Other Parameters:

  • modify_sym_energy_for_cryst

    bool = False - Whether the symmetric energy in the file should be modified

  • energy

    int = 2 - Scalar to modify the Rosetta energy by

Returns:

  • AnyStr

    Symmetry definition filename

Source code in symdesign/structure/model.py
4194
4195
4196
4197
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
def make_sdf(self, struct_file: AnyStr = None, out_path: AnyStr = os.getcwd(), **kwargs) -> AnyStr:
    """Use the make_symmdef_file.pl script from Rosetta to make a symmetry definition file on the Structure

    perl $ROSETTA/source/src/apps/public/symmetry/make_symmdef_file.pl -p filepath/to/pdb.pdb -i B -q

    Args:
        struct_file: The location of the input .pdb file
        out_path: The location the symmetry definition file should be written

    Keyword Args:
        modify_sym_energy_for_cryst: bool = False - Whether the symmetric energy in the file should be modified
        energy: int = 2 - Scalar to modify the Rosetta energy by

    Returns:
        Symmetry definition filename
    """
    out_file = os.path.join(out_path, f'{self.name}.sdf')
    if os.path.exists(out_file):
        return out_file

    if self.symmetry in utils.symmetry.cubic_point_groups:
        sdf_mode = 'PSEUDO'
        self.log.warning('Using experimental symmetry definition file generation, proceed with caution as Rosetta '
                         'runs may fail due to improper set up')
    else:
        sdf_mode = 'NCS'

    if not struct_file:
        struct_file = self.write(assembly=True, out_path=f'make_sdf_input-{self.name}-{random() * 100000:.0f}.pdb',
                                 increment_chains=True)

    # As increment_chains is used, get the chain name corresponding to the same index as incremental chain
    available_chain_ids = chain_id_generator()
    for _ in range(self.max_symmetry_chain_idx):
        next(available_chain_ids)
    chains = [next(available_chain_ids)]
    if self.is_dihedral():
        chains.append(self.find_dihedral_chain().chain_id)

    sdf_cmd = [
        'perl', putils.make_symmdef, '-m', sdf_mode, '-q', '-p', struct_file, '-a', self.chain_ids[0], '-i'
    ] + chains
    self.log.info(f'Creating symmetry definition file: {subprocess.list2cmdline(sdf_cmd)}')
    # with open(out_file, 'w') as file:
    p = subprocess.Popen(sdf_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    out, err = p.communicate()

    if os.path.exists(struct_file):
        os.system(f'rm {struct_file}')
    if p.returncode != 0:
        raise DesignError(
            f'Symmetry definition file creation failed for {self.name}')

    self.format_sdf(out.decode('utf-8').split('\n')[:-1], to_file=out_file, **kwargs)
    #                 modify_sym_energy_for_cryst=False, energy=2)

    return out_file

format_sdf

format_sdf(lines: list, to_file: AnyStr = None, out_path: AnyStr = os.getcwd(), modify_sym_energy_for_cryst: bool = False, energy: int = None) -> AnyStr

Ensure proper sdf formatting before proceeding

Parameters:

  • lines (list) –

    The symmetry definition file lines

  • to_file (AnyStr, default: None ) –

    The name of the symmetry definition file

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

    The location the symmetry definition file should be written

  • modify_sym_energy_for_cryst (bool, default: False ) –

    Whether the symmetric energy should match crystallographic systems

  • energy (int, default: None ) –

    Scalar to modify the Rosetta energy by

Returns:

  • AnyStr

    The location the symmetry definition file was written

Source code in symdesign/structure/model.py
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
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
def format_sdf(self, lines: list, to_file: AnyStr = None, out_path: AnyStr = os.getcwd(),
               modify_sym_energy_for_cryst: bool = False, energy: int = None) -> AnyStr:
    """Ensure proper sdf formatting before proceeding

    Args:
        lines: The symmetry definition file lines
        to_file: The name of the symmetry definition file
        out_path: The location the symmetry definition file should be written
        modify_sym_energy_for_cryst: Whether the symmetric energy should match crystallographic systems
        energy: Scalar to modify the Rosetta energy by

    Returns:
        The location the symmetry definition file was written
    """
    subunits, virtuals, jumps_com, jumps_subunit, trunk = [], [], [], [], []
    for idx, line in enumerate(lines, 1):
        if line.startswith('xyz'):
            virtual = line.split()[1]
            if virtual.endswith('_base'):
                subunits.append(virtual)
            else:
                virtuals.append(virtual.lstrip('VRT'))
            # last_vrt = line + 1
        elif line.startswith('connect_virtual'):
            jump = line.split()[1].lstrip('JUMP')
            if jump.endswith('_to_com'):
                jumps_com.append(jump[:-7])
            elif jump.endswith('_to_subunit'):
                jumps_subunit.append(jump[:-11])
            else:
                trunk.append(jump)
            last_jump = idx  # index where the VRTs and connect_virtuals end. The "last jump"

    if set(trunk).difference(virtuals):
        raise SymmetryError(
            f"Symmetry Definition File VRTS are malformed. See '{to_file}'")
    if len(subunits) != self.number_of_symmetry_mates:
        raise SymmetryError(
            f"Symmetry Definition File VRTX_base are malformed. See '{to_file}'")

    if self.is_dihedral():  # Remove dihedral connecting (trunk) virtuals: VRT, VRT0, VRT1
        virtuals = [virtual for virtual in virtuals if len(virtual) > 1]  # subunit_
    else:
        try:
            virtuals.remove('')
        except ValueError:  # '' not present
            pass

    jumps_com_to_add = set(virtuals).difference(jumps_com)
    count_ = 0
    if jumps_com_to_add:
        for count_, jump_com in enumerate(jumps_com_to_add, count_):
            lines.insert(last_jump + count_,
                         f'connect_virtual JUMP{jump_com}_to_com VRT{jump_com} VRT{jump_com}_base')
        lines[-2] = lines[-2].strip() + (' JUMP%s_to_subunit' * len(jumps_com_to_add)) % tuple(jumps_com_to_add)

    jumps_subunit_to_add = set(virtuals).difference(jumps_subunit)
    if jumps_subunit_to_add:
        for count_, jump_subunit in enumerate(jumps_subunit_to_add, count_):
            lines.insert(last_jump + count_,
                         f'connect_virtual JUMP{jump_subunit}_to_subunit VRT{jump_subunit}_base SUBUNIT')
        lines[-1] = \
            lines[-1].strip() + (' JUMP%s_to_subunit' * len(jumps_subunit_to_add)) % tuple(jumps_subunit_to_add)

    if modify_sym_energy_for_cryst:
        # new energy should equal the energy multiplier times the scoring subunit plus additional complex subunits
        # where complex subunits = num_subunits - 1
        # new_energy = 'E = %d*%s + ' % (energy, subunits[0])  # assumes subunits are read in alphanumerical order
        # new_energy += ' + '.join('1*(%s:%s)' % t for t in zip(repeat(subunits[0]), subunits[1:]))
        lines[1] = f'E = 2*{subunits[0]}+{"+".join(f"1*({subunits[0]}:{pair})" for pair in subunits[1:])}'
    else:
        if not energy:
            energy = len(subunits)
        lines[1] = \
            f'E = {energy}*{subunits[0]}+{"+".join(f"{energy}*({subunits[0]}:{pair})" for pair in subunits[1:])}'

    if not to_file:
        to_file = os.path.join(out_path, f'{self.name}.sdf')

    with open(to_file, 'w') as f:
        f.write('%s\n' % '\n'.join(lines))
    if count_ != 0:
        self.log.info(f"Symmetry Definition File '{to_file}' was missing {count_} lines. A fix was attempted and "
                      'modeling may be affected')
    return to_file

reset_mates

reset_mates()

Remove oligomeric chains. They should be generated fresh

Source code in symdesign/structure/model.py
4338
4339
4340
4341
def reset_mates(self):
    """Remove oligomeric chains. They should be generated fresh"""
    self._chains.clear()
    self._chains.append(self)

fragment_db

fragment_db(fragment_db: FragmentDatabase)

Set the Structure FragmentDatabase to assist with Fragment creation, manipulation, and profiles. Sets .fragment_db for each dependent Structure in 'structure_containers'

Entity specific implementation to prevent recursion with [1:]

Source code in symdesign/structure/model.py
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
@ContainsResidues.fragment_db.setter
def fragment_db(self, fragment_db: FragmentDatabase):
    """Set the Structure FragmentDatabase to assist with Fragment creation, manipulation, and profiles.
    Sets .fragment_db for each dependent Structure in 'structure_containers'

    Entity specific implementation to prevent recursion with [1:]
    """
    # Set this instance then set all dependents
    super(Structure, Structure).fragment_db.fset(self, fragment_db)
    _fragment_db = self._fragment_db
    if _fragment_db is not None:
        for structure_type in self.structure_containers:
            for structure in self.__getattribute__(structure_type)[1:]:
                structure.fragment_db = _fragment_db
    else:  # This is likely the RELOAD_DB token. Just return.
        return

Model

Model(chains: bool | Sequence[Chain] = True, chain_ids: Iterable[str] = None, rename_chains: bool = False, as_mates: bool = False, **kwargs)

Bases: ContainsChains

The main class for simple Structure manipulation, particularly containing multiple Chain instances

Can initialize by passing a file, or passing Atom/Residue/Chain instances. If your Structure is symmetric, a SymmetricModel should be used instead. If you have multiple Model instances, use the MultiModel class.

Parameters:

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

    A list of identifiers to assign to each Chain instance

  • chains (bool | Sequence[Chain], default: True ) –

    Whether to create Chain instances from passed Structure container instances, or existing Chain instances to create the Model with

  • rename_chains (bool, default: False ) –

    Whether to name each chain an incrementally new Alphabetical character

  • as_mates (bool, default: False ) –

    Whether Chain instances should be controlled by a captain (True), or be dependents

Source code in symdesign/structure/model.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
def __init__(self, chains: bool | Sequence[Chain] = True, chain_ids: Iterable[str] = None,
             rename_chains: bool = False, as_mates: bool = False, **kwargs):
    """Construct the instance

    Args:
        chain_ids: A list of identifiers to assign to each Chain instance
        chains: Whether to create Chain instances from passed Structure container instances, or existing Chain
            instances to create the Model with
        rename_chains: Whether to name each chain an incrementally new Alphabetical character
        as_mates: Whether Chain instances should be controlled by a captain (True), or be dependents
    """
    super().__init__(**kwargs)  # ContainsChains
    # Use the same list as default to save parsed chain ids
    self.original_chain_ids = self.chain_ids = []
    if chains:  # Populate chains
        self.structure_containers.append('_chains')
        if isinstance(chains, Sequence):
            # Set the chains accordingly, copying them to remove prior relationships
            self._chains = list(chains)
            self._copy_structure_containers()  # Copy each Chain in chains
            if as_mates:
                if self.residues is None:
                    raise DesignError(
                        f"Couldn't initialize {self.__class__.__name__}.chains as it is missing '.residues' while "
                        f"{as_mates=}"
                    )
            else:  # Create the instance from existing chains
                self.assign_residues_from_structures(chains)
                # Reindex all residue and atom indices
                self.reset_and_reindex_structures(self._chains)
                # Set the parent attribute for all containers
                self._update_structure_container_attributes(_parent=self)

            if chain_ids:
                for chain, id_ in zip(self.chains, chain_ids):
                    chain.chain_id = id_
            # By using extend, self.original_chain_ids are set as well
            self.chain_ids.extend([chain.chain_id for chain in self.chains])
        else:  # Create Chain instances from Residues
            self._chains = []
            self._create_chains(chain_ids=chain_ids)
            if as_mates:
                for chain in self.chains:
                    chain.make_parent()

        if rename_chains or not self.are_chain_ids_pdb_compatible():
            self.rename_chains()

        self.log.debug(f'Original chain_ids: {",".join(self.original_chain_ids)} | '
                       f'Loaded chain_ids: {",".join(self.chain_ids)}')
    else:
        self._chains = []

    if self.is_parent():
        reference_sequence = self.metadata.reference_sequence
        if isinstance(reference_sequence, dict):  # Was parsed from file
            self.set_reference_sequence_from_seqres(reference_sequence)

Models

Models(models: Iterable[ContainsEntities | Entity], name: str = None, **kwargs)

Bases: UserList

Container for Model instances. Primarily used for writing [symmetric] multimodel-like Structure instances

Source code in symdesign/structure/model.py
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
def __init__(self, models: Iterable[ContainsEntities | Entity], name: str = None, **kwargs):
    super().__init__(initlist=models)  # Sets UserList.data to models

    for model in self:
        if not isinstance(model, (ContainsEntities, Entity)):
            raise TypeError(
                f"Can't initialize {self.__class__.__name__} with a {type(model).__name__}. Must be an Iterable"
                f' of {Model.__name__}')

    self.name = name if name else f'Nameless-{Models.__name__}'

number_of_models property

number_of_models: int

The number of unique models that are found in the Models object

from_models classmethod

from_models(models: Iterable[Model], **kwargs)

Initialize from an iterable of Model instances

Source code in symdesign/structure/model.py
4457
4458
4459
4460
@classmethod
def from_models(cls, models: Iterable[Model], **kwargs):
    """Initialize from an iterable of Model instances"""
    return cls(models=models, **kwargs)

write

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

Write Model Atoms to a file specified by out_path or with a passed file_handle

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

  • multimodel (bool, default: False ) –

    Whether MODEL and ENDMDL records should be added at the end of each Model

  • increment_chains (bool, default: False ) –

    Whether to write each Chain with an incrementing chain ID, otherwise use the chain IDs present, repeating for each Model

Keyword Args assembly: bool = False - Whether to write an assembly representation of each Model instance

Returns:

  • AnyStr | None

    The name of the written file if out_path is used

Source code in symdesign/structure/model.py
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
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
def write(self, out_path: bytes | str = os.getcwd(), file_handle: IO = None, header: str = None,
          multimodel: bool = False, increment_chains: bool = False, **kwargs) -> AnyStr | None:
    """Write Model Atoms to a file specified by out_path or with a passed file_handle

    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
        multimodel: Whether MODEL and ENDMDL records should be added at the end of each Model
        increment_chains: Whether to write each Chain with an incrementing chain ID,
            otherwise use the chain IDs present, repeating for each Model

    Keyword Args
        assembly: bool = False - Whether to write an assembly representation of each Model instance

    Returns:
        The name of the written file if out_path is used
    """
    logger.debug(f'{Models.__name__} is writing {repr(self)}')

    def _write(handle) -> None:
        if increment_chains:
            available_chain_ids = chain_id_generator()

            def _get_chain_id(struct: Chain) -> str:
                return next(available_chain_ids)

        else:

            def _get_chain_id(struct: Chain) -> str:
                return struct.chain_id

        chain: Chain
        offset = 0

        def _write_model(_model):
            nonlocal offset
            for chain in _model.entities:
                chain_id = _get_chain_id(chain)
                chain.write(file_handle=handle, chain_id=chain_id, atom_offset=offset, **kwargs)
                c_term_residue: Residue = chain.c_terminal_residue
                offset += chain.number_of_atoms
                handle.write(f'TER   {offset + 1:>5d}      {c_term_residue.type:3s} '
                             f'{chain_id:1s}{c_term_residue.number:>4d}\n')

        if multimodel:
            for model_number, model in enumerate(self, 1):
                handle.write('{:9s}{:>4d}\n'.format('MODEL', model_number))
                _write_model(model)
                handle.write('ENDMDL\n')
        else:
            for model in self:
                _write_model(model)

    if file_handle:
        return _write(file_handle)
    else:  # out_path always has default argument current working directory
        _header = ''  # self.format_header(**kwargs)
        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)
            _write(outfile)
        return out_path

SymmetricModel

SymmetricModel(sym_entry: SymEntry | int = None, symmetry: str = None, transformations: list[TransformationMapping] = None, uc_dimensions: list[float] = None, symmetry_operators: ndarray | list = None, rotation_matrices: ndarray | list = None, translation_matrices: ndarray | list = None, surrounding_uc: bool = True, **kwargs)

Bases: SymmetryOpsMixin, ContainsEntities

Parameters:

  • sym_entry (SymEntry | int, default: None ) –

    The SymEntry which specifies all symmetry parameters

  • symmetry (str, default: None ) –

    The name of a symmetry to be searched against compatible symmetries

  • transformations (list[TransformationMapping], default: None ) –

    Transformation operations that reproduce the oligomeric/assembly for each Entity

  • rotation_matrices (ndarray | list, default: None ) –

    Rotation operations that create the symmetric state

  • translation_matrices (ndarray | list, default: None ) –

    Translation operations that create the symmetric state

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

    The unit cell dimensions for the crystalline symmetry

  • symmetry_operators (ndarray | list, default: None ) –

    A set of custom expansion matrices

  • surrounding_uc (bool, default: True ) –

    Whether the 3x3 layer group, or 3x3x3 space group should be generated

Source code in symdesign/structure/model.py
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
def __init__(self, sym_entry: utils.SymEntry.SymEntry | int = None, symmetry: str = None,
             transformations: list[types.TransformationMapping] = None, uc_dimensions: list[float] = None,
             symmetry_operators: np.ndarray | list = None, rotation_matrices: np.ndarray | list = None,
             translation_matrices: np.ndarray | list = None, surrounding_uc: bool = True, **kwargs):
    """Construct the instance

    Args:
        sym_entry: The SymEntry which specifies all symmetry parameters
        symmetry: The name of a symmetry to be searched against compatible symmetries
        transformations: Transformation operations that reproduce the oligomeric/assembly for each Entity
        rotation_matrices: Rotation operations that create the symmetric state
        translation_matrices: Translation operations that create the symmetric state
        uc_dimensions: The unit cell dimensions for the crystalline symmetry
        symmetry_operators: A set of custom expansion matrices
        surrounding_uc: Whether the 3x3 layer group, or 3x3x3 space group should be generated
    """
    super().__init__(**kwargs)  # SymmetryOpsMixin
    self._expand_matrices = self._expand_translations = None
    self.set_symmetry(sym_entry=sym_entry, symmetry=symmetry, uc_dimensions=uc_dimensions,
                      operators=symmetry_operators, rotations=rotation_matrices, translations=translation_matrices,
                      transformations=transformations, surrounding_uc=surrounding_uc)

symmetric_coords_split_by_entity property

symmetric_coords_split_by_entity: list[list[ndarray]]

A view of the symmetric coords split for each symmetric model by the Pose Entity indices

symmetric_coords_by_entity property

symmetric_coords_by_entity: list[ndarray]

A view of the symmetric coords for each Entity in order of the Pose Entity indices

center_of_mass_symmetric_entities property

center_of_mass_symmetric_entities: list[list[ndarray]]

The center of mass position for each Entity instance in the symmetric system for each symmetry mate with shape [(number_of_symmetry_mates, 3), ... number_of_entities]

assembly property

assembly: Model

Provides the Structure object containing all symmetric chains in the assembly unless the design is 2- or 3-D then the assembly only contains the contacting models

assembly_minimally_contacting property

assembly_minimally_contacting: Model

Provides the Structure object only containing the SymmetricModel instances contacting the ASU

entity_transformations property

entity_transformations: list[TransformationMapping] | list

The transformation parameters for each Entity in the SymmetricModel. Each entry has the TransformationMapping type

assembly_tree property

assembly_tree: BinaryTreeType

Holds the tree structure of the backbone and cb symmetric_coords not including the asu coords

from_assembly classmethod

from_assembly(assembly: Model, sym_entry: SymEntry | int = None, symmetry: str = None, **kwargs)

Initialize from a symmetric assembly

Source code in symdesign/structure/model.py
4591
4592
4593
4594
4595
4596
4597
4598
4599
@classmethod
def from_assembly(cls, assembly: Model, sym_entry: utils.SymEntry.SymEntry | int = None,
                  symmetry: str = None, **kwargs):
    """Initialize from a symmetric assembly"""
    if symmetry is None and sym_entry is None:
        raise ValueError(
            "Can't initialize without symmetry. Pass 'symmetry' or 'sym_entry' to "
            f'{cls.__name__}.{cls.from_assembly.__name__}() constructor')
    return cls(structure=assembly, sym_entry=sym_entry, symmetry=symmetry, **kwargs)

set_symmetry

set_symmetry(sym_entry: SymEntry | int = None, symmetry: str = None, crystal: bool = False, cryst_record: str = None, uc_dimensions: list[float] = None, operators: tuple[ndarray | list[list[float]], ndarray | list[float]] | ndarray = None, rotations: ndarray | list[list[float]] = None, translations: ndarray | list[float] = None, transformations: list[TransformationMapping] = None, surrounding_uc: bool = True, **kwargs)

Set the model symmetry using the CRYST1 record, or the unit cell dimensions and the Hermann-Mauguin symmetry notation (in CRYST1 format, ex P432) for the Model assembly. If the assembly is a point group, only the symmetry notation is required

Parameters:

  • sym_entry (SymEntry | int, default: None ) –

    The SymEntry which specifies all symmetry parameters

  • symmetry (str, default: None ) –

    The name of a symmetry to be searched against compatible symmetries

  • crystal (bool, default: False ) –

    Whether crystalline symmetry should be used

  • cryst_record (str, default: None ) –

    If a CRYST1 record is known and should be used

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

    The unit cell dimensions for the crystalline symmetry

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

    A set of custom expansion matrices

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

    A set of rotation matrices used to recapitulate the SymmetricModel from the asymmetric unit

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

    A set of translation vectors used to recapitulate the SymmetricModel from the asymmetric unit

  • transformations (list[TransformationMapping], default: None ) –

    Transformation operations that reproduce the oligomeric state for each Entity

  • surrounding_uc (bool, default: True ) –

    Whether the 3x3 layer group, or 3x3x3 space group should be generated

  • crystal (bool, default: False ) –

    Whether crystalline symmetry should be used

  • cryst_record (str, default: None ) –

    If a CRYST1 record is known and should be used

Source code in symdesign/structure/model.py
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
4667
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
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
def set_symmetry(self, sym_entry: utils.SymEntry.SymEntry | int = None, symmetry: str = None,
                 crystal: bool = False, cryst_record: str = None, uc_dimensions: list[float] = None,
                 operators: tuple[np.ndarray | list[list[float]], np.ndarray | list[float]] | np.ndarray = None,
                 rotations: np.ndarray | list[list[float]] = None, translations: np.ndarray | list[float] = None,
                 transformations: list[types.TransformationMapping] = None, surrounding_uc: bool = True,
                 **kwargs):
    """Set the model symmetry using the CRYST1 record, or the unit cell dimensions and the Hermann-Mauguin symmetry
    notation (in CRYST1 format, ex P432) for the Model assembly. If the assembly is a point group, only the symmetry
    notation is required

    Args:
        sym_entry: The SymEntry which specifies all symmetry parameters
        symmetry: The name of a symmetry to be searched against compatible symmetries
        crystal: Whether crystalline symmetry should be used
        cryst_record: If a CRYST1 record is known and should be used
        uc_dimensions: The unit cell dimensions for the crystalline symmetry
        operators: A set of custom expansion matrices
        rotations: A set of rotation matrices used to recapitulate the SymmetricModel from the asymmetric unit
        translations: A set of translation vectors used to recapitulate the SymmetricModel from the asymmetric unit
        transformations: Transformation operations that reproduce the oligomeric state for each Entity
        surrounding_uc: Whether the 3x3 layer group, or 3x3x3 space group should be generated
        crystal: Whether crystalline symmetry should be used
        cryst_record: If a CRYST1 record is known and should be used
    """
    chains = self._chains
    super().set_symmetry(
        sym_entry=sym_entry, symmetry=symmetry,
        crystal=crystal, cryst_record=cryst_record, uc_dimensions=uc_dimensions,
    )
    number_of_symmetry_mates = self.number_of_symmetry_mates

    if not self.is_symmetric():
        # No symmetry keyword args were passed
        if operators is not None or rotations is not None or translations is not None:
            passed_args = []
            if operators:
                passed_args.append('operators')
            if rotations:
                passed_args.append('rotations')
            if translations:
                passed_args.append('translations')
            raise ConstructionError(
                f"Couldn't set_symmetry() using {', '.join(passed_args)} without explicitly passing "
                "'symmetry' or 'sym_entry'"
            )
        return

    # Set rotations and translations to the correct symmetry operations
    # where operators, rotations, and translations are user provided from some sort of BIOMT (fiber, other)
    if operators is not None:
        symmetry_source_arg = "'operators' "

        num_operators = len(operators)
        if isinstance(operators, tuple) and num_operators == 2:
            self.log.warning("Providing custom symmetry 'operators' may result in improper symmetric "
                             'configuration. Proceed with caution')
            rotations, translations = operators
        elif isinstance(operators, Sequence) and num_operators == number_of_symmetry_mates:
            rotations = []
            translations = []
            try:
                for rot, tx in operators:
                    rotations.append(rot)
                    translations.append(tx)
            except TypeError:  # Unpack failed
                raise ValueError(
                    f"Couldn't parse the 'operators'={repr(operators)}.\n\n"
                    "Expected a Sequence[rotation shape=(3,3). translation shape=(3,)] pairs."
                )
        elif isinstance(operators, np.ndarray):
            if operators.shape[1:] == (3, 4):
                # Parse from a single input of 3 row by 4 column style, like BIOMT
                rotations = operators[:, :, :3]
                translations = operators[:, :, 3:].squeeze()
            elif operators.shape[1:] == 3:  # Assume just rotations
                rotations = operators
                translations = np.tile(utils.symmetry.origin, len(rotations))
            else:
                raise ConstructionError(
                    f"The 'operators' form {repr(operators)} isn't supported.")
        else:
            raise ConstructionError(
                f"The 'operators' form {repr(operators)} isn't supported. Must provide a tuple of "
                'array-like objects with the order (rotation matrices, translation vectors) or use the '
                "'rotations' and 'translations' keyword args")
    else:
        symmetry_source_arg = ''

    # Now that symmetry is set, check if the Structure parsed all symmetric chains
    if len(chains) == self.number_of_entities * number_of_symmetry_mates:
        parsed_assembly = True
    else:
        parsed_assembly = False

    # Set the symmetry operations
    if rotations is not None and translations is not None:
        if not isinstance(rotations, np.ndarray):
            rotations = np.ndarray(rotations)
        if rotations.ndim == 3:
            # Assume operators were provided in a standard orientation and transpose for subsequent efficiency
            # Using .swapaxes(-2, -1) call here instead of .transpose() for safety
            self._expand_matrices = rotations.swapaxes(-2, -1)
        else:
            raise SymmetryError(
                f"Expected {symmetry_source_arg}rotation matrices with 3 dimensions, not {rotations.ndim} "
                "dimensions. Ensure the passed rotation matrices have a shape of (N symmetry operations, 3, 3)"
            )

        if not isinstance(translations, np.ndarray):
            translations = np.ndarray(translations)
        if translations.ndim == 2:
            # Assume operators were provided in a standard orientation each vector needs to be in own array on dim=2
            self._expand_translations = translations[:, None, :]
        else:
            raise SymmetryError(
                f"Expected {symmetry_source_arg}translation vectors with 2 dimensions, not {translations.ndim} "
                "dimensions. Ensure the passed translations have a shape of (N symmetry operations, 3)"
            )
    else:  # The symmetry operators must be possible to find or canonical.
        symmetry_source_arg = "'chains' "
        # Get canonical operators
        if self.dimension == 0:
            # The _expand_matrices rotation matrices are pre-transposed to avoid repetitive operations
            _expand_matrices = utils.symmetry.point_group_symmetry_operatorsT[self.symmetry]
            # The _expand_translations vectors are pre-sliced to enable numpy operations
            _expand_translations = \
                np.tile(utils.symmetry.origin, (self.number_of_symmetry_mates, 1))[:, None, :]

            if parsed_assembly:
                # The Structure should have symmetric chains
                # Set up symmetry operations using orient

                # Save the original position for subsequent reversion
                ca_coords = self.ca_coords.copy()
                # Transform to canonical orientation.
                self.orient()
                # Set the symmetry operations again as they are incorrect after orient()
                self._expand_matrices = _expand_matrices
                self._expand_translations = _expand_translations
                # Next, transform back to original and carry the correctly situated symmetry operations along.
                _, rot, tx = superposition3d(ca_coords, self.ca_coords)
                self.transform(rotation=rot, translation=tx)
            else:
                self._expand_matrices = _expand_matrices
                self._expand_translations = _expand_translations
        else:
            self._expand_matrices, self._expand_translations = \
                utils.symmetry.space_group_symmetry_operatorsT[self.symmetry]

    # Removed parsed chain information
    self.reset_mates()

    try:
        self._symmetric_coords.coords
    except AttributeError:
        self.generate_symmetric_coords(surrounding_uc=surrounding_uc)

    # Check if the oligomer is constructed for each entity
    for entity, subunit_number in zip(self.entities, self.sym_entry.group_subunit_numbers):
        if entity.number_of_symmetry_mates != subunit_number:
            # Generate oligomers for each entity
            self.make_oligomers(transformations=transformations)
            break

    # Once oligomers are specified the ASU can be set properly
    self.set_contacting_asu(from_assembly=parsed_assembly)

get_asu_interaction_model_indices

get_asu_interaction_model_indices(calculate_contacts: bool = True, distance: float = 8.0, **kwargs) -> list[int]

From an ASU, find the symmetric models that immediately surround the ASU

Parameters:

  • calculate_contacts (bool, default: True ) –

    Whether to calculate interacting models by atomic contacts

  • distance (float, default: 8.0 ) –

    When calculate_contacts is True, the CB distance which nearby symmetric models should be found When calculate_contacts is False, uses the ASU radius plus the maximum Entity radius

Returns:

  • list[int]

    The indices of the models that contact the asu

Source code in symdesign/structure/model.py
5087
5088
5089
5090
5091
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
def get_asu_interaction_model_indices(self, calculate_contacts: bool = True, distance: float = 8., **kwargs) -> \
        list[int]:
    """From an ASU, find the symmetric models that immediately surround the ASU

    Args:
        calculate_contacts: Whether to calculate interacting models by atomic contacts
        distance: When calculate_contacts is True, the CB distance which nearby symmetric models should be found
            When calculate_contacts is False, uses the ASU radius plus the maximum Entity radius

    Returns:
        The indices of the models that contact the asu
    """
    if calculate_contacts:
        # DEBUG self.report_symmetric_coords(self.get_asu_interaction_model_indices.__name__)
        asu_query = self.assembly_tree.query_radius(self.coords[self.backbone_and_cb_indices], distance)
        # Combine each subarray of the asu_query and divide by the assembly_tree interval length -> len(asu_query)
        interacting_models = (
                                     np.array(list({asu_idx for asu_contacts in asu_query.tolist()
                                                    for asu_idx in asu_contacts.tolist()})
                                              )
                                     // len(asu_query)
                             ) + 1
        # The asu is missing from assembly_tree so add 1 to get the
        # correct model indices ^
        interacting_models = np.unique(interacting_models).tolist()
    else:
        # The furthest point from the asu COM + the max individual Entity radius
        distance = self.radius + max([entity.radius for entity in self.entities])
        self.log.debug(f'For ASU neighbor query, using the distance={distance}')
        center_of_mass = self.center_of_mass
        interacting_models = [idx for idx, sym_model_com in enumerate(self.center_of_mass_symmetric_models)
                              if np.linalg.norm(center_of_mass - sym_model_com) <= distance]
        # Remove the first index from the interacting_models due to exclusion of asu from convention above
        interacting_models.pop(0)

    return interacting_models

get_asu_atom_indices

get_asu_atom_indices(as_slice: bool = False) -> list[int] | slice

Find the coordinate indices of the asu equivalent model in the SymmetricModel. Zero-indexed

Returns:

  • list[int] | slice

    The indices in the SymmetricModel where the ASU is also located

Source code in symdesign/structure/model.py
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
def get_asu_atom_indices(self, as_slice: bool = False) -> list[int] | slice:
    """Find the coordinate indices of the asu equivalent model in the SymmetricModel. Zero-indexed

    Returns:
        The indices in the SymmetricModel where the ASU is also located
    """
    asu_model_idx = self.asu_model_index
    number_of_atoms = self.number_of_atoms
    start_idx = number_of_atoms * asu_model_idx
    end_idx = number_of_atoms * (asu_model_idx + 1)

    if as_slice:
        return slice(start_idx, end_idx)
    else:
        return list(range(start_idx, end_idx))

get_oligomeric_atom_indices

get_oligomeric_atom_indices(entity: Entity) -> list[int]

Find the coordinate indices of the intra-oligomeric equivalent models in the SymmetricModel. Zero-indexed

Parameters:

  • entity (Entity) –

    The Entity with oligomeric chains to query for corresponding symmetry mates

Returns:

  • list[int]

    The indices in the SymmetricModel where the intra-oligomeric contacts are located

Source code in symdesign/structure/model.py
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
def get_oligomeric_atom_indices(self, entity: Entity) -> list[int]:
    """Find the coordinate indices of the intra-oligomeric equivalent models in the SymmetricModel. Zero-indexed

    Args:
        entity: The Entity with oligomeric chains to query for corresponding symmetry mates

    Returns:
        The indices in the SymmetricModel where the intra-oligomeric contacts are located
    """
    number_of_atoms = self.number_of_atoms
    oligomeric_atom_indices = []
    for model_number in self.oligomeric_model_indices.get(entity):
        oligomeric_atom_indices.extend(range(number_of_atoms * model_number,
                                             number_of_atoms * (model_number + 1)))
    return oligomeric_atom_indices

get_asu_interaction_indices

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

Find the coordinate indices for the models in the SymmetricModel interacting with the asu. Zero-indexed

Other Parameters:

  • calculate_contacts

    bool = True - Whether to calculate interacting models by atomic contacts

  • distance

    float = 8.0 - When calculate_contacts is True, the CB distance which nearby symmetric models should be found. When calculate_contacts is False, uses the ASU radius plus the maximum Entity radius

Returns:

  • list[int]

    The indices in the SymmetricModel where the asu contacts other models

Source code in symdesign/structure/model.py
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
def get_asu_interaction_indices(self, **kwargs) -> list[int]:
    """Find the coordinate indices for the models in the SymmetricModel interacting with the asu. Zero-indexed

    Keyword Args:
        calculate_contacts: bool = True - Whether to calculate interacting models by atomic contacts
        distance: float = 8.0 - When calculate_contacts is True, the CB distance which nearby symmetric models
             should be found. When calculate_contacts is False, uses the ASU radius plus the maximum Entity radius

    Returns:
        The indices in the SymmetricModel where the asu contacts other models
    """
    number_of_atoms = self.number_of_atoms
    interacting_indices = []
    for model_number in self.get_asu_interaction_model_indices(**kwargs):
        interacting_indices.extend(range(number_of_atoms * model_number,
                                         number_of_atoms * (model_number+1)))

    return interacting_indices

make_oligomers

make_oligomers(transformations: list[TransformationMapping] = None)

Generate oligomers for each Entity in the SymmetricModel

Parameters:

  • transformations (list[TransformationMapping], default: None ) –

    The entity_transformations operations that reproduce the individual oligomers

Source code in symdesign/structure/model.py
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
def make_oligomers(self, transformations: list[types.TransformationMapping] = None):
    """Generate oligomers for each Entity in the SymmetricModel

    Args:
        transformations: The entity_transformations operations that reproduce the individual oligomers
    """
    self.log.debug(f'Initializing oligomeric symmetry')
    if transformations is None or not all(transformations):
        # If this fails then the symmetry is failed... It should never return an empty list as
        # .entity_transformations -> ._assign_pose_transformation() will raise SymmetryError
        transformations = self.entity_transformations

    for entity, subunit_number, symmetry, transformation in zip(
            self.entities, self.sym_entry.group_subunit_numbers, self.sym_entry.groups, transformations):
        if entity.number_of_symmetry_mates != subunit_number:
            entity.make_oligomer(symmetry=symmetry, **transformation)
        else:
            self.log.debug(f'{repr(entity)} is already the correct oligomer, skipping make_oligomer()')

symmetric_assembly_is_clash

symmetric_assembly_is_clash(measure: coords_type_literal = default_clash_criteria, distance: float = default_clash_distance, warn: bool = False) -> bool

Returns True if the SymmetricModel presents any clashes at the specified distance

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

Returns:

  • bool

    True if the symmetric assembly clashes with the asu, False otherwise

Source code in symdesign/structure/model.py
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
def symmetric_assembly_is_clash(self, measure: coords_type_literal = default_clash_criteria,
                                distance: float = default_clash_distance, warn: bool = False) -> bool:
    """Returns True if the SymmetricModel presents any clashes at the specified distance

    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

    Returns:
        True if the symmetric assembly clashes with the asu, False otherwise
    """
    if not self.is_symmetric():
        self.log.warning("Can't check if the assembly is clashing as it has no symmetry")
        return False
    indices = self.__getattribute__(f'{measure}_indices')
    clashes = self.assembly_tree.two_point_correlation(self.coords[indices], [distance])
    if clashes[0] > 0:
        if warn:
            self.log.warning(
                f"{self.name}: Found {clashes[0]} clashing sites. Pose isn't a viable symmetric assembly")
        return True  # Clash
    else:
        return False  # No clash

write

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

Write SymmetricModel Atoms to a file specified by out_path or with a passed file_handle

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

  • assembly (bool, default: False ) –

    Whether to write the full assembly. Default writes only the ASU

Other Parameters:

  • increment_chains

    bool = False - Whether to write each Structure with a new chain name, otherwise write as a new Model

  • surrounding_uc

    bool = False - Whether the 3x3 layer group, or 3x3x3 space group should be written when assembly is True and self.dimension > 1

Returns:

  • AnyStr | None

    The name of the written file if out_path is used

Source code in symdesign/structure/model.py
5606
5607
5608
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
5646
5647
5648
5649
5650
5651
5652
5653
def write(self, out_path: bytes | str = os.getcwd(), file_handle: IO = None, header: str = None,
          assembly: bool = False, **kwargs) -> AnyStr | None:
    """Write SymmetricModel Atoms to a file specified by out_path or with a passed file_handle

    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
        assembly: Whether to write the full assembly. Default writes only the ASU

    Keyword Args:
        increment_chains: bool = False - Whether to write each Structure with a new chain name, otherwise write as
            a new Model
        surrounding_uc: bool = False - Whether the 3x3 layer group, or 3x3x3 space group should be written when
            assembly is True and self.dimension > 1

    Returns:
        The name of the written file if out_path is used
    """
    self.log.debug(f'{SymmetricModel.__name__} is writing {repr(self)}')
    is_symmetric = self.is_symmetric()

    def _write(handle) -> None:
        if is_symmetric:
            if assembly:
                models = self._generate_assembly_models(**kwargs)
                models.write(file_handle=handle, **kwargs)
            else:  # Skip all models, write asu. Use biomt_record/cryst_record for symmetry
                for entity in self.entities:
                    entity.write(file_handle=handle, **kwargs)
        else:  # Finish with a standard write
            super(Structure, Structure).write(self, file_handle=handle, **kwargs)

    if file_handle:
        return _write(file_handle)
    else:  # out_path default argument is current working directory
        # Write the header as an asu if no assembly requested or not symmetric
        assembly_header = (is_symmetric and assembly) or not is_symmetric
        _header = self.format_header(assembly=assembly_header, **kwargs)
        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)
            _write(outfile)
        return out_path

Pose

Pose(**kwargs)

Bases: SymmetricModel, MetricsMixin

A Pose is made of single or multiple Structure objects such as Entities, Chains, or other structures. All objects share a common feature such as the same symmetric system or the same general atom configuration in separate models across the Structure or sequence.

Parameters:

  • **kwargs
Source code in symdesign/structure/model.py
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
def __init__(self, **kwargs):
    """Construct the instance

    Args:
        **kwargs:
    """
    super().__init__(**kwargs)  # Pose
    self._design_selection_entity_names = {entity.name for entity in self.entities}
    self._design_selector_atom_indices = set(self._atom_indices)
    self._required_atom_indices = []
    self._interface_residue_indices_by_entity_name_pair = {}
    self._interface_residue_indices_by_interface = {}
    self._interface_residue_indices_by_interface_unique = {}
    self._fragment_info_by_entity_pair = {}
    self.split_interface_ss_elements = {}
    self.ss_sequence_indices = []
    self.ss_type_sequence = []

split_interface_ss_elements instance-attribute

split_interface_ss_elements: dict[int, list[int]] = {}

Stores the interface number mapped to an index corresponding to the secondary structure type Ex: {1: [0, 0, 1, 2, ...] , 2: [9, 9, 9, 13, ...]]}

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

active_entities property

active_entities: list[Entity]

The Entity instances that are available for design calculations given a design selector

interface_residues property

interface_residues: list[Residue]

The Residue instances identified in interfaces in the Pose sorted based on index. Residue instances may be completely buried depending on interface distance

interface_residues_by_entity_pair property

interface_residues_by_entity_pair: dict[tuple[Entity, Entity], tuple[list[Residue], list[Residue]]]

The Residue instances identified between pairs of Entity instances

interface_neighbor_residues property

interface_neighbor_residues: list[Residue]

The Residue instances identified as neighbors to interfaces in the Pose. Assumes default distance of 8 A

design_residues property writable

design_residues: list[Residue]

The Residue instances identified for design in the Pose. Includes interface_residues

required_residues property

required_residues: list[Residue]

Returns the Residue instances that are required according to DesignSelector

core_residues property

core_residues: list[Residue]

Get the Residue instances that reside in the core of the interfaces

Parameters:

  • relative_sasa_thresh

    The relative area threshold that the Residue should fall below before it is considered 'core'. Default cutoff percent 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 core Residue instances

rim_residues property

rim_residues: list[Residue]

Get the Residue instances that reside in the rim of the interface

Parameters:

  • relative_sasa_thresh

    The relative area threshold that the Residue should fall below before it is considered 'rim'. Default cutoff percent 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 rim Residue instances

support_residues property

support_residues: list[Residue]

Get the Residue instances that support the interface

Parameters:

  • relative_sasa_thresh

    The relative area threshold that the Residue should fall below before it is considered 'support'. Default cutoff percent 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 support Residue instances

fragment_info_by_entity_pair property

fragment_info_by_entity_pair: dict[tuple[Entity, Entity], list[FragmentInfo]]

Returns the FragmentInfo present as the result of structural overlap between pairs of Entity instances

interface_fragment_residue_indices property writable

interface_fragment_residue_indices: list[int]

The Residue indices where Fragment occurrences are observed

interface_residues_by_interface_unique property

interface_residues_by_interface_unique: dict[int, list[Residue]]

Keeps the Residue instances grouped by membership to each side of the interface. Residues are unique to one side of the interface Ex: {1: [Residue, ...], 2: [Residue, ...]}

interface_residues_by_interface property

interface_residues_by_interface: dict[int, list[Residue]]

Keeps the Residue instances grouped by membership to each side of the interface. Residues can be duplicated on each side when interface contains a 2-fold axis of symmetry Ex: {1: [Residue, ...], 2: [Residue, ...]}

fragment_metrics_by_entity_pair property

fragment_metrics_by_entity_pair: dict[tuple[Entity, Entity], dict[str, Any]]

Returns the metrics from structural overlapping Fragment observations between pairs of Entity instances

calculate_metrics

calculate_metrics(**kwargs) -> dict[str, Any]

Calculate metrics for the instance

Returns:

  • dict[str, Any]

    { 'entity_max_radius_average_deviation', 'entity_min_radius_average_deviation', 'entity_radius_average_deviation', 'interface_b_factor', 'interface1_secondary_structure_fragment_topology', 'interface1_secondary_structure_fragment_count', 'interface1_secondary_structure_topology', 'interface1_secondary_structure_count', 'interface2_secondary_structure_fragment_topology', 'interface2_secondary_structure_fragment_count', 'interface2_secondary_structure_topology', 'interface2_secondary_structure_count', 'maximum_radius', 'minimum_radius', 'multiple_fragment_ratio', 'nanohedra_score_normalized', 'nanohedra_score_center_normalized', 'nanohedra_score', 'nanohedra_score_center', 'number_residues_interface_fragment_total', 'number_residues_interface_fragment_center', 'number_fragments_interface', 'number_residues_interface', 'number_residues_interface_non_fragment', 'percent_fragment_helix', 'percent_fragment_strand', 'percent_fragment_coil', 'percent_residues_fragment_interface_total', 'percent_residues_fragment_interface_center', 'percent_residues_non_fragment_interface', 'pose_length', 'symmetric_interface'

  • dict[str, Any]

    }

Source code in symdesign/structure/model.py
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
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
5841
5842
5843
def calculate_metrics(self, **kwargs) -> dict[str, Any]:
    """Calculate metrics for the instance

    Returns:
        {
            'entity_max_radius_average_deviation',
            'entity_min_radius_average_deviation',
            'entity_radius_average_deviation',
            'interface_b_factor',
            'interface1_secondary_structure_fragment_topology',
            'interface1_secondary_structure_fragment_count',
            'interface1_secondary_structure_topology',
            'interface1_secondary_structure_count',
            'interface2_secondary_structure_fragment_topology',
            'interface2_secondary_structure_fragment_count',
            'interface2_secondary_structure_topology',
            'interface2_secondary_structure_count',
            'maximum_radius',
            'minimum_radius',
            'multiple_fragment_ratio',
            'nanohedra_score_normalized',
            'nanohedra_score_center_normalized',
            'nanohedra_score',
            'nanohedra_score_center',
            'number_residues_interface_fragment_total',
            'number_residues_interface_fragment_center',
            'number_fragments_interface',
            'number_residues_interface',
            'number_residues_interface_non_fragment',
            'percent_fragment_helix',
            'percent_fragment_strand',
            'percent_fragment_coil',
            'percent_residues_fragment_interface_total',
            'percent_residues_fragment_interface_center',
            'percent_residues_non_fragment_interface',
            'pose_length',
            'symmetric_interface'
        }
    """
    minimum_radius, maximum_radius = float('inf'), 0.
    entity_metrics = []
    reference_com = self.center_of_mass_symmetric
    for entity in self.entities:
        # _entity_metrics = entity.calculate_metrics()
        _entity_metrics = entity.calculate_spatial_orientation_metrics(reference=reference_com)

        if _entity_metrics['min_radius'] < minimum_radius:
            minimum_radius = _entity_metrics['min_radius']
        if _entity_metrics['max_radius'] > maximum_radius:
            maximum_radius = _entity_metrics['max_radius']
        entity_metrics.append(_entity_metrics)

    pose_metrics = {'minimum_radius': minimum_radius,
                    'maximum_radius': maximum_radius,
                    'pose_length': self.number_of_residues
                    # 'sequence': self.sequence
                    }
    radius_ratio_sum = min_ratio_sum = max_ratio_sum = 0.  # residue_ratio_sum
    counter = 1
    # index_combinations = combinations(range(1, 1 + len(entity_metrics)), 2)
    for counter, (metrics1, metrics2) in enumerate(combinations(entity_metrics, 2), counter):
        if metrics1['radius'] > metrics2['radius']:
            radius_ratio = metrics2['radius'] / metrics1['radius']
        else:
            radius_ratio = metrics1['radius'] / metrics2['radius']

        if metrics1['min_radius'] > metrics2['min_radius']:
            min_ratio = metrics2['min_radius'] / metrics1['min_radius']
        else:
            min_ratio = metrics1['min_radius'] / metrics2['min_radius']

        if metrics1['max_radius'] > metrics2['max_radius']:
            max_ratio = metrics2['max_radius'] / metrics1['max_radius']
        else:
            max_ratio = metrics1['max_radius'] / metrics2['max_radius']

        radius_ratio_sum += 1 - radius_ratio
        min_ratio_sum += 1 - min_ratio
        max_ratio_sum += 1 - max_ratio
        # residue_ratio_sum += abs(1 - residue_ratio)
        # entity_idx1, entity_idx2 = next(index_combinations)
        # pose_metrics.update({f'entity_radius_ratio_{entity_idx1}v{entity_idx2}': radius_ratio,
        #                      f'entity_min_radius_ratio_{entity_idx1}v{entity_idx2}': min_ratio,
        #                      f'entity_max_radius_ratio_{entity_idx1}v{entity_idx2}': max_ratio,
        #                      f'entity_number_of_residues_ratio_{entity_idx1}v{entity_idx2}': residue_ratio})

    pose_metrics.update({'entity_radius_average_deviation': radius_ratio_sum / counter,
                         'entity_min_radius_average_deviation': min_ratio_sum / counter,
                         'entity_max_radius_average_deviation': max_ratio_sum / counter,
                         # 'entity_number_of_residues_average_deviation': residue_ratio_sum / counter
                         })
    pose_metrics.update(**self.interface_metrics())

    return pose_metrics

apply_design_selector

apply_design_selector(selection: StructureSpecification = None, mask: StructureSpecification = None, required: StructureSpecification = None)

Set up a design selector for the Pose including selections, masks, and required Entities and Atoms

Sets

self._design_selection_entity_names set[str] self._design_selector_atom_indices set[int] self._required_atom_indices Sequence[int]

Source code in symdesign/structure/model.py
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
def apply_design_selector(self, selection: StructureSpecification = None, mask: StructureSpecification = None,
                          required: StructureSpecification = None):
    """Set up a design selector for the Pose including selections, masks, and required Entities and Atoms

    Sets:
        self._design_selection_entity_names set[str]
        self._design_selector_atom_indices set[int]
        self._required_atom_indices Sequence[int]
    """

    def grab_indices(entities: set[str] = None, chains: set[str] = None, residues: set[int] = None) \
            -> tuple[set[str], set[int]]:
        # atoms: set[int] = None
        """Parses the residue selector to a set of entities and a set of atom indices

        Args:
            entities: The Entity identifiers to include in selection schemes
            chains: The Chain identifiers to include in selection schemes
            residues: The Residue identifiers to include in selection schemes

        Returns:
            A tuple with the names of Entity instances and the indices of the Atom/Coord instances that are parsed
        """
        # if start_with_none:
        #     set_function = set.union
        # else:  # Start with all indices and include those of interest
        #     set_function = set.intersection

        entity_atom_indices = []
        entities_of_interest = []
        # All selectors could be a set() or None.
        if entities:
            for entity_name in entities:
                entity = self.get_entity(entity_name)
                if entity is None:
                    raise NameError(
                        f"No entity named '{entity_name}'")
                entities_of_interest.append(entity)
                entity_atom_indices.extend(entity.atom_indices)

        if chains:
            for chain_id in chains:
                chain = self.get_chain(chain_id)
                if chain is None:
                    raise NameError(
                        f"No chain named '{chain_id}'")
                entities_of_interest.append(chain.entity)
                entity_atom_indices.extend(chain.atom_indices)

        # vv This is for the additive model
        # atom_indices.union(iter_chain.from_iterable(self.chain(chain_id).get_residue_atom_indices(numbers=residues)
        #                                     for chain_id in chains))
        # vv This is for the intersectional model
        # atom_indices = set_function(atom_indices, entity_atom_indices)
        # entity_set = set_function(entity_set, [ent.name for ent in entities_of_interest])
        atom_indices = set(entity_atom_indices)
        entity_set = {ent.name for ent in entities_of_interest}

        if residues:
            atom_indices = atom_indices.union(self.get_residue_atom_indices(numbers=residues))
        # if pdb_residues:
        #     atom_indices = set_function(atom_indices, self.get_residue_atom_indices(numbers=residues, pdb=True))
        # if atoms:
        #     atom_indices = set_function(atom_indices, [idx for idx in self._atom_indices if idx in atoms])

        return entity_set, atom_indices

    if selection:
        self.log.debug(f"The 'design_selector' {selection=}")
        entity_selection, atom_selection = grab_indices(**selection)
    else:  # Use existing entities and indices
        entity_selection = self._design_selection_entity_names
        atom_selection = self._design_selector_atom_indices

    if mask:
        self.log.debug(f"The 'design_selector' {mask=}")
        entity_mask, atom_mask = grab_indices(**mask)  # , start_with_none=True)
    else:
        entity_mask = set()
        atom_mask = set()

    entity_selection = entity_selection.difference(entity_mask)
    atom_selection = atom_selection.difference(atom_mask)

    if required:
        self.log.debug(f"The 'design_selector' {required=}")
        entity_required, required_atom_indices = grab_indices(**required)  # , start_with_none=True)
        self._required_atom_indices = list(required_atom_indices)
    else:
        entity_required = set()

    self._design_selection_entity_names = entity_selection.union(entity_required)
    self._design_selector_atom_indices = atom_selection.union(self._required_atom_indices)

    self.log.debug(f'Entities: {", ".join(entity.name for entity in self.entities)}')
    self.log.debug(f'Active Entities: {", ".join(name for name in self._design_selection_entity_names)}')

get_alphafold_features

get_alphafold_features(symmetric: bool = False, multimer: bool = False, **kwargs) -> FeatureDict

Retrieve the required feature dictionary for this instance to use in Alphafold inference

Parameters:

  • symmetric (bool, default: False ) –

    Whether the symmetric version of the Pose should be used for feature production

  • multimer (bool, default: False ) –

    Whether to run as a multimer. If multimer is True while symmetric is False, the Pose will be processed according to the ASU

Other Parameters:

  • msas

    Sequence - A sequence of multiple sequence alignments if they should be included in the features

  • no_msa

    bool = False - Whether multiple sequence alignments should be included in the features

Returns:

  • FeatureDict

    The alphafold FeatureDict which is essentially a dictionary with dict[str, np.ndarray]

Source code in symdesign/structure/model.py
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
def get_alphafold_features(
        self, symmetric: bool = False, multimer: bool = False, **kwargs
) -> FeatureDict:
    """Retrieve the required feature dictionary for this instance to use in Alphafold inference

    Args:
        symmetric: Whether the symmetric version of the Pose should be used for feature production
        multimer: Whether to run as a multimer. If multimer is True while symmetric is False, the Pose will
            be processed according to the ASU

    Keyword Args:
        msas: Sequence - A sequence of multiple sequence alignments if they should be included in the features
        no_msa: bool = False - Whether multiple sequence alignments should be included in the features

    Returns:
        The alphafold FeatureDict which is essentially a dictionary with dict[str, np.ndarray]
    """
    # heteromer = heteromer or self.number_of_entities > 1
    # symmetric = symmetric or heteromer or self.number_of_chains > 1
    # if multimer:

    # Set up the ASU unless otherwise specified
    number_of_symmetry_mates = 1
    if self.is_symmetric():
        if symmetric:
            number_of_symmetry_mates = self.number_of_symmetry_mates
            multimer = True
    # else:
    #     self.log.warning("Can't run as symmetric since Pose isn't symmetric")

    if self.number_of_entities > 1:
        # self.log.warning(f"Can't run with symmetric=True while multimer=False on a {self.__class__.__name__}. "
        #                  f"Setting heteromer=True")
        heteromer = multimer = True
    else:
        heteromer = False
        # if self.number_of_chains > 1:
        #     multimer = True
        # raise ValueError(f"Can't run monomer when {self.number_of_entities} entities are present in the "
        #                  f"{self.__class__.__name__}. Use Entity.{Entity.get_alphafold_features.__name__} on "
        #                  f"each entity individually instead")

    chain_count = count(1)
    all_chain_features = {}
    available_chain_ids = list(chain_id_generator())[:self.number_of_entities * self.number_of_symmetry_mates]
    available_chain_ids_iter = iter(available_chain_ids)
    for entity_idx, entity in enumerate(self.entities):
        entity_features = entity.get_alphafold_features(heteromer=heteromer, **kwargs)  # no_msa=no_msa)
        # The above function creates most of the work for the adaptation
        # particular importance needs to be given to the MSA used.
        # Should fragments be utilized in the MSA? If so, naming them in some way to pair is required!
        # Follow the example in:
        #    af_pipeline.make_msa_features(msas: Sequence[af_data_parsers.Msa]) -> FeatureDict
        # to featurize

        if multimer:  # symmetric:
            # The chain_id passed to this function is used by the entity_features to (maybe) tie different chains
            # to this chain. In alphafold implementation, the chain_id passed should be oriented so that each
            # additional entity has the chain_id of the chain number within the entire system.
            # For example, for an A4B4 heteromer with C4 symmetry, the chain_id for entity idx 0 would be A and for
            # entity idx 1 would be E. This may not be important, but this is how symmetric is prepared
            chain_id = available_chain_ids[self.number_of_symmetry_mates * entity_idx]
            entity_features = af_pipeline_multimer.convert_monomer_features(entity_features, chain_id=chain_id)

            entity_integer = entity_idx + 1
            entity_id = af_pipeline_multimer.int_id_to_str_id(entity_integer)

        entity_length = entity.number_of_residues
        # for _ in range(self.number_of_symmetry_mates):
        for sym_idx in range(1, 1 + number_of_symmetry_mates):
            # chain_id = next(available_chain_ids_iter)  # The mmCIF formatted chainID with 'AB' type notation
            this_entity_features = deepcopy(entity_features)
            # Where chain_id increments for each new chain instance i.e. A_1 is 1, A_2 is 2, ...
            # Where entity_id increments for each new Entity instance i.e. A_1 is 1, A_2 is 1, ...
            # Where sym_id increments for each new Entity instance regardless of chain i.e. A_1 is 1, A_2 is 2, ...,
            # B_1 is 1, B2 is 2
            if multimer:  # symmetric:
                this_entity_features.update({'asym_id': next(chain_count) * np.ones(entity_length),
                                             'sym_id': sym_idx * np.ones(entity_length),
                                             'entity_id': entity_integer * np.ones(entity_length)})
                chain_name = f'{entity_id}_{sym_idx}'
            else:
                chain_name = next(available_chain_ids_iter)
            # Make the key '<seq_id>_<sym_id>' where seq_id is the chain name assigned to the Entity where
            # chain names increment according to reverse spreadsheet style i.e. A,B,...AA,BA,...
            # and sym_id increments from 1 to number_of_symmetry_mates
            all_chain_features[chain_name] = this_entity_features
            # all_chain_features[next(available_chain_ids_iter)] = this_entity_features
            # all_chain_features[next(available_chain_ids_iter)] = this_entity_features
            # NOT HERE chain_features = convert_monomer_features(copy.deepcopy(entity_features), chain_id=chain_id)
            # all_chain_features[chain_id] = chain_features

    # This v performed above during all_chain_features creation
    # all_chain_features = \
    #     af_pipeline_multimer.add_assembly_features(all_chain_features)

    if multimer:  # symmetric:
        all_chain_features = af_feature_processing.pair_and_merge(all_chain_features=all_chain_features)
        # Pad MSA to avoid zero-sized extra_msa.
        all_chain_features = af_pipeline_multimer.pad_msa(all_chain_features, 512)

    return all_chain_features

get_proteinmpnn_params

get_proteinmpnn_params(ca_only: bool = False, pssm_bias_flag: bool = False, pssm_multi: float = 0.0, bias_pssm_by_probabilities: bool = False, pssm_log_odds_flag: bool = False, interface: bool = False, neighbors: bool = False, **kwargs) -> dict[str, ndarray]

Parameters:

  • ca_only (bool, default: False ) –

    Whether a minimal CA variant of the protein should be used for design calculations

  • pssm_bias_flag (bool, default: False ) –

    Whether to use bias to modulate the residue probabilities designed

  • pssm_multi (float, default: 0.0 ) –

    How much to skew the design probabilities towards the sequence profile. Bounded between [0, 1] where 0 is no sequence profile probability. Only used with pssm_bias_flag and modifies each coefficient in pssm_coef by the fractional amount

  • bias_pssm_by_probabilities (bool, default: False ) –

    Whether to produce bias by profile probabilities as opposed to lods

  • pssm_log_odds_flag (bool, default: False ) –

    Whether to use log_odds threshold (>0) to limit amino acid types of designed residues Creates pssm_log_odds_mask based on the threshold

  • interface (bool, default: False ) –

    Whether to design the interface

  • neighbors (bool, default: False ) –

    Whether to design interface neighbors

Other Parameters:

  • distance

    float = 8. - The distance to measure Residues across an interface

Returns:

  • dict[str, ndarray]

    A mapping of the ProteinMPNN parameter names to their data, typically arrays

Source code in symdesign/structure/model.py
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
def get_proteinmpnn_params(self, ca_only: bool = False, pssm_bias_flag: bool = False, pssm_multi: float = 0.,
                           bias_pssm_by_probabilities: bool = False, pssm_log_odds_flag: bool = False,
                           interface: bool = False, neighbors: bool = False, **kwargs) -> dict[str, np.ndarray]:
    # decode_core_first: bool = False
    """

    Args:
        ca_only: Whether a minimal CA variant of the protein should be used for design calculations
        pssm_bias_flag: Whether to use bias to modulate the residue probabilities designed
        pssm_multi: How much to skew the design probabilities towards the sequence profile.
            Bounded between [0, 1] where 0 is no sequence profile probability.
            Only used with pssm_bias_flag and modifies each coefficient in pssm_coef by the fractional amount
        bias_pssm_by_probabilities: Whether to produce bias by profile probabilities as opposed to lods
        pssm_log_odds_flag: Whether to use log_odds threshold (>0) to limit amino acid types of designed residues
            Creates pssm_log_odds_mask based on the threshold
        interface: Whether to design the interface
        neighbors: Whether to design interface neighbors

    Keyword Args:
        distance: float = 8. - The distance to measure Residues across an interface

    Returns:
        A mapping of the ProteinMPNN parameter names to their data, typically arrays
    """
    #   decode_core_first: Whether to decode the interface core first
    # Initialize pose data structures for design
    number_of_residues = self.number_of_residues
    if interface:
        self.find_and_split_interface(**kwargs)

        # Add all interface + required residues
        self.design_residues = self.required_residues + self.interface_residues
        if neighbors:
            self.design_residues += self.interface_neighbor_residues

        design_indices = [residue.index for residue in self.design_residues]
    else:
        self.design_residues = self.residues
        design_indices = list(range(number_of_residues))

    if ca_only:  # self.job.design.ca_only:
        coords_type = 'ca_coords'
        num_model_residues = 1
    else:
        coords_type = 'backbone_coords'
        num_model_residues = 4

    # Make masks for the sequence design task
    # Residue position mask denotes which residues should be designed. 1 - designed, 0 - known
    residue_mask = np.zeros(number_of_residues, dtype=np.int32)  # (number_of_residues,)
    residue_mask[design_indices] = 1

    omit_AAs_np = np.zeros(ml.mpnn_alphabet_length, dtype=np.int32)  # (alphabet_length,)
    bias_AAs_np = np.zeros_like(omit_AAs_np)  # (alphabet_length,)
    omit_AA_mask = np.zeros((number_of_residues, ml.mpnn_alphabet_length),
                            dtype=np.int32)  # (number_of_residues, alphabet_length)
    bias_by_res = np.zeros(omit_AA_mask.shape, dtype=np.float32)  # (number_of_residues, alphabet_length)

    # Get sequence profile to include for design bias
    pssm_threshold = 0.  # Must be a greater probability than wild-type
    pssm_log_odds = pssm_as_array(self.profile, lod=True)  # (number_of_residues, 20)
    pssm_log_odds_mask = np.where(pssm_log_odds >= pssm_threshold, 1., 0.)  # (number_of_residues, 20)
    pssm_coef = np.ones(residue_mask.shape, dtype=np.float32)  # (number_of_residues,)
    # shape (1, 21) where last index (20) is 1

    # Make the pssm_bias between 0 and 1 specifying how important position is where 1 is more important
    if bias_pssm_by_probabilities:
        pssm_probability = pssm_as_array(self.profile)
        pssm_bias = softmax(pssm_probability)  # (number_of_residues, 20)
    else:
        pssm_bias = softmax(pssm_log_odds)  # (number_of_residues, 20)

    if self.is_symmetric():
        number_of_symmetry_mates = self.number_of_symmetry_mates
        number_of_sym_residues = number_of_residues * number_of_symmetry_mates
        X = self.return_symmetric_coords(getattr(self, coords_type))
        # Should be N, CA, C, O for each residue
        #  v - Residue
        # [[[N  [x, y, z],
        #   [CA [x, y, z],
        #   [C  [x, y, z],
        #   [O  [x, y, z]],
        #  [[], ...      ]]
        # split the coordinates into those grouped by residues
        # X = np.array(.split(X, self.number_of_residues))
        X = X.reshape((number_of_sym_residues, num_model_residues, 3))  # (number_of_sym_residues, 4, 3)

        S = np.tile(self.sequence_numeric, number_of_symmetry_mates)  # (number_of_sym_residues,)
        # self.log.info(f'self.sequence_numeric: {self.sequence_numeric}')
        # self.log.info(f'Tiled sequence_numeric.shape: {S.shape}')
        # self.log.info(f'Tiled sequence_numeric start: {S[:5]}')
        # self.log.info(f'Tiled sequence_numeric chain_break: '
        #               f'{S[number_of_residues-5: number_of_residues+5]}')

        # Make masks for the sequence design task
        residue_mask = np.tile(residue_mask, number_of_symmetry_mates)  # (number_of_sym_residues,)
        mask = np.ones_like(residue_mask)  # (number_of_sym_residues,)
        # Chain mask denotes which chains should be designed. 1 - designed, 0 - known
        # For symmetric systems, treat each chain as designed as the logits are averaged during model.tied_sample()
        chain_mask = np.ones_like(residue_mask)  # (number_of_sym_residues,)
        # Set up a simple array where each residue index has the index of the chain starting with the index of 1
        chain_encoding = np.zeros_like(residue_mask)  # (number_of_residues,)
        # Set up an array where each residue index is incremented, however each chain break has an increment of 100
        residue_idx = np.arange(number_of_sym_residues, dtype=np.int32)  # (number_of_residues,)
        number_of_entities = self.number_of_entities
        for model_idx in range(number_of_symmetry_mates):
            model_offset = model_idx * number_of_residues
            model_entity_number = model_idx * number_of_entities
            for idx, entity in enumerate(self.entities, 1):
                entity_number_of_residues = entity.number_of_residues
                entity_start = entity.offset_index + model_offset
                chain_encoding[entity_start:entity_start + entity_number_of_residues] = model_entity_number + idx
                residue_idx[entity_start:entity_start + entity_number_of_residues] += \
                    (model_entity_number+idx) * 100

        # self.log.debug(f'Tiled chain_encoding chain_break: '
        #                f'{chain_encoding[number_of_residues-5: number_of_residues+5]}')
        # self.log.debug(f'Tiled residue_idx chain_break: '
        #                f'{residue_idx[number_of_residues-5: number_of_residues+5]}')

        pssm_coef = np.tile(pssm_coef, number_of_symmetry_mates)  # (number_of_sym_residues,)
        # Below have shape (number_of_sym_residues, alphabet_length)
        pssm_bias = np.tile(pssm_bias, (number_of_symmetry_mates, 1))
        pssm_log_odds_mask = np.tile(pssm_log_odds_mask, (number_of_symmetry_mates, 1))
        omit_AA_mask = np.tile(omit_AA_mask, (number_of_symmetry_mates, 1))
        bias_by_res = np.tile(bias_by_res, (number_of_symmetry_mates, 1))
        self.log.debug(f'Tiled bias_by_res start: {bias_by_res[:5]}')
        self.log.debug(f'Tiled bias_by_res: '
                       f'{bias_by_res[number_of_residues-5: number_of_residues+5]}')
        tied_beta = np.ones_like(residue_mask)  # (number_of_sym_residues,)
        tied_pos = [self.make_indices_symmetric([idx], dtype='residue') for idx in design_indices]
        # (design_residues, number_of_symmetry_mates)
    else:
        X = getattr(self, coords_type).reshape((number_of_residues, num_model_residues, 3))  # (residues, 4, 3)
        S = self.sequence_numeric  # (number_of_residues,)
        mask = np.ones_like(residue_mask)  # (number_of_residues,)
        chain_mask = np.ones_like(residue_mask)  # (number_of_residues,)
        # Set up a simple array where each residue index has the index of the chain starting with the index of 1
        chain_encoding = np.zeros_like(residue_mask)  # (number_of_residues,)
        # Set up an array where each residue index is incremented, however each chain break has an increment of 100
        residue_idx = np.arange(number_of_residues, dtype=np.int32)  # (number_of_residues,)
        for idx, entity in enumerate(self.entities):
            entity_number_of_residues = entity.number_of_residues
            entity_start = entity.offset_index
            chain_encoding[entity_start: entity_start + entity_number_of_residues] = idx + 1
            residue_idx[entity_start: entity_start + entity_number_of_residues] += idx * 100
        tied_beta = None  # np.ones_like(residue_mask)  # (number_of_sym_residues,)
        tied_pos = None  # [[]]

    return dict(X=X,
                S=S,
                chain_mask=chain_mask,
                chain_encoding=chain_encoding,
                residue_idx=residue_idx,
                mask=mask,
                omit_AAs_np=omit_AAs_np,
                bias_AAs_np=bias_AAs_np,
                chain_M_pos=residue_mask,
                omit_AA_mask=omit_AA_mask,
                pssm_coef=pssm_coef,
                pssm_bias=pssm_bias,
                pssm_multi=pssm_multi,
                pssm_log_odds_flag=pssm_log_odds_flag,
                pssm_log_odds_mask=pssm_log_odds_mask,
                pssm_bias_flag=pssm_bias_flag,
                tied_pos=tied_pos,
                tied_beta=tied_beta,
                bias_by_res=bias_by_res
                )

generate_proteinmpnn_decode_order

generate_proteinmpnn_decode_order(to_device: str = None, core_first: bool = False, **kwargs) -> Tensor | ndarray

Return the decoding order for ProteinMPNN. Currently just returns an array of random floats

For original ProteinMPNN GitHub release, the decoding order is only dependent on first entry in batch for model.tied_sample() while it is dependent on the entire batch for model.sample()

Parameters:

  • to_device (str, default: None ) –

    Whether the decoding order should be transferred to the device that a ProteinMPNN model is on

  • core_first (bool, default: False ) –

    Whether the core residues (identified as fragment pairs) should be decoded first

Returns:

  • Tensor | ndarray

    The decoding order to be used in ProteinMPNN graph decoding

Source code in symdesign/structure/model.py
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
def generate_proteinmpnn_decode_order(self, to_device: str = None, core_first: bool = False, **kwargs) -> \
        torch.Tensor | np.ndarray:
    """Return the decoding order for ProteinMPNN. Currently just returns an array of random floats

    For original ProteinMPNN GitHub release, the decoding order is only dependent on first entry in batch for
    model.tied_sample() while it is dependent on the entire batch for model.sample()

    Args:
        to_device: Whether the decoding order should be transferred to the device that a ProteinMPNN model is on
        core_first: Whether the core residues (identified as fragment pairs) should be decoded first

    Returns:
        The decoding order to be used in ProteinMPNN graph decoding
    """
    pose_length = self.number_of_residues
    if self.is_symmetric():
        pose_length *= self.number_of_symmetry_mates

    if core_first:
        raise NotImplementedError(f'core_first is not available yet')
    else:  # random decoding order
        decode_order = np.random.rand(pose_length)

    if to_device is None:
        return decode_order
    else:
        return torch.from_numpy(decode_order).to(dtype=torch.float32, device=to_device)

get_proteinmpnn_unbound_coords

get_proteinmpnn_unbound_coords(ca_only: bool = False) -> ndarray

Translate the coordinates along z in increments of 1000 to separate coordinates

Parameters:

  • ca_only (bool, default: False ) –

    Whether a minimal CA variant of the protein should be used for design calculations

Returns:

  • ndarray

    The Pose coords where each Entity has been translated away from other entities

Source code in symdesign/structure/model.py
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
def get_proteinmpnn_unbound_coords(self, ca_only: bool = False) -> np.ndarray:
    """Translate the coordinates along z in increments of 1000 to separate coordinates

    Args:
        ca_only: Whether a minimal CA variant of the protein should be used for design calculations

    Returns:
        The Pose coords where each Entity has been translated away from other entities
    """
    if ca_only:
        coords_type = 'ca_coords'
        num_model_residues = 1
    else:
        coords_type = 'backbone_coords'
        num_model_residues = 4

    unbound_transform = np.array([0., 0., 1000.])
    if self.is_symmetric():
        number_of_residues = self.number_of_symmetric_residues
        coord_func = self.return_symmetric_coords
    else:
        number_of_residues = self.number_of_residues
        def coord_func(coords): return coords

    # Caution this doesn't move the oligomeric unit, it moves the ASU entity.
    # "Unbound" measurements shouldn't modify the oligomeric unit
    entity_unbound_coords = []
    for idx, entity in enumerate(self.entities, 1):
        entity_unbound_coords.append(coord_func(getattr(entity, coords_type) + unbound_transform*idx))

    return np.concatenate(entity_unbound_coords).reshape((number_of_residues, num_model_residues, 3))

score_sequences

score_sequences(sequences: Sequence[str] | Sequence[Sequence[str]] | array, method: design_programs_literal = putils.proteinmpnn, measure_unbound: bool = True, ca_only: bool = False, **kwargs) -> dict[str, ndarray]

Analyze the output of sequence design

Parameters:

  • sequences (Sequence[str] | Sequence[Sequence[str]] | array) –

    The sequences to score

  • method (design_programs_literal, default: proteinmpnn ) –

    Whether to score using ProteinMPNN or Rosetta

  • measure_unbound (bool, default: True ) –

    Whether the protein should be scored in the unbound state

  • ca_only (bool, default: False ) –

    Whether a minimal CA variant of the protein should be used for design calculations

Other Parameters:

  • model_name

    The name of the model to use from ProteinMPNN taking the format v_X_Y, where X is neighbor distance and Y is noise

  • backbone_noise

    float = 0.0 - The amount of backbone noise to add to the pose during design

  • pssm_multi

    float = 0.0 - How much to skew the design probabilities towards the sequence profile. Bounded between [0, 1] where 0 is no sequence profile probability. Only used with pssm_bias_flag

  • pssm_log_odds_flag

    bool = False - Whether to use log_odds mask to limit the residues designed

  • pssm_bias_flag

    bool = False - Whether to use bias to modulate the residue probabilites designed

  • bias_pssm_by_probabilities

    Whether to produce bias by profile probabilities as opposed to profile lods

  • # (interface) –

    Whether to design the interface

  • # (neighbors) –

    Whether to design interface neighbors

  • decode_core_first

    bool = False - Whether to decode identified fragments (constituting the protein core) first

Returns:

  • dict[str, ndarray]

    A mapping of the design score type name to the per-residue output data which is a ndarray with shape

  • dict[str, ndarray]

    (number of sequences, pose_length).

  • dict[str, ndarray]

    For proteinmpnn,

  • dict[str, ndarray]

    these are the outputs: 'sequences', 'numeric_sequences', 'proteinmpnn_loss_complex', and

  • dict[str, ndarray]

    'proteinmpnn_loss_unbound' mapped to their corresponding arrays with data types as np.ndarray

  • dict[str, ndarray]

    For rosetta, this function isn't implemented

Source code in symdesign/structure/model.py
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
@torch.no_grad()  # Ensure no gradients are produced
def score_sequences(self, sequences: Sequence[str] | Sequence[Sequence[str]] | np.array,
                    method: design_programs_literal = putils.proteinmpnn,
                    measure_unbound: bool = True, ca_only: bool = False, **kwargs) -> dict[str, np.ndarray]:
    """Analyze the output of sequence design

    Args:
        sequences: The sequences to score
        method: Whether to score using ProteinMPNN or Rosetta
        measure_unbound: Whether the protein should be scored in the unbound state
        ca_only: Whether a minimal CA variant of the protein should be used for design calculations

    Keyword Args:
        model_name: The name of the model to use from ProteinMPNN taking the format v_X_Y,
            where X is neighbor distance and Y is noise
        backbone_noise: float = 0.0 - The amount of backbone noise to add to the pose during design
        pssm_multi: float = 0.0 - How much to skew the design probabilities towards the sequence profile.
            Bounded between [0, 1] where 0 is no sequence profile probability.
            Only used with pssm_bias_flag
        pssm_log_odds_flag: bool = False - Whether to use log_odds mask to limit the residues designed
        pssm_bias_flag: bool = False - Whether to use bias to modulate the residue probabilites designed
        bias_pssm_by_probabilities: Whether to produce bias by profile probabilities as opposed to profile lods
        # interface: Whether to design the interface
        # neighbors: Whether to design interface neighbors
        decode_core_first: bool = False - Whether to decode identified fragments (constituting the protein core)
            first

    Returns:
        A mapping of the design score type name to the per-residue output data which is a ndarray with shape
        (number of sequences, pose_length).
        For proteinmpnn,
        these are the outputs: 'sequences', 'numeric_sequences', 'proteinmpnn_loss_complex', and
        'proteinmpnn_loss_unbound' mapped to their corresponding arrays with data types as np.ndarray

        For rosetta, this function isn't implemented
    """
    if method == putils.rosetta:
        sequences_and_scores = {}
        raise NotImplementedError(f"Can't score with Rosetta from this method yet...")
    elif method == putils.proteinmpnn:  # Design with vanilla version of ProteinMPNN
        # Convert the sequences to correct format
        # missing_alphabet = ''
        warn_alphabet = 'With passed sequences type of {}, ensure that the order of ' \
                        f'integers is of the default ProteinMPNN alphabet "{ml.mpnn_alphabet}"'

        def convert_and_check_sequence_type(sequences_) -> Sequence[Sequence[str | int]]:
            incorrect_input = ValueError(f'The passed sequences must be an Sequence[Sequence[Any]]')
            nesting_level = count()
            item = sequences_
            # print(item)
            while not isinstance(item, (int, str)):
                next(nesting_level)
                item = item[0]
                # print(item)
            else:
                final_level = next(nesting_level)
                item_type = type(item)
                # print(final_level)
                # print(item_type)
                if final_level == 1:
                    if item_type is str:
                        sequences_ = sequences_to_numeric(
                            sequences, translation_table=ml.proteinmpnn_default_translation_table)
                    else:
                        raise incorrect_input
                elif final_level == 2:
                    if item_type is str:
                        for idx, sequence in enumerate(sequences_):
                            sequences[idx] = ''.join(sequence)

                        sequences_ = sequences_to_numeric(
                            sequences, translation_table=ml.proteinmpnn_default_translation_table)
                    else:
                        self.log.warning(warn_alphabet.format('int'))
                        sequences_ = np.array(sequences_)
                else:
                    raise incorrect_input
                # print('Final', sequences)
            return sequences_

        if isinstance(sequences, (torch.Tensor, np.ndarray)):
            if sequences.dtype in utils.np_torch_int_float_types:
                # This is an integer sequence. An alphabet is required
                self.log.warning(warn_alphabet.format(sequences.dtype))
                numeric_sequences = sequences
                sequences = numeric_to_sequence(sequences)
                # raise ValueError(missing_alphabet)
            else:  # This is an AnyStr type?
                numeric_sequences = sequences_to_numeric(sequences)
        else:  # Some sort of iterable
            numeric_sequences = convert_and_check_sequence_type(sequences)

        # pose_length = self.number_of_residues
        size, pose_length, *_ = numeric_sequences.shape
        batch_length = ml.PROTEINMPNN_SCORE_BATCH_LEN

        # Set up parameters and model sampling type based on symmetry
        if measure_unbound:
            parameters = {'X_unbound': self.get_proteinmpnn_unbound_coords(ca_only=ca_only)}
        else:
            parameters = {}

        # Set up return containers based on the asymmetric sequence
        per_residue_complex_sequence_loss = np.empty_like(numeric_sequences, dtype=np.float32)
        per_residue_unbound_sequence_loss = np.empty_like(per_residue_complex_sequence_loss)

        # Set up parameters for the scoring task, including scoring all positions
        parameters.update(**self.get_proteinmpnn_params(ca_only=ca_only, **kwargs))

        # Remove the precalculated sequence array to add our own
        parameters.pop('S')
        # # Insert the designed sequences inplace of the pose sequence
        # parameters['S'] = np.tile(numeric_sequences, (1, number_of_symmetry_mates))
        # Set up for symmetry
        numeric_sequences_ = np.tile(numeric_sequences, (1, self.number_of_symmetry_mates))
        # Solve decoding order
        # parameters['randn'] = self.generate_proteinmpnn_decode_order(**kwargs)  # to_device=device)
        # decoding_order = self.generate_proteinmpnn_decode_order(**kwargs)  # to_device=device)
        # Solve decoding order
        parameters['decoding_order'] = self.generate_proteinmpnn_decode_order(**kwargs)  # to_device=device)

        @ml.batch_calculation(size=size, batch_length=batch_length,
                              setup=ml.setup_pose_batch_for_proteinmpnn,
                              compute_failure_exceptions=(RuntimeError,
                                                          np.core._exceptions._ArrayMemoryError))
        def _proteinmpnn_batch_score(*args, **_kwargs):
            return ml.proteinmpnn_batch_score(*args, **_kwargs)

        # Set up the model with the desired weights
        proteinmpnn_model = ml.proteinmpnn_factory(ca_only=ca_only, **kwargs)
        device = proteinmpnn_model.device

        # Send the numpy array to torch.tensor and the device
        # Pass sequences as 'S' parameter to _proteinmpnn_batch_score instead of as setup_kwargs
        # unique_parameters = ml.proteinmpnn_to_device(device, S=sequences, decoding_order=decoding_order)
        unique_parameters = ml.proteinmpnn_to_device(device, S=numeric_sequences_)
        # score_start = time.time()
        scores = \
            _proteinmpnn_batch_score(proteinmpnn_model, **unique_parameters,  # S=sequences,
                                     pose_length=pose_length,  # decoding_order=decoding_order,
                                     setup_args=(device,),
                                     setup_kwargs=parameters,
                                     return_containers={
                                         'proteinmpnn_loss_complex': per_residue_complex_sequence_loss,
                                         'proteinmpnn_loss_unbound': per_residue_unbound_sequence_loss})
        sequences_and_scores = {'sequences': sequences,
                                'numeric_sequences': numeric_sequences,
                                **scores}
    else:
        sequences_and_scores = {}
        raise ValueError(
            f"The method '{method}' isn't a viable scoring protocol")

    return sequences_and_scores

design_sequences

design_sequences(method: design_programs_literal = putils.proteinmpnn, number: int = 10, temperatures: Sequence[float] = (0.1), interface: bool = False, neighbors: bool = False, measure_unbound: bool = True, ca_only: bool = False, **kwargs) -> dict[str, ndarray]

Perform sequence design on the Pose

Parameters:

  • method (design_programs_literal, default: proteinmpnn ) –

    Whether to design using ProteinMPNN or Rosetta

  • number (int, default: 10 ) –

    The number of sequences to design

  • temperatures (Sequence[float], default: (0.1) ) –

    The temperatures to perform design at

  • interface (bool, default: False ) –

    Whether to design the interface

  • neighbors (bool, default: False ) –

    Whether to design interface neighbors

  • measure_unbound (bool, default: True ) –

    Whether the protein should be designed with concern for the unbound state

  • ca_only (bool, default: False ) –

    Whether a minimal CA variant of the protein should be used for design calculations

Other Parameters:

  • neighbors (bool) –

    bool = False - Whether to design interface neighbors

  • model_name

    The name of the model to use from ProteinMPNN taking the format v_X_Y, where X is neighbor distance and Y is noise

  • backbone_noise

    float = 0.0 - The amount of backbone noise to add to the pose during design

  • pssm_multi

    float = 0.0 - How much to skew the design probabilities towards the sequence profile. Bounded between [0, 1] where 0 is no sequence profile probability. Only used with pssm_bias_flag

  • pssm_log_odds_flag

    bool = False - Whether to use log_odds mask to limit the residues designed

  • pssm_bias_flag

    bool = False - Whether to use bias to modulate the residue probabilites designed

  • bias_pssm_by_probabilities

    Whether to produce bias by profile probabilities as opposed to profile lods

  • decode_core_first

    bool = False - Whether to decode identified fragments (constituting the protein core) first

Returns:

  • dict[str, ndarray]

    A mapping of the design score type to the per-residue output data which is a ndarray with shape

  • dict[str, ndarray]

    (number*temperatures, pose_length).

  • dict[str, ndarray]

    For proteinmpnn,

  • dict[str, ndarray]

    these are the outputs 'sequences', 'numeric_sequences', 'design_indices', 'proteinmpnn_loss_complex', and

  • dict[str, ndarray]

    'proteinmpnn_loss_unbound' mapped to their corresponding score types. For each return array, the return

  • dict[str, ndarray]

    varies such as: [temp1/number1, temp1/number2, ...,

  • dict[str, ndarray]

    tempN/number1, ...] where designs are sorted by temperature

  • dict[str, ndarray]

    For rosetta, this function isn't implemented

Source code in symdesign/structure/model.py
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
@torch.no_grad()  # Ensure no gradients are produced
def design_sequences(self, method: design_programs_literal = putils.proteinmpnn, number: int = 10,
                     temperatures: Sequence[float] = (0.1,), interface: bool = False, neighbors: bool = False,
                     measure_unbound: bool = True, ca_only: bool = False, **kwargs) -> dict[str, np.ndarray]:
    """Perform sequence design on the Pose

    Args:
        method: Whether to design using ProteinMPNN or Rosetta
        number: The number of sequences to design
        temperatures: The temperatures to perform design at
        interface: Whether to design the interface
        neighbors: Whether to design interface neighbors
        measure_unbound: Whether the protein should be designed with concern for the unbound state
        ca_only: Whether a minimal CA variant of the protein should be used for design calculations

    Keyword Args:
        neighbors: bool = False - Whether to design interface neighbors
        model_name: The name of the model to use from ProteinMPNN taking the format v_X_Y,
            where X is neighbor distance and Y is noise
        backbone_noise: float = 0.0 - The amount of backbone noise to add to the pose during design
        pssm_multi: float = 0.0 - How much to skew the design probabilities towards the sequence profile.
            Bounded between [0, 1] where 0 is no sequence profile probability.
            Only used with pssm_bias_flag
        pssm_log_odds_flag: bool = False - Whether to use log_odds mask to limit the residues designed
        pssm_bias_flag: bool = False - Whether to use bias to modulate the residue probabilites designed
        bias_pssm_by_probabilities: Whether to produce bias by profile probabilities as opposed to profile lods
        decode_core_first: bool = False - Whether to decode identified fragments (constituting the protein core)
            first

    Returns:
        A mapping of the design score type to the per-residue output data which is a ndarray with shape
        (number*temperatures, pose_length).
        For proteinmpnn,
        these are the outputs 'sequences', 'numeric_sequences', 'design_indices', 'proteinmpnn_loss_complex', and
        'proteinmpnn_loss_unbound' mapped to their corresponding score types. For each return array, the return
        varies such as: [temp1/number1, temp1/number2, ...,
        tempN/number1, ...] where designs are sorted by temperature

        For rosetta, this function isn't implemented
    """
    # rosetta: Whether to design using Rosetta energy functions
    if method == putils.rosetta:
        sequences_and_scores = {}
        raise NotImplementedError(f"Can't design with Rosetta from this method yet...")
    elif method == putils.proteinmpnn:  # Design with vanilla version of ProteinMPNN
        pose_length = self.number_of_residues
        # Set up parameters and model sampling type based on symmetry
        if self.is_symmetric():
            # number_of_symmetry_mates = pose.number_of_symmetry_mates
            # mpnn_sample = proteinmpnn_model.tied_sample
            number_of_residues = pose_length * self.number_of_symmetry_mates
        else:
            # mpnn_sample = proteinmpnn_model.sample
            number_of_residues = pose_length

        if measure_unbound:
            parameters = {'X_unbound': self.get_proteinmpnn_unbound_coords(ca_only=ca_only)}
        else:
            parameters = {}

        # Set up the inference task
        parameters.update(**self.get_proteinmpnn_params(interface=interface, neighbors=neighbors,
                                                        ca_only=ca_only, **kwargs))
        # Solve decoding order
        parameters['randn'] = self.generate_proteinmpnn_decode_order(**kwargs)  # to_device=device)

        # Set up the model with the desired weights
        size = number
        proteinmpnn_model = ml.proteinmpnn_factory(ca_only=ca_only, **kwargs)
        device = proteinmpnn_model.device
        batch_length = ml.calculate_proteinmpnn_batch_length(proteinmpnn_model, number_of_residues)
        # batch_length = ml.PROTEINMPNN_DESIGN_BATCH_LEN
        logger.info(f'Found ProteinMPNN batch_length={batch_length}')

        generated_sequences = np.empty((size, len(temperatures), pose_length), dtype=np.int64)
        per_residue_complex_sequence_loss = np.empty_like(generated_sequences, dtype=np.float32)
        per_residue_unbound_sequence_loss = np.empty_like(per_residue_complex_sequence_loss)
        design_indices = np.zeros((size, pose_length), dtype=bool)

        @ml.batch_calculation(size=size, batch_length=batch_length,
                              setup=ml.setup_pose_batch_for_proteinmpnn,
                              compute_failure_exceptions=(RuntimeError,
                                                          np.core._exceptions._ArrayMemoryError))
        def _proteinmpnn_batch_design(*args, **_kwargs):
            return ml.proteinmpnn_batch_design(*args, **_kwargs)

        # Data has shape (batch_length, number_of_temperatures, pose_length)
        number_of_temps = len(temperatures)
        # design_start = time.time()
        sequences_and_scores = \
            _proteinmpnn_batch_design(proteinmpnn_model, temperatures=temperatures, pose_length=pose_length,
                                      setup_args=(device,),
                                      setup_kwargs=parameters,
                                      return_containers={
                                          'sequences': generated_sequences,
                                          'proteinmpnn_loss_complex': per_residue_complex_sequence_loss,
                                          'proteinmpnn_loss_unbound': per_residue_unbound_sequence_loss,
                                          'design_indices': design_indices})
        # self.log.debug(f"Took {time.time() - design_start:8f}s for _proteinmpnn_batch_design")

        sequences_and_scores['numeric_sequences'] = sequences_and_scores.pop('sequences')
        sequences_and_scores['sequences'] = numeric_to_sequence(sequences_and_scores['numeric_sequences'])

        # Format returns to have shape (temperatures*size, pose_length) where the temperatures vary slower
        # Ex: [temp1/pose1, temp1/pose2, ..., tempN/pose1, ...] This groups the designs by temperature first
        for data_type, data in sequences_and_scores.items():
            if data_type == 'design_indices':
                # These must vary by temperature
                sequences_and_scores['design_indices'] = np.tile(data, (number_of_temps, 1))
                # self.log.debug(f'Found design_indices with shape: {sequences_and_scores["design_indices"].shape}')
                continue
            # print(f"{data_type} has shape {data.shape}")
            sequences_and_scores[data_type] = np.concatenate(data, axis=1).reshape(-1, pose_length)

        # self.log.debug(f'Found sequences with shape {sequences_and_scores["sequences"].shape}')
        # self.log.debug(f'Found proteinmpnn_loss_complex with shape {sequences_and_scores["proteinmpnn_loss_complex"].shape}')
        # self.log.debug(f'Found proteinmpnn_loss_unbound with shape {sequences_and_scores["proteinmpnn_loss_unbound"].shape}')
    else:
        sequences_and_scores = {}
        raise ValueError(
            f"The method '{method}' isn't a viable design protocol")

    return sequences_and_scores

get_termini_accessibility

get_termini_accessibility(entity: Entity = None, report_if_helix: bool = False) -> dict[str, bool]

Returns a dictionary indicating which termini are not buried. Coarsely locates termini which face outward

Parameters:

  • entity (Entity, default: None ) –

    The Structure to query which originates in the pose

  • report_if_helix (bool, default: False ) –

    Whether the query should additionally report on the helicity of the termini

Returns:

  • dict[str, bool]

    A dictionary with the mapping from termini to True if the termini is exposed Ex: {'n': True, 'c': False}

Source code in symdesign/structure/model.py
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
def get_termini_accessibility(self, entity: Entity = None, report_if_helix: bool = False) -> dict[str, bool]:
    """Returns a dictionary indicating which termini are not buried. Coarsely locates termini which face outward

    Args:
        entity: The Structure to query which originates in the pose
        report_if_helix: Whether the query should additionally report on the helicity of the termini

    Returns:
        A dictionary with the mapping from termini to True if the termini is exposed
            Ex: {'n': True, 'c': False}
    """
    assembly = self.assembly
    if not assembly.sasa:
        assembly.get_sasa()

    # Find the chain that matches the Entity
    for chain in assembly.chains:
        if chain.entity_id == entity.name:
            entity_chain = chain
            break
    else:
        raise DesignError(
            f"Couldn't find a corresponding {repr(assembly)}.chain for the passed entity={repr(entity)}")

    n_term = c_term = False
    entity_reference = None
    if self.is_symmetric():
        if self.dimension > 0:
            self.log.critical("Locating termini accessibility for lattice symmetries hasn't been tested")
            for _entity, entity_transformation in zip(self.entities, self.entity_transformations):
                if entity == _entity:
                    entity_reference = entity_transformation.get('translation2', None)
                    break
            else:
                raise ValueError(
                    f"Can't measure point of reference for entity={repr(entity)} as a matching instance wasn't "
                    f"found in the {repr(self)}")

    if entity.termini_proximity_from_reference(reference=entity_reference) == 1:  # if outward
        if entity_chain.n_terminal_residue.relative_sasa > metrics.default_sasa_burial_threshold:
            n_term = True

    if entity.termini_proximity_from_reference(termini='c', reference=entity_reference) == 1:  # if outward
        if entity_chain.c_terminal_residue.relative_sasa > metrics.default_sasa_burial_threshold:
            c_term = True

    if report_if_helix:
        try:
            retrieve_stride_info = resources.structure_db.structure_database_factory().stride.retrieve_data
        except AttributeError:
            pass
        else:
            parsed_secondary_structure = retrieve_stride_info(name=entity.name)
            if parsed_secondary_structure:
                entity.secondary_structure = parsed_secondary_structure

        n_term = True if n_term and entity.is_termini_helical() else False
        c_term = True if c_term and entity.is_termini_helical(termini='c') else False

    return dict(n=n_term, c=c_term)

per_residue_contact_order

per_residue_contact_order(oligomeric_interfaces: bool = False, **kwargs) -> dict[str, ndarray]

Calculate the contact order separating calculation for chain breaks as would be expected for 3 state folding

Parameters:

  • oligomeric_interfaces (bool, default: False ) –

    Whether to query oligomeric interfaces

Returns:

  • dict[str, ndarray]

    The dictionary of {'contact_order': array of shape (number_of_residues,)}

Source code in symdesign/structure/model.py
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
def per_residue_contact_order(self, oligomeric_interfaces: bool = False, **kwargs) -> dict[str, np.ndarray]:
    """Calculate the contact order separating calculation for chain breaks as would be expected for 3 state folding

    Args:
        oligomeric_interfaces: Whether to query oligomeric interfaces

    Returns:
        The dictionary of {'contact_order': array of shape (number_of_residues,)}
    """
    if oligomeric_interfaces:
        raise NotImplementedError(
            "Need to perform 'oligomeric_interfaces' calculation on the Entity.oligomer")

    contact_order = []
    for idx, entity in enumerate(self.entities):
        contact_order.append(entity.contact_order)

    return {'contact_order': np.concatenate(contact_order)}

get_folding_metrics

get_folding_metrics(profile_type: profile_types = 'evolutionary', **kwargs) -> tuple[ndarray, ndarray, ndarray]

Calculate metrics relating to the Pose folding, separating calculation for chain breaks. These include contact_order, hydrophobic_collapse, and hydrophobic_collapse_profile (each Entity MUST have a .*_profile attribute to return the hydrophobic collapse profile!)

Parameters:

  • profile_type (profile_types, default: 'evolutionary' ) –

    The type of profile to use to calculate the hydrophobic collapse profile

Other Parameters:

  • hydrophobicity

    str = 'standard' – The hydrophobicity scale to consider. Either 'standard' (FILV), 'expanded' (FMILYVW), or provide one with 'custom' keyword argument

  • custom

    mapping[str, float | int] = None – A user defined mapping of amino acid type, hydrophobicity value pairs

  • alphabet_type

    alphabet_types = None – The amino acid alphabet if the sequence consists of integer characters

  • lower_window

    int = 3 – The smallest window used to measure

  • upper_window

    int = 9 – The largest window used to measure

Returns:

  • tuple[ndarray, ndarray, ndarray]

    The per-residue contact_order_z_score (number_of_residues), a per-residue hydrophobic_collapse (number_of_residues), and the hydrophobic_collapse profile (number_of_residues) based on Entity.evolutionary_profile instances

Source code in symdesign/structure/model.py
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
def get_folding_metrics(
    self, profile_type: profile_types = 'evolutionary', **kwargs
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Calculate metrics relating to the Pose folding, separating calculation for chain breaks. These include
    contact_order, hydrophobic_collapse, and hydrophobic_collapse_profile (each Entity MUST have a .*_profile
    attribute to return the hydrophobic collapse profile!)

    Args:
        profile_type: The type of profile to use to calculate the hydrophobic collapse profile

    Keyword Args:
        hydrophobicity: str = 'standard' – The hydrophobicity scale to consider. Either 'standard' (FILV),
            'expanded' (FMILYVW), or provide one with 'custom' keyword argument
        custom: mapping[str, float | int] = None – A user defined mapping of amino acid type, hydrophobicity value
            pairs
        alphabet_type: alphabet_types = None – The amino acid alphabet if the sequence consists of integer
            characters
        lower_window: int = 3 – The smallest window used to measure
        upper_window: int = 9 – The largest window used to measure

    Returns:
        The per-residue contact_order_z_score (number_of_residues),
            a per-residue hydrophobic_collapse (number_of_residues),
            and the hydrophobic_collapse profile (number_of_residues) based on Entity.evolutionary_profile instances
    """
    #       and the hydrophobic_collapse profile (msa.length, msa.number_of_residues) based on Entity.msa instances
    # Measure the wild type (reference) entity versus modified entity(ies) to find the hci delta
    # Calculate Reference sequence statistics
    contact_order_z, hydrophobic_collapse, hydrophobic_collapse_profile = [], [], []
    missing = []
    msa_metrics = True
    for idx, entity in enumerate(self.entities):
        contact_order = entity.contact_order
        # This calculation shouldn't depend on oligomers... Only assumes unfolded -> folded
        # contact_order = entity_oligomer.contact_order[:entity.number_of_residues]
        entity_residue_contact_order_z = metrics.z_score(contact_order, contact_order.mean(), contact_order.std())
        contact_order_z.append(entity_residue_contact_order_z)
        # inverse_residue_contact_order_z.append(entity_residue_contact_order_z * -1)
        hydrophobic_collapse.append(entity.hydrophobic_collapse(**kwargs))

        # Set the entity.msa which makes a copy and adjusts for any disordered residues
        # This method is more accurate as it uses full sequences from MSA. However,
        # more time-consuming and may not matter much
        # if chain.msa and msa_metrics:
        #     hydrophobic_collapse_profile.append(chain.collapse_profile(**kwargs))
        #     collapse = chain.collapse_profile()
        #     entity_collapse_mean.append(collapse.mean(axis=-2))
        #     entity_collapse_std.append(collapse.std(axis=-2))
        #     reference_collapse_z_score.append(utils.z_score(reference_collapse, entity_collapse_mean[idx],
        #                                                     entity_collapse_std[idx]))
        if msa_metrics and entity.evolutionary_profile:
            try:
                profile = getattr(entity, f'{profile_type}_profile')
                if profile_type == 'fragment':
                    profile_array = profile.as_array()
                else:
                    profile_array = pssm_as_array(profile)
            except AttributeError:  # No profile from getattr()
                raise ValueError(
                    f"The profile_type '{profile_type}' isn't available on {type(entity).__name__} {entity.name}")

            hydrophobic_collapse_profile.append(
                metrics.hydrophobic_collapse_index(profile_array, alphabet_type='protein_letters_alph1', **kwargs))
        else:
            missing.append(1)
            msa_metrics = False

    contact_order_z = np.concatenate(contact_order_z)
    hydrophobic_collapse = np.concatenate(hydrophobic_collapse)
    if sum(missing):  # Need to sum as it could be empty from no .entities and then wouldn't collect either
        hydrophobic_collapse_profile = np.empty(0)
        self.log.warning(f'There were missing .evolutionary_profile attributes for {sum(missing)} Entity instances.'
                         f' The collapse_profile will not be captured for the entire {self.__class__.__name__}')
    #     self.log.warning(f'There were missing MultipleSequenceAlignment objects on {sum(missing)} Entity '
    #                      'instances. The collapse_profile will not be captured for the entire '
    #                      f'{self.__class__.__name__}.')
    # else:
    #     # We have to concatenate where the values will be different
    #     # axis=1 is along the residues, so the result should be the length of the pose
    #     # axis=0 will be different for each individual entity, so we pad to the maximum for lesser ones
    #     array_sizes = [array.shape[0] for array in hydrophobic_collapse_profile]
    #     axis0_max_length = max(array_sizes)
    #     # full_hydrophobic_collapse_profile = \
    #     #     np.full((axis0_max_length, self.number_of_residues), np.nan)  # , dtype=np.float32)
    #     for idx, array in enumerate(hydrophobic_collapse_profile):
    #         hydrophobic_collapse_profile[idx] = \
    #             np.pad(array, ((0, axis0_max_length - array_sizes[idx]), (0, 0)), constant_values=np.nan)
    #
    #     hydrophobic_collapse_profile = np.concatenate(hydrophobic_collapse_profile, axis=1)
    else:
        hydrophobic_collapse_profile = np.concatenate(hydrophobic_collapse_profile)

    return contact_order_z, hydrophobic_collapse, hydrophobic_collapse_profile

interface_metrics

interface_metrics() -> dict[str, Any]

Gather all metrics relating to the Pose and the interfaces within the Pose

Calls self.get_fragment_metrics(), self.calculate_secondary_structure()

Returns:

  • dict[str, Any]

    Metrics measured as: { 'entity_max_radius_average_deviation', 'entity_min_radius_average_deviation', 'entity_radius_average_deviation', 'interface_b_factor', 'interface1_secondary_structure_fragment_topology', 'interface1_secondary_structure_fragment_count', 'interface1_secondary_structure_topology', 'interface1_secondary_structure_count', 'interface2_secondary_structure_fragment_topology', 'interface2_secondary_structure_fragment_count', 'interface2_secondary_structure_topology', 'interface2_secondary_structure_count', 'maximum_radius', 'minimum_radius', 'multiple_fragment_ratio', 'nanohedra_score_normalized', 'nanohedra_score_center_normalized', 'nanohedra_score', 'nanohedra_score_center', 'number_residues_interface_fragment_total', 'number_residues_interface_fragment_center', 'number_fragments_interface', 'number_residues_interface', 'number_residues_interface_non_fragment', 'percent_fragment_helix', 'percent_fragment_strand', 'percent_fragment_coil', 'percent_residues_fragment_interface_total', 'percent_residues_fragment_interface_center', 'percent_residues_non_fragment_interface', 'pose_length', 'symmetric_interface'

  • dict[str, Any]

    }

    'entity_radius_ratio_#v#',

    'entity_min_radius_ratio_#v#',

    'entity_max_radius_ratio_#v#',

    'entity_number_of_residues_ratio_#v#',

    'entity_number_of_residues_average_deviation,

Source code in symdesign/structure/model.py
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
def interface_metrics(self) -> dict[str, Any]:
    """Gather all metrics relating to the Pose and the interfaces within the Pose

    Calls self.get_fragment_metrics(), self.calculate_secondary_structure()

    Returns:
        Metrics measured as: {
            'entity_max_radius_average_deviation',
            'entity_min_radius_average_deviation',
            'entity_radius_average_deviation',
            'interface_b_factor',
            'interface1_secondary_structure_fragment_topology',
            'interface1_secondary_structure_fragment_count',
            'interface1_secondary_structure_topology',
            'interface1_secondary_structure_count',
            'interface2_secondary_structure_fragment_topology',
            'interface2_secondary_structure_fragment_count',
            'interface2_secondary_structure_topology',
            'interface2_secondary_structure_count',
            'maximum_radius',
            'minimum_radius',
            'multiple_fragment_ratio',
            'nanohedra_score_normalized',
            'nanohedra_score_center_normalized',
            'nanohedra_score',
            'nanohedra_score_center',
            'number_residues_interface_fragment_total',
            'number_residues_interface_fragment_center',
            'number_fragments_interface',
            'number_residues_interface',
            'number_residues_interface_non_fragment',
            'percent_fragment_helix',
            'percent_fragment_strand',
            'percent_fragment_coil',
            'percent_residues_fragment_interface_total',
            'percent_residues_fragment_interface_center',
            'percent_residues_non_fragment_interface',
            'pose_length',
            'symmetric_interface'
        }
            # 'entity_radius_ratio_#v#',
            # 'entity_min_radius_ratio_#v#',
            # 'entity_max_radius_ratio_#v#',
            # 'entity_number_of_residues_ratio_#v#',
            # 'entity_number_of_residues_average_deviation,
    """
    pose_metrics = self.get_fragment_metrics(total_interface=True)
    # Remove *_indices from further analysis
    interface_fragment_residue_indices = self.interface_fragment_residue_indices = (
        pose_metrics.pop('center_indices', []))
    pose_metrics.pop('total_indices')
    number_residues_fragment_center = pose_metrics.pop('number_residues_fragment_center')
    number_residues_fragment_total = pose_metrics.pop('number_residues_fragment_total')

    interface_residues = self.interface_residues
    number_residues_interface = len(interface_residues)
    number_residues_interface_non_fragment = number_residues_interface - number_residues_fragment_total
    # if number_residues_interface_non_fragment < 0:
    #     raise ValueError(f'Fragment metrics are broken due to "number_residues_interface_non_fragment" > 1')
    # Interface B Factor
    int_b_factor = sum(residue.b_factor for residue in interface_residues)
    try:  # If interface_distance is different from interface query and fragment generation these can be < 0 or > 1
        percent_residues_fragment_interface_center = number_residues_fragment_center / number_residues_interface
        # This value can be more than 1 so not a percent...
        # percent_residues_fragment_interface_total = number_residues_fragment_total / number_residues_interface
        percent_residues_fragment_interface_total = \
            min(number_residues_fragment_total / number_residues_interface, 1)
        percent_interface_residues_non_fragment = number_residues_interface_non_fragment / number_residues_interface
        # if percent_residues_fragment_interface_center > 1:
        #     raise ValueError(f'Fragment metrics are broken due to "percent_residues_fragment_interface_center">1')
        # if percent_interface_residues_non_fragment > 1:
        #     raise ValueError(f'Fragment metrics are broken due to "percent_interface_residues_non_fragment" > 1')
        ave_b_factor = int_b_factor / number_residues_interface
    except ZeroDivisionError:
        self.log.warning(f'{self.name}: No interface residues were found. Is there an interface in your design?')
        ave_b_factor = percent_residues_fragment_interface_center = percent_residues_fragment_interface_total = \
            percent_interface_residues_non_fragment = 0.

    pose_metrics.update({
        'interface_b_factor': ave_b_factor,
        'number_residues_interface': number_residues_interface,
        'number_residues_interface_fragment_center': number_residues_fragment_center,
        'number_residues_interface_fragment_total': number_residues_fragment_total,
        'number_residues_interface_non_fragment': number_residues_interface_non_fragment,
        'percent_residues_non_fragment_interface': percent_interface_residues_non_fragment,
        'percent_residues_fragment_interface_total': percent_residues_fragment_interface_total,
        'percent_residues_fragment_interface_center': percent_residues_fragment_interface_center})

    interface_residues_by_interface_unique = self.interface_residues_by_interface_unique
    if not self.ss_sequence_indices or not self.ss_type_sequence:
        self.calculate_secondary_structure()

    # interface_ss_topology = {}  # {1: 'HHLH', 2: 'HSH'}
    # interface_ss_fragment_topology = {}  # {1: 'HHH', 2: 'HH'}
    ss_type_array = self.ss_type_sequence
    total_interface_ss_topology = total_interface_ss_fragment_topology = ''
    for number, elements in self.split_interface_ss_elements.items():
        # Use unique as 2-fold interfaces 'interface_residues_by_interface_unique' duplicate fragment_elements
        fragment_elements = {
            element for residue, element in zip(interface_residues_by_interface_unique[number], elements)
            if residue.index in interface_fragment_residue_indices}
        # Take the set of elements as there are element repeats if SS is continuous over residues
        interface_ss_topology = ''.join(ss_type_array[element] for element in set(elements))
        interface_ss_fragment_topology = ''.join(ss_type_array[element] for element in fragment_elements)

        pose_metrics[f'interface{number}_secondary_structure_topology'] = interface_ss_topology
        pose_metrics[f'interface{number}_secondary_structure_count'] = len(interface_ss_topology)
        total_interface_ss_topology += interface_ss_topology
        pose_metrics[f'interface{number}_secondary_structure_fragment_topology'] = interface_ss_fragment_topology
        pose_metrics[f'interface{number}_secondary_structure_fragment_count'] = len(interface_ss_fragment_topology)
        total_interface_ss_fragment_topology += interface_ss_fragment_topology

    pose_metrics['interface_secondary_structure_fragment_topology'] = total_interface_ss_fragment_topology
    pose_metrics['interface_secondary_structure_fragment_count'] = len(total_interface_ss_fragment_topology)
    pose_metrics['interface_secondary_structure_topology'] = total_interface_ss_topology
    pose_metrics['interface_secondary_structure_count'] = len(total_interface_ss_topology)

    # Calculate secondary structure percent for the entire interface
    helical_designations = ['H', 'G', 'I']
    strand_designations = ['E', 'B']
    coil_designations = ['C', 'T']
    number_helical_residues = number_strand_residues = number_loop_residues = 0
    for residue in interface_residues:
        if residue.secondary_structure in helical_designations:
            number_helical_residues += 1
        elif residue.secondary_structure in strand_designations:
            number_strand_residues += 1
        elif residue.secondary_structure in coil_designations:
            number_loop_residues += 1

    pose_metrics['percent_interface_helix'] = number_helical_residues / number_residues_interface
    pose_metrics['percent_interface_strand'] = number_strand_residues / number_residues_interface
    pose_metrics['percent_interface_coil'] = number_loop_residues / number_residues_interface
    if self.interface_residues_by_interface == interface_residues_by_interface_unique:
        pose_metrics['symmetric_interface'] = False
    else:
        pose_metrics['symmetric_interface'] = True

    return pose_metrics

per_residue_errat

per_residue_errat() -> dict[str, list[float]]

Return per-residue metrics for the interface surface area

Returns:

  • dict[str, list[float]]

    The dictionary of errat metrics {errat_deviation, } mapped to arrays of shape (number_of_residues,)

Source code in symdesign/structure/model.py
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
def per_residue_errat(self) -> dict[str, list[float]]:
    """Return per-residue metrics for the interface surface area

    Returns:
        The dictionary of errat metrics {errat_deviation, } mapped to arrays of shape (number_of_residues,)
    """
    per_residue_data = {}
    # pose_length = self.number_of_residues
    assembly_minimally_contacting = self.assembly_minimally_contacting
    self.log.debug(f'Starting {repr(self)} Errat')
    errat_start = time.time()
    _, per_residue_errat = assembly_minimally_contacting.errat(out_path=os.devnull)
    self.log.debug(f'Finished Errat, took {time.time() - errat_start:6f} s')
    per_residue_data['errat_deviation'] = per_residue_errat[:self.number_of_residues].tolist()

    return per_residue_data

per_residue_interface_surface_area

per_residue_interface_surface_area() -> dict[str, list[float]]

Return per-residue metrics for the interface surface area

Returns:

  • dict[str, list[float]]

    The dictionary of metrics mapped to arrays of values with shape (number_of_residues,) Metrics include sasa_hydrophobic_complex, sasa_polar_complex, sasa_relative_complex, sasa_hydrophobic_bound, sasa_polar_bound, sasa_relative_bound

Source code in symdesign/structure/model.py
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
def per_residue_interface_surface_area(self) -> dict[str, list[float]]:
    """Return per-residue metrics for the interface surface area

    Returns:
        The dictionary of metrics mapped to arrays of values with shape (number_of_residues,)
            Metrics include sasa_hydrophobic_complex, sasa_polar_complex, sasa_relative_complex,
            sasa_hydrophobic_bound, sasa_polar_bound, sasa_relative_bound
    """
    per_residue_data = {}
    pose_length = self.number_of_residues
    assembly_minimally_contacting = self.assembly_minimally_contacting

    # Perform SASA measurements
    if not assembly_minimally_contacting.sasa:
        assembly_minimally_contacting.get_sasa()
    assembly_asu_residues = assembly_minimally_contacting.residues[:pose_length]
    per_residue_data['sasa_hydrophobic_complex'] = [residue.sasa_apolar for residue in assembly_asu_residues]
    per_residue_data['sasa_polar_complex'] = [residue.sasa_polar for residue in assembly_asu_residues]
    per_residue_data['sasa_relative_complex'] = [residue.relative_sasa for residue in assembly_asu_residues]
    per_residue_sasa_unbound_apolar, per_residue_sasa_unbound_polar, per_residue_sasa_unbound_relative = [], [], []
    for entity in self.entities:
        if not entity.assembly.sasa:
            entity.assembly.get_sasa()
        oligomer_asu_residues = entity.assembly.residues[:entity.number_of_residues]
        per_residue_sasa_unbound_apolar.extend([residue.sasa_apolar for residue in oligomer_asu_residues])
        per_residue_sasa_unbound_polar.extend([residue.sasa_polar for residue in oligomer_asu_residues])
        per_residue_sasa_unbound_relative.extend([residue.relative_sasa for residue in oligomer_asu_residues])

    per_residue_data['sasa_hydrophobic_bound'] = per_residue_sasa_unbound_apolar
    per_residue_data['sasa_polar_bound'] = per_residue_sasa_unbound_polar
    per_residue_data['sasa_relative_bound'] = per_residue_sasa_unbound_relative

    return per_residue_data

per_residue_relative_surface_area

per_residue_relative_surface_area() -> dict[str, ndarray]

Returns the relative solvent accessible surface area (SASA), per residue type compared to ideal three residue peptides, in both the bound (but not repacked) and complex states of the constituent Entity instances

Returns:

  • dict[str, ndarray]

    Mapping of 'sasa_relative_complex' and 'sasa_relative_bound' to array with the per-residue relative SASA

Source code in symdesign/structure/model.py
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
def per_residue_relative_surface_area(self) -> dict[str, np.ndarray]:
    """Returns the relative solvent accessible surface area (SASA), per residue type compared to ideal three residue
    peptides, in both the bound (but not repacked) and complex states of the constituent Entity instances

    Returns:
        Mapping of 'sasa_relative_complex' and 'sasa_relative_bound' to array with the per-residue relative SASA
    """
    pose_length = self.number_of_residues
    assembly_minimally_contacting = self.assembly_minimally_contacting

    # Perform SASA measurements
    if not assembly_minimally_contacting.sasa:
        assembly_minimally_contacting.get_sasa()
    assembly_asu_residues = assembly_minimally_contacting.residues[:pose_length]
    per_residue_relative_sasa_complex = np.array([residue.relative_sasa for residue in assembly_asu_residues])
    per_residue_relative_sasa_unbound = []
    for entity in self.entities:
        if not entity.assembly.sasa:
            entity.assembly.get_sasa()
        oligomer_asu_residues = entity.assembly.residues[:entity.number_of_residues]
        per_residue_relative_sasa_unbound.extend([residue.relative_sasa for residue in oligomer_asu_residues])

    per_residue_relative_sasa_unbound = np.array(per_residue_relative_sasa_unbound)

    return {'sasa_relative_complex': per_residue_relative_sasa_complex,
            'sasa_relative_bound': per_residue_relative_sasa_unbound}

per_residue_buried_surface_area

per_residue_buried_surface_area() -> ndarray

Returns the buried surface area (BSA) as a result of all interfaces between Entity instances

Returns:

  • ndarray

    An array with the per-residue unbound solvent accessible surface area (SASA) minus the SASA of the complex

Source code in symdesign/structure/model.py
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
def per_residue_buried_surface_area(self) -> np.ndarray:
    """Returns the buried surface area (BSA) as a result of all interfaces between Entity instances

    Returns:
        An array with the per-residue unbound solvent accessible surface area (SASA) minus the SASA of the complex
    """
    pose_length = self.number_of_residues
    assembly_minimally_contacting = self.assembly_minimally_contacting

    # Perform SASA measurements
    if not assembly_minimally_contacting.sasa:
        assembly_minimally_contacting.get_sasa()
    assembly_asu_residues = assembly_minimally_contacting.residues[:pose_length]
    per_residue_sasa_complex = np.array([residue.sasa for residue in assembly_asu_residues])
    per_residue_sasa_unbound = []
    for entity in self.entities:
        if not entity.assembly.sasa:
            entity.assembly.get_sasa()
        oligomer_asu_residues = entity.assembly.residues[:entity.number_of_residues]
        per_residue_sasa_unbound.extend([residue.sasa for residue in oligomer_asu_residues])

    per_residue_sasa_unbound = np.array(per_residue_sasa_unbound)

    return per_residue_sasa_unbound - per_residue_sasa_complex

per_residue_spatial_aggregation_propensity

per_residue_spatial_aggregation_propensity(distance: float = 5.0) -> dict[str, list[float]]

Return per-residue spatial_aggregation for the complexed and unbound states. Positive values are more aggregation prone, while negative values are less prone

Parameters:

  • distance (float, default: 5.0 ) –

    The distance in angstroms to measure Atom instances in contact

Returns:

  • dict[str, list[float]]

    The dictionary of metrics mapped to arrays of values with shape (number_of_residues,) Metrics include 'spatial_aggregation_propensity' and 'spatial_aggregation_propensity_unbound'

Source code in symdesign/structure/model.py
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
def per_residue_spatial_aggregation_propensity(self, distance: float = 5.0) -> dict[str, list[float]]:
    """Return per-residue spatial_aggregation for the complexed and unbound states. Positive values are more
    aggregation prone, while negative values are less prone

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

    Returns:
        The dictionary of metrics mapped to arrays of values with shape (number_of_residues,)
            Metrics include 'spatial_aggregation_propensity' and 'spatial_aggregation_propensity_unbound'
    """
    per_residue_sap = {}
    pose_length = self.number_of_residues
    assembly_minimally_contacting = self.assembly_minimally_contacting
    assembly_minimally_contacting.spatial_aggregation_propensity_per_residue(distance=distance)
    assembly_asu_residues = assembly_minimally_contacting.residues[:pose_length]
    per_residue_sap['spatial_aggregation_propensity'] = \
        [residue.spatial_aggregation_propensity for residue in assembly_asu_residues]
    # Calculate sap for each Entity
    per_residue_sap_unbound = []
    for entity in self.entities:
        entity.assembly.spatial_aggregation_propensity_per_residue(distance=distance)
        oligomer_asu_residues = entity.assembly.residues[:entity.number_of_residues]
        # per_residue_sap_unbound.extend(entity.assembly.spatial_aggregation_propensity[:entity.number_of_residues])
        per_residue_sap_unbound.extend(
            [residue.spatial_aggregation_propensity for residue in oligomer_asu_residues])

    per_residue_sap['spatial_aggregation_propensity_unbound'] = per_residue_sap_unbound

    return per_residue_sap

get_interface

get_interface(distance: float = 8.0) -> Model

Provide a view of the Pose interface by generating a Model containing only interface Residues

Parameters:

  • distance (float, default: 8.0 ) –

    The distance across the interface to query for Residue contacts

Returns:

  • Model

    The Structure containing only the Residues in the interface

Source code in symdesign/structure/model.py
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
def get_interface(self, distance: float = 8.) -> Model:
    """Provide a view of the Pose interface by generating a Model containing only interface Residues

    Args:
        distance: The distance across the interface to query for Residue contacts

    Returns:
        The Structure containing only the Residues in the interface
    """
    if not self.is_symmetric():
        raise NotImplementedError('This function has not been properly converted to deal with non-symmetric poses')

    # interface_residues = []
    # interface_core_coords = []
    # for residues1, residues2 in self.interface_residues_by_entity_pair.values():
    #     if not residues1 and not residues2:  # no interface
    #         continue
    #     elif residues1 and not residues2:  # symmetric case
    #         interface_residues.extend(residues1)
    #         # This was useful when not doing the symmetrization below...
    #         # symmetric_residues = []
    #         # for _ in range(number_of_models):
    #         #     symmetric_residues.extend(residues1)
    #         # residues1_coords = np.concatenate([residue.coords for residue in residues1])
    #         # # Add the number of symmetric observed structures to a single new Structure
    #         # symmetric_residue_structure = Chain.from_residues(residues=symmetric_residues)
    #         # # symmetric_residues2_coords = self.return_symmetric_coords(residues1_coords)
    #         # symmetric_residue_structure.replace_coords(self.return_symmetric_coords(residues1_coords))
    #         # # use a single instance of the residue coords to perform a distance query against symmetric coords
    #         # residues_tree = BallTree(residues1_coords)
    #         # symmetric_query = residues_tree.query_radius(symmetric_residue_structure.coords, distance)
    #         # # symmetric_indices = [symmetry_idx for symmetry_idx, asu_contacts in enumerate(symmetric_query)
    #         # #                      if asu_contacts.any()]
    #         # # finally, add all correctly located, asu interface indexed symmetrical residues to the interface
    #         # coords_indexed_residues = symmetric_residue_structure.coords_indexed_residues
    #         # interface_residues.extend(set(coords_indexed_residues[sym_idx]
    #         #                               for sym_idx, asu_contacts in enumerate(symmetric_query)
    #         #                               if asu_contacts.any()))
    #     else:  # non-symmetric case
    #         interface_core_coords.extend([residue.cb_coords for residue in residues1])
    #         interface_core_coords.extend([residue.cb_coords for residue in residues2])
    #         interface_residues.extend(residues1), interface_residues.extend(residues2)

    # return Chain.from_residues(residues=sorted(interface_residues, key=lambda residue: residue.number))
    # interface_symmetry_mates = self.return_symmetric_copies(interface_asu_structure)
    # interface_coords = interface_asu_structure.coords
    # interface_cb_indices = interface_asu_structure.cb_indices
    # print('NUMBER of RESIDUES:', interface_asu_structure.number_of_residues,
    #       '\nNUMBER of CB INDICES', len(interface_cb_indices))
    # residue_number = interface_asu_structure.number_of_residues
    # [interface_asu_structure.cb_indices + (residue_number * model) for model in self.number_of_symmetry_mates]
    # symmetric_cb_indices = np.array([idx + (coords_length * model_num) for model_num in range(number_of_models)
    #                                  for idx in interface_asu_structure.cb_indices])
    # print('Number sym CB INDICES:\n', len(symmetric_cb_indices))
    # From the interface core, find the mean position to seed clustering
    entities_asu_com = self.center_of_mass
    # initial_interface_coords = self.return_symmetric_coords(entities_asu_com)
    initial_interface_coords = self.center_of_mass_symmetric_models
    # initial_interface_coords = self.return_symmetric_coords(np.array(interface_core_coords).mean(axis=0))

    # Get all interface residues and sort to ensure the asu is ordered and entity breaks can be found
    sorted_residues = sorted(self.interface_residues, key=lambda residue: residue.index)
    interface_asu_structure = Structure.from_residues(residues=sorted_residues)  # , chains=False, entities=False)
    # symmetric_cb_indices = self.make_indices_symmetric(interface_asu_structure.cb_indices)
    number_of_models = self.number_of_symmetry_mates
    coords_length = interface_asu_structure.number_of_atoms
    jump_sizes = [coords_length * model_num for model_num in range(number_of_models)]
    symmetric_cb_indices = [idx + jump_size for jump_size in jump_sizes
                            for idx in interface_asu_structure.cb_indices]
    symmetric_interface_coords = self.return_symmetric_coords(interface_asu_structure.coords)
    # index_cluster_labels = KMeans(n_clusters=self.number_of_symmetry_mates).fit_predict(symmetric_interface_coords)
    # symmetric_interface_cb_coords = symmetric_interface_coords[symmetric_cb_indices]
    # print('Number sym CB COORDS:\n', len(symmetric_interface_cb_coords))
    # initial_cluster_indices = [interface_cb_indices[0] + (coords_length * model_number)
    #                            for model_number in range(self.number_of_symmetry_mates)]
    # Fit a KMeans model to the symmetric interface cb coords
    kmeans_cluster_model = \
        KMeans(n_clusters=number_of_models, init=initial_interface_coords, n_init=1) \
        .fit(symmetric_interface_coords[symmetric_cb_indices])
    # kmeans_cluster_model = \
    #     KMeans(n_clusters=self.number_of_symmetry_mates, init=symmetric_interface_coords[initial_cluster_indices],
    #            n_init=1).fit(symmetric_interface_cb_coords)
    # Find the label where the asu is nearest too
    asu_label = kmeans_cluster_model.predict(entities_asu_com[None, :])  # <- add new first axis
    # asu_interface_labels = kmeans_cluster_model.predict(interface_asu_structure.cb_coords)

    # closest_interface_indices = np.where(index_cluster_labels == 0, True, False)
    # [False, False, False, True, True, True, True, True, True, False, False, False, False, False, ...]
    # symmetric_residues = interface_asu_structure.residues * self.number_of_symmetry_mates
    # [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, ...]
    # asu_index = np.median(asu_interface_labels)
    # grab the symmetric indices for a single interface cluster, matching spatial proximity to the asu_index
    # closest_asu_sym_cb_indices = symmetric_cb_indices[index_cluster_labels == asu_index]
    # index_cluster_labels = kmeans_cluster_model.labels_
    closest_asu_sym_cb_indices = \
        np.where(kmeans_cluster_model.labels_ == asu_label, symmetric_cb_indices, 0)
    # # find the cb indices of the closest interface asu
    # closest_asu_cb_indices = closest_asu_sym_cb_indices % coords_length
    # interface_asu_structure.coords_indexed_residues
    # find the model indices of the closest interface asu
    # print('Normal sym CB INDICES\n:', closest_asu_sym_cb_indices)

    # Create an array where each model is along axis=0 and each cb_index is along axis=1
    # The values in the array correspond to the symmetric cb_index if the cb_index is in the ASU
    # or 0 if the index isn't in the ASU
    # In this example the numbers aren't actually cb atom indices, they are cb residue indices...
    # [[ 0,  0, 2, 3, 4,  0, ...],
    #  [10,  0, 0, 0, 0,  0, ...],
    #  [ 0, 21, 0, 0, 0, 25, ...]].sum(axis=0) ->
    # [ 10, 21, 2, 3, 4, 25, ...]
    sym_cb_index_per_cb = closest_asu_sym_cb_indices.reshape((number_of_models, -1)).sum(axis=0)
    # print('FLATTENED CB INDICES to get MODEL\n:', sym_cb_index_per_cb)
    # Now divide that array by the number of atoms to get the model index
    sym_model_indices_per_cb = list(sym_cb_index_per_cb // coords_length)
    # print('FLOORED sym CB INDICES to get MODEL\n:', sym_model_indices_per_cb)
    symmetry_mate_index_symmetric_coords = symmetric_interface_coords.reshape((number_of_models, -1, 3))
    # print('RESHAPED SYMMETRIC COORDS SHAPE:', symmetry_mate_index_symmetric_coords.shape,
    #       '\nCOORDS length:', coords_length)
    # Get the cb coords from the symmetric coords that correspond to the asu indices
    closest_interface_coords = \
        np.concatenate([symmetry_mate_index_symmetric_coords[model_idx, residue.atom_indices]
                        for model_idx, residue in zip(sym_model_indices_per_cb, interface_asu_structure.residues)])
    # closest_symmetric_coords = \
    #     np.where(index_cluster_labels[:, None] == asu_index, symmetric_interface_coords, np.array([0.0, 0.0, 0.0]))
    # closest_interface_coords = \
    #     closest_symmetric_coords.reshape((self.number_of_symmetry_mates, interface_coords.shape[0], -1)).sum(axis=0)

    interface_asu_structure.coords = closest_interface_coords

    # Correct structure attributes
    # Get the new indices where there are different Entity instances
    entity_breaks = iter(self.entity_breaks)
    next_entity_break = next(entity_breaks)
    interface_residue_entity_breaks = []  # 0]
    for idx, residue in enumerate(sorted_residues):
        if residue.index > next_entity_break:
            interface_residue_entity_breaks.append(idx)
            try:
                next_entity_break = next(entity_breaks)
            except StopIteration:
                raise StopIteration(f'Reached the end of self.entity_breaks before sorted_residues ran out')
    else:  # Add the final idx
        interface_residue_entity_breaks.append(idx + 1)

    # For each residue, rename the chain_id according to the model it belongs to
    number_entities = self.number_of_entities
    model_chain_ids = list(chain_id_generator())[:number_of_models * number_entities]
    entity_idx = 0
    next_interface_asu_entity_break = interface_residue_entity_breaks[entity_idx]
    for model_idx, residue in zip(sym_model_indices_per_cb, interface_asu_structure.residues):
        if residue.index >= next_interface_asu_entity_break:  # Increment the entity_idx
            entity_idx += 1
            next_interface_asu_entity_break = interface_residue_entity_breaks[entity_idx]
        residue.chain_id = model_chain_ids[(model_idx * number_entities) + entity_idx]

    return interface_asu_structure

get_interface_residues

get_interface_residues(entity1: Entity = None, entity2: Entity = None, **kwargs) -> tuple[list[Residue] | list, list[Residue] | list]

Get unique Residues across an interface between two Entities

If the interface occurs between the same Entity which is non-symmetrically defined, but happens to occur along a dimeric axis of symmetry (evaluates to True when the same Residue is found on each side of the interface), then the residues are returned belonging to only one side of the interface

Parameters:

  • entity1 (Entity, default: None ) –

    First Entity to measure interface between

  • entity2 (Entity, default: None ) –

    Second Entity to measure interface between

Other Parameters:

  • oligomeric_interfaces

    bool = False - Whether to query oligomeric interfaces

  • distance

    float = 8. - The distance to measure Residues across an interface

Returns:

  • tuple[list[Residue] | list, list[Residue] | list]

    The Entity1 and Entity2 interface Residue instances

Source code in symdesign/structure/model.py
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
def get_interface_residues(
        self, entity1: Entity = None, entity2: Entity = None, **kwargs
) -> tuple[list[Residue] | list, list[Residue] | list]:
    """Get unique Residues across an interface between two Entities

    If the interface occurs between the same Entity which is non-symmetrically defined, but happens to occur along a
    dimeric axis of symmetry (evaluates to True when the same Residue is found on each side of the interface), then
    the residues are returned belonging to only one side of the interface

    Args:
        entity1: First Entity to measure interface between
        entity2: Second Entity to measure interface between

    Keyword Args:
        oligomeric_interfaces: bool = False - Whether to query oligomeric interfaces
        distance: float = 8. - The distance to measure Residues across an interface

    Returns:
        The Entity1 and Entity2 interface Residue instances
    """
    entity1_residues, entity2_residues = \
        split_residue_pairs(self._find_interface_residue_pairs(entity1=entity1, entity2=entity2, **kwargs))

    if not entity1_residues or not entity2_residues:
        self.log.info(f'Interface search at {entity1.name} | {entity2.name} found no interface residues')
        return [], []

    if entity1 == entity2:  # If symmetric query
        # Is the interface across a dimeric interface?
        for residue in entity2_residues:  # entity2 usually has fewer residues, this might be quickest
            if residue in entity1_residues:  # The interface is dimeric
                # Include all residues found to only one side and move on
                entity1_residues = sorted(set(entity1_residues).union(entity2_residues), key=lambda res: res.number)
                entity2_residues = []
                break
    self.log.info(f'At Entity {entity1.name} | Entity {entity2.name} interface:'
                  f'\n\t{entity1.name} found residue numbers: {", ".join(str(r.number) for r in entity1_residues)}'
                  f'\n\t{entity2.name} found residue numbers: {", ".join(str(r.number) for r in entity2_residues)}')

    return entity1_residues, entity2_residues

local_density_interface

local_density_interface(distance: float = 12.0, atom_distance: float = None, **kwargs) -> float

Returns the density of heavy Atoms neighbors within 'distance' Angstroms to Atoms in the Pose interface

Parameters:

  • distance (float, default: 12.0 ) –

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

  • atom_distance (float, default: None ) –

    The distance to measure contacts between atoms. By default, uses default_atom_count_distance

Other Parameters:

  • residue_distance

    float = 8. - The distance to residue contacts in the interface. Uses the default if None

  • oligomeric_interfaces

    bool = False - Whether to query oligomeric interfaces

Returns:

  • float

    The local atom density around the interface

Source code in symdesign/structure/model.py
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
def local_density_interface(self, distance: float = 12., atom_distance: float = None, **kwargs) -> float:
    """Returns the density of heavy Atoms neighbors within 'distance' Angstroms to Atoms in the Pose interface

    Args:
        distance: The cutoff distance with which Atoms should be included in local density
        atom_distance: The distance to measure contacts between atoms. By default, uses default_atom_count_distance

    Keyword Args:
        residue_distance: float = 8. - The distance to residue contacts in the interface. Uses the default if None
        oligomeric_interfaces: bool = False - Whether to query oligomeric interfaces

    Returns:
        The local atom density around the interface
    """
    if atom_distance:
        kwargs['distance'] = atom_distance

    interface_indices1, interface_indices2 = [], []
    for entity1, entity2 in self.interface_residues_by_entity_pair:
        atoms_indices1, atoms_indices2 = \
            split_number_pairs_and_sort(self._find_interface_atom_pairs(entity1=entity1, entity2=entity2, **kwargs))
        interface_indices1.extend(atoms_indices1)
        interface_indices2.extend(atoms_indices2)

    if not interface_indices1 and not interface_indices2:
        self.log.warning(f'No interface atoms located during {self.local_density_interface.__name__}')
        return 0.

    interface_indices = list(set(interface_indices1).union(interface_indices2))
    if self.is_symmetric():
        interface_coords = self.symmetric_coords[interface_indices]
    else:
        interface_coords = self.coords[interface_indices]

    interface_tree = BallTree(interface_coords)
    interface_counts = interface_tree.query_radius(interface_coords, distance, count_only=True)

    return interface_counts.mean()

query_entity_pair_for_fragments

query_entity_pair_for_fragments(entity1: Entity = None, entity2: Entity = None, oligomeric_interfaces: bool = False, **kwargs)

For all found interface residues in an Entity/Entity interface, search for corresponding fragment pairs

Parameters:

  • entity1 (Entity, default: None ) –

    The first Entity to measure for interface fragments

  • entity2 (Entity, default: None ) –

    The second Entity to measure for interface fragments

  • oligomeric_interfaces (bool, default: False ) –

    Whether to query oligomeric interfaces

Other Parameters:

  • by_distance

    bool = False - Whether interface Residue instances should be found by inter-residue Cb distance

  • distance

    float = 8. - The distance to measure Residues across an interface

Sets

self._fragment_info_by_entity_pair (dict[tuple[str, str], list[FragmentInfo]])

Source code in symdesign/structure/model.py
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
def query_entity_pair_for_fragments(self, entity1: Entity = None, entity2: Entity = None,
                                    oligomeric_interfaces: bool = False, **kwargs):
    """For all found interface residues in an Entity/Entity interface, search for corresponding fragment pairs

    Args:
        entity1: The first Entity to measure for interface fragments
        entity2: The second Entity to measure for interface fragments
        oligomeric_interfaces: Whether to query oligomeric interfaces

    Keyword Args:
        by_distance: bool = False - Whether interface Residue instances should be found by inter-residue Cb distance
        distance: float = 8. - The distance to measure Residues across an interface

    Sets:
        self._fragment_info_by_entity_pair (dict[tuple[str, str], list[FragmentInfo]])
    """
    if (entity1.name, entity2.name) in self._fragment_info_by_entity_pair:
        # Due to asymmetry in fragment generation, (2, 1) isn't checked
        return

    try:
        residues1, residues2 = self.interface_residues_by_entity_pair[(entity1, entity2)]
    except KeyError:  # When interface_residues haven't been set
        self.find_and_split_interface(**kwargs)
        try:
            residues1, residues2 = self.interface_residues_by_entity_pair[(entity1, entity2)]
        except KeyError:
            raise DesignError(
                f"{self.query_entity_pair_for_fragments.__name__} can't access 'interface_residues' as the Entity "
                f"pair {entity1.name}, {entity2.name} hasn't located any 'interface_residues'")

    # Because of the way self.interface_residues_by_entity_pair is set, when there isn't an interface, a check on
    # residues1 is sufficient, however residues2 is empty with an interface present across a
    # non-oligomeric dimeric 2-fold
    if not residues1:
        self.log.debug(f'No residues at the {entity1.name} | {entity2.name} interface. Fragments not available')
        self._fragment_info_by_entity_pair[(entity1.name, entity2.name)] = []
        return

    frag_residues1 = entity1.get_fragment_residues(residues=residues1, fragment_db=self.fragment_db)
    if not residues2:  # entity1 == entity2 and not residues2:
        frag_residues2 = frag_residues1.copy()
    else:
        frag_residues2 = entity2.get_fragment_residues(residues=residues2, fragment_db=self.fragment_db)

    if not frag_residues1 or not frag_residues2:
        self.log.info(f'No fragments found at the {entity1.name} | {entity2.name} interface')
        self._fragment_info_by_entity_pair[(entity1.name, entity2.name)] = []
        return
    else:
        self.log.debug(f'At Entity {entity1.name} | Entity {entity2.name} interface:\n\t'
                       f'{entity1.name} has {len(frag_residues1)} interface fragments at residues: '
                       f'{",".join(map(str, [res.number for res in frag_residues1]))}\n\t'
                       f'{entity2.name} has {len(frag_residues2)} interface fragments at residues: '
                       f'{",".join(map(str, [res.number for res in frag_residues2]))}')

    if self.is_symmetric():
        # Even if entity1 == entity2, only need to expand the entity2 fragments due to surface/ghost frag mechanics
        skip_models = []
        if entity1 == entity2:
            if oligomeric_interfaces:  # Intra-oligomeric contacts are desired
                self.log.info(f'Including oligomeric models: '
                              f'{", ".join(map(str, self.oligomeric_model_indices.get(entity1)))}')
            elif entity1.is_symmetric():
                # Remove interactions with the intra-oligomeric contacts (contains asu)
                skip_models = self.oligomeric_model_indices.get(entity1)
                self.log.info(f'Skipping oligomeric models: {", ".join(map(str, skip_models))}')
            # else:  # Probably a C1

        symmetric_frags2 = [self.return_symmetric_copies(residue) for residue in frag_residues2]
        frag_residues2.clear()
        for frag_mates in symmetric_frags2:
            frag_residues2.extend([frag for sym_idx, frag in enumerate(frag_mates) if sym_idx not in skip_models])
        self.log.debug(f'Entity {entity2.name} has {len(frag_residues2)} symmetric fragments')

    # For clash check, only the backbone and Cb are desired
    entity1_coords = entity1.backbone_and_cb_coords
    fragment_time_start = time.time()
    ghostfrag_surfacefrag_pairs = \
        find_fragment_overlap(frag_residues1, frag_residues2, clash_coords=entity1_coords)
    self.log.info(f'Found {len(ghostfrag_surfacefrag_pairs)} overlapping fragment pairs at the {entity1.name} | '
                  f'{entity2.name} interface')
    self.log.debug(f'Took {time.time() - fragment_time_start:.8f}s')

    self._fragment_info_by_entity_pair[(entity1.name, entity2.name)] = \
        create_fragment_info_from_pairs(ghostfrag_surfacefrag_pairs)

find_and_split_interface

find_and_split_interface(by_distance: bool = False, **kwargs)

Locate interfaces regions for the designable entities and split into two contiguous interface residues sets

Parameters:

  • by_distance (bool, default: False ) –

    Whether interface Residue instances should be found by inter-residue Cb distance

Other Parameters:

  • distance

    float = 8. - The distance to measure Residues across an interface

  • oligomeric_interfaces

    bool = False - Whether to query oligomeric interfaces

Sets

self._interface_residues_by_entity_pair (dict[tuple[str, str], tuple[list[int], list[int]]]): The Entity1/Entity2 interface mapped to the interface Residues self._interface_residues_by_interface (dict[int, list[int]]): Residue instances separated by interface topology self._interface_residues_by_interface_unique (dict[int, list[int]]): Residue instances separated by interface topology removing any dimeric duplicates

Source code in symdesign/structure/model.py
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
def find_and_split_interface(self, by_distance: bool = False, **kwargs):
    """Locate interfaces regions for the designable entities and split into two contiguous interface residues sets

    Args:
        by_distance: Whether interface Residue instances should be found by inter-residue Cb distance

    Keyword Args:
        distance: float = 8. - The distance to measure Residues across an interface
        oligomeric_interfaces: bool = False - Whether to query oligomeric interfaces

    Sets:
        self._interface_residues_by_entity_pair (dict[tuple[str, str], tuple[list[int], list[int]]]):
            The Entity1/Entity2 interface mapped to the interface Residues
        self._interface_residues_by_interface (dict[int, list[int]]): Residue instances separated by
            interface topology
        self._interface_residues_by_interface_unique (dict[int, list[int]]): Residue instances separated by
            interface topology removing any dimeric duplicates
    """
    if self._interface_residue_indices_by_interface:
        self.log.debug("Interface residues weren't set as they're already set. If they've been changed, the "
                       "attribute 'interface_residues_by_interface' should be reset")
        return

    active_entities = self.active_entities
    self.log.debug('Find and split interface using active_entities: '
                   f'{", ".join(entity.name for entity in active_entities)}')

    if by_distance:
        if self.is_symmetric():
            entity_combinations = combinations_with_replacement(active_entities, 2)
        else:
            entity_combinations = combinations(active_entities, 2)

        entity_pair: tuple[Entity, Entity]
        for entity1, entity2 in entity_combinations:
            residues1, residues2 = self.get_interface_residues(entity1, entity2, **kwargs)
            self._interface_residue_indices_by_entity_name_pair[(entity1.name, entity2.name)] = (
                [res.index for res in residues1],
                [res.index for res in residues2]
            )
    else:
        self._find_interface_residues_by_buried_surface_area()

    self.check_interface_topology()

check_interface_topology

check_interface_topology()

From each pair of entities that share an interface, split the identified residues into two distinct groups. If an interface can't be composed into two distinct groups, raise DesignError

Sets

self._interface_residues_by_interface (dict[int, list[int]]): Residue instances separated by interface topology self._interface_residues_by_interface_unique (dict[int, list[int]]): Residue instances separated by interface topology removing any dimeric duplicates

Source code in symdesign/structure/model.py
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
def check_interface_topology(self):
    """From each pair of entities that share an interface, split the identified residues into two distinct groups.
    If an interface can't be composed into two distinct groups, raise DesignError

    Sets:
        self._interface_residues_by_interface (dict[int, list[int]]): Residue instances separated by
            interface topology
        self._interface_residues_by_interface_unique (dict[int, list[int]]): Residue instances separated by
            interface topology removing any dimeric duplicates
    """
    first_side, second_side = 0, 1
    first_interface_side = defaultdict(list)  # {}
    second_interface_side = defaultdict(list)  # {}
    # interface = {first_side: {}, second_side: {}}
    # Assume no symmetric contacts to start, i.e. [False, False]
    self_indication = [False, False]
    """Set to True if the interface side (1 or 2) contains self-symmetric contacts"""
    symmetric_dimer = {entity: False for entity in self.entities}
    terminate = False
    for (entity1, entity2), (residues1, residues2) in self.interface_residues_by_entity_pair.items():
        # if not entity_residues:
        if not residues1:  # No residues were found at this interface
            continue
        # Partition residues from each entity to the correct interface side
        # Check for any existing symmetry
        if entity1 == entity2:  # The query is with itself. Record as a self interaction
            _self = True
            if not residues2:  # The interface is a symmetric dimer and residues were removed from interface 2
                symmetric_dimer[entity1] = True
                # Set residues2 as residues1
                residues2 = residues1  # .copy()  # Add residues1 to residues2
        else:
            _self = False

        if not first_interface_side:  # This is first interface observation
            # Add the pair to the dictionary in their indexed order
            first_interface_side[entity1].extend(residues1)  # residues1.copy()
            second_interface_side[entity2].extend(residues2)  # residues2.copy()
            # Indicate whether the interface is a self symmetric interface by marking side 2 with _self
            self_indication[second_side] = _self
        else:  # Interface already assigned, so interface observation >= 2
            # Need to check if either Entity is in either side before adding correctly
            if entity1 in first_interface_side:  # is Entity1 on the interface side 1?
                # Is Entity1 in interface1 here as a result of self symmetric interaction?
                if self_indication[first_side]:
                    # Yes. Ex4 - self Entity was added to index 0 while ASU added to index 1
                    # Add Entity1 to interface side 2
                    second_interface_side[entity1].extend(residues1)
                    # Add new Entity2 to interface side 1
                    first_interface_side[entity2].extend(residues2)  # residues2.copy()
                else:  # Entities are properly indexed
                    # Add Entity1 to the first
                    first_interface_side[entity1].extend(residues1)
                    # Because of combinations with replacement Entity search, the second Entity isn't in
                    # interface side 2, UNLESS the Entity self interaction is on interface 1 (above if check)
                    # Therefore, add Entity2 to the second without checking for overwrite
                    second_interface_side[entity2].extend(residues2)  # residues2.copy()
                    # This can't happen, it would VIOLATE RULES
                    # if _self:
                    #     self_indication[second_side] = _self
            # Entity1 isn't in the first index. It may be in the second, it may not
            elif entity1 in second_interface_side:
                # Yes. Ex5, add to interface side 2
                second_interface_side[entity1].extend(residues1)
                # Also, add Entity2 to the first side
                # Entity 2 can't be in interface side 1 due to combinations with replacement check
                first_interface_side[entity2].extend(residues2)  # residues2.copy()
                if _self:  # Only modify if self is True, don't want to overwrite an existing True value
                    self_indication[first_side] = _self
            # If Entity1 is missing, check Entity2 to see if it has been identified yet
            # This is more likely from combinations with replacement
            elif entity2 in second_interface_side:
                # Possible in an iteration Ex: (A:D) (C:D)
                second_interface_side[entity2].extend(residues2)
                # Entity 1 was not in first interface (from if #1), therefore we can set directly
                first_interface_side[entity1].extend(residues1)  # residues1.copy()
                # Ex3
                if _self:  # Only modify if self is True, don't want to overwrite an existing True value
                    self_indication[first_side] = _self
            elif entity2 in first_interface_side:
                # The first Entity wasn't found in either interface, but both interfaces are already set,
                # therefore Entity pair isn't self, so the only way this works is if entity1 is further in the
                # iterative process which is an impossible topology given combinations with replacement.
                # Violates interface separation rules
                second_interface_side[entity1] = False
                terminate = True
                break
            # Neither of our Entities were found, thus we would add 2 entities to each interface side, violation
            else:
                first_interface_side[entity1] = second_interface_side[entity2] = False
                terminate = True
                break

        if len(first_interface_side) == 2 and len(second_interface_side) == 2 and all(self_indication):
            pass
        elif len(first_interface_side) == 1 or len(second_interface_side) == 1:
            pass
        else:
            terminate = True
            break

    if terminate:
        self.log.critical('The set of interfaces found during interface search generated a topologically '
                          'disallowed combination.\n\t %s\n This cannot be modeled by a simple split for residues '
                          'on either side while respecting the requirements of polymeric Entities. '
                          '%sPlease correct your design_selectors to reduce the number of Entities you are '
                          'attempting to design'
                          % (' | '.join(':'.join(entity.name for entity in interface_entities)
                                        for interface_entities in (first_interface_side, second_interface_side)),
                             'Symmetry was set which may have influenced this unfeasible topology, you can try to '
                             'set it False. ' if self.is_symmetric() else ''))
        raise DesignError('The specified interfaces generated a topologically disallowed combination')

    if not first_interface_side:
        # raise utils.DesignError('Interface was unable to be split because no residues were found on one side of '
        self.log.warning("The interface wasn't able to be split because no residues were found on one side. "
                         "Check that your input has an interface or your flags aren't too stringent")
        return

    for interface_number, entity_residues in enumerate((first_interface_side, second_interface_side), 1):
        _residue_indices = [residue.index for _, residues in entity_residues.items() for residue in residues]
        self._interface_residue_indices_by_interface[interface_number] = sorted(set(_residue_indices))

    if any(symmetric_dimer.values()):
        # For each entity, find the maximum residue observations on each interface side
        entity_observations = {entity: [0, 0] for entity, dimer in symmetric_dimer.items() if dimer}
        for interface_index, entity_residues in enumerate((first_interface_side, second_interface_side)):
            for entity, observations in entity_observations.items():
                observations[interface_index] += len(entity_residues[entity])

        # Remove non-unique occurrences by entity if there are fewer observations
        for entity, observations in entity_observations.items():
            interface_obs1, interface_obs2 = entity_observations[entity]
            if interface_obs1 > interface_obs2:
                second_interface_side.pop(entity)
            elif interface_obs1 < interface_obs2:
                first_interface_side.pop(entity)
            elif len(entity_observations) == 1:
                # This is a homo-dimer, by convention, get rid of the second side
                second_interface_side.pop(entity)
            else:
                raise SymmetryError(
                    f"Couldn't separate {entity.name} dimeric interface into unique residues. The number of "
                    f"residues in each interface is equal: {interface_obs1} == {interface_obs2}")

        # Perform the sort as without dimeric constraints
        for interface_number, entity_residues in enumerate((first_interface_side, second_interface_side), 1):
            _residue_indices = [residue.index for _, residues in entity_residues.items() for residue in residues]
            self._interface_residue_indices_by_interface_unique[interface_number] = sorted(set(_residue_indices))

    else:  # Just make a copy of the internal list... Avoids unforeseen issues if these are ever modified
        self._interface_residue_indices_by_interface_unique = \
            {number: residue_indices.copy()
             for number, residue_indices in self._interface_residue_indices_by_interface.items()}

calculate_secondary_structure

calculate_secondary_structure()

Curate the secondary structure topology for each Entity

Sets

self.ss_sequence_indices (list[int]): Index which indicates the Residue membership to the secondary structure type element sequence self.ss_type_sequence (list[str]): The ordered secondary structure type sequence which contains one character/secondary structure element self.split_interface_ss_elements (dict[int, list[int]]): Maps the interface number to a list of indices corresponding to the secondary structure type Ex: {1: [0, 0, 1, 2, ...] , 2: [9, 9, 9, 13, ...]]}

Source code in symdesign/structure/model.py
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
def calculate_secondary_structure(self):
    """Curate the secondary structure topology for each Entity

    Sets:
        self.ss_sequence_indices (list[int]):
            Index which indicates the Residue membership to the secondary structure type element sequence
        self.ss_type_sequence (list[str]):
            The ordered secondary structure type sequence which contains one character/secondary structure element
        self.split_interface_ss_elements (dict[int, list[int]]):
            Maps the interface number to a list of indices corresponding to the secondary structure type
            Ex: {1: [0, 0, 1, 2, ...] , 2: [9, 9, 9, 13, ...]]}
    """
    pose_secondary_structure = ''
    for entity in self.entities:  # self.active_entities:
        pose_secondary_structure += entity.secondary_structure

    # Increment a secondary structure index which changes with every secondary structure transition
    # Simultaneously, map the secondary structure type to an array of pose length
    ss_increment_index = 0
    ss_sequence_indices = [ss_increment_index]
    ss_type_sequence = [pose_secondary_structure[0]]
    for prior_ss_type, ss_type in zip(pose_secondary_structure[:-1], pose_secondary_structure[1:]):
        if prior_ss_type != ss_type:
            ss_increment_index += 1
            ss_type_sequence.append(ss_type)
        ss_sequence_indices.append(ss_increment_index)

    # Clear any information if it exists
    self.ss_sequence_indices.clear(), self.ss_type_sequence.clear()
    self.ss_sequence_indices.extend(ss_sequence_indices)
    self.ss_type_sequence.extend(ss_type_sequence)

    for number, residue_indices in self._interface_residue_indices_by_interface_unique.items():
        self.split_interface_ss_elements[number] = [ss_sequence_indices[idx] for idx in residue_indices]
    self.log.debug(f'Found interface secondary structure: {self.split_interface_ss_elements}')
    self.secondary_structure = pose_secondary_structure

calculate_fragment_profile

calculate_fragment_profile(**kwargs)

Take the fragment_profile from each member Entity and combine

Other Parameters:

  • evo_fill

    bool = False - Whether to fill missing positions with evolutionary profile values

  • alpha

    float = 0.5 - The maximum contribution of the fragment profile to use, bounded between (0, 1]. 0 means no use of fragments in the .profile, while 1 means only use fragments

Source code in symdesign/structure/model.py
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
def calculate_fragment_profile(self, **kwargs):
    """Take the fragment_profile from each member Entity and combine

    Keyword Args:
        evo_fill: bool = False - Whether to fill missing positions with evolutionary profile values
        alpha: float = 0.5 - The maximum contribution of the fragment profile to use, bounded between (0, 1].
            0 means no use of fragments in the .profile, while 1 means only use fragments
    """
    #   keep_extras: bool = True - Whether to keep values for all that are missing data
    for (entity1, entity2), fragment_info in self.fragment_info_by_entity_pair.items():
        if fragment_info:
            self.log.debug(f'Query Pair: {entity1.name}, {entity2.name}'
                           f'\n\tFragment Info:{fragment_info}')
            entity1.add_fragments_to_profile(fragments=fragment_info, alignment_type='mapped')
            entity2.add_fragments_to_profile(fragments=fragment_info, alignment_type='paired')

    # The order of this and below could be switched by combining self.fragment_map too
    # Also, need to extract the entity.fragment_map to process_fragment_profile()
    fragments_available = False
    entities = self.entities
    for entity in entities:
        if entity.fragment_map:
            entity.simplify_fragment_profile(**kwargs)
            fragments_available = True
        else:
            entity.fragment_profile = Profile(
                list(entity.create_null_profile(nan=True, zero_index=True).values()), dtype='fragment')

    if fragments_available:
        # # This assumes all values are present. What if they are not?
        # self.fragment_profile = concatenate_profile([entity.fragment_profile for entity in self.entities],
        #                                             start_at=0)
        # self.alpha = concatenate_profile([entity.alpha for entity in self.entities])
        fragment_profile = []
        alpha = []
        for entity in entities:
            fragment_profile.extend(entity.fragment_profile)
            alpha.extend(entity.alpha)
        fragment_profile = Profile(fragment_profile, dtype='fragment')
        self._alpha = entity._alpha  # Logic enforces entity is always referenced here
    else:
        alpha = [0 for _ in range(self.number_of_residues)]  # Reset the data
        fragment_profile = Profile(
            list(self.create_null_profile(nan=True, zero_index=True).values()), dtype='fragment')
    self.alpha = alpha
    self.fragment_profile = fragment_profile

get_fragment_observations

get_fragment_observations(interface: bool = True) -> list[FragmentInfo] | list

Return the fragment observations identified on the Pose for various types of tertiary structure interactions

Parameters:

  • interface (bool, default: True ) –

    Whether to return fragment observations from only the Pose interface

Returns:

  • list[FragmentInfo] | list

    The fragment observations

Source code in symdesign/structure/model.py
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
def get_fragment_observations(self, interface: bool = True) -> list[FragmentInfo] | list:
    """Return the fragment observations identified on the Pose for various types of tertiary structure interactions

    Args:
        interface: Whether to return fragment observations from only the Pose interface

    Returns:
        The fragment observations
    """
    # Ensure fragments are generated if they aren't already
    if interface:
        self.generate_interface_fragments()
    else:
        self.generate_fragments()

    interface_residues_by_entity_pair = self.interface_residues_by_entity_pair
    observations = []
    # {(ent1, ent2): [{mapped: res_num1, paired: res_num2, cluster: (int, int, int), match: score}, ...], ...}
    for entity_pair, fragment_info in self.fragment_info_by_entity_pair.items():
        if interface:
            if entity_pair not in interface_residues_by_entity_pair:
                continue

        observations.extend(fragment_info)

    return observations

get_fragment_metrics

get_fragment_metrics(fragments: list[FragmentInfo] = None, total_interface: bool = True, by_interface: bool = False, by_entity: bool = False, entity1: Entity = None, entity2: Entity = None, **kwargs) -> dict[str, Any]

Return fragment metrics from the Pose. Returns the entire Pose unless by_interface or by_entity is True

Uses data from self.fragment_queries unless fragments are passed

Parameters:

  • fragments (list[FragmentInfo], default: None ) –

    A list of fragment observations

  • total_interface (bool, default: True ) –

    Return all fragment metrics for every interface found in the Pose

  • by_interface (bool, default: False ) –

    Return fragment metrics for each particular interface between Chain instances in the Pose

  • by_entity (bool, default: False ) –

    Return fragment metrics for each Entity found in the Pose

  • entity1 (Entity, default: None ) –

    The first Entity object to identify the interface if per_interface=True

  • entity2 (Entity, default: None ) –

    The second Entity object to identify the interface if per_interface=True

Other Parameters:

  • distance

    float = 8. - The distance to measure Residues across an interface

  • oligomeric_interfaces

    bool = False - Whether to query oligomeric interfaces

Returns:

  • dict[str, Any]

    A mapping of the following metrics for the requested structural region - {'center_indices', 'total_indices', 'nanohedra_score', 'nanohedra_score_center', 'nanohedra_score_normalized', 'nanohedra_score_center_normalized', 'number_residues_fragment_total', 'number_residues_fragment_center', 'multiple_fragment_ratio', 'number_fragments_interface' 'percent_fragment_helix' 'percent_fragment_strand' 'percent_fragment_coil' }

  • dict[str, Any]

    Will include a single mapping if total_interface, a mapping for each interface if by_interface, and a

  • dict[str, Any]

    mapping for each Entity if by_entity

Source code in symdesign/structure/model.py
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
def get_fragment_metrics(self, fragments: list[FragmentInfo] = None, total_interface: bool = True,
                         by_interface: bool = False, by_entity: bool = False,
                         entity1: Entity = None, entity2: Entity = None, **kwargs) -> dict[str, Any]:
    """Return fragment metrics from the Pose. Returns the entire Pose unless by_interface or by_entity is True

    Uses data from self.fragment_queries unless fragments are passed

    Args:
        fragments: A list of fragment observations
        total_interface: Return all fragment metrics for every interface found in the Pose
        by_interface: Return fragment metrics for each particular interface between Chain instances in the Pose
        by_entity: Return fragment metrics for each Entity found in the Pose
        entity1: The first Entity object to identify the interface if per_interface=True
        entity2: The second Entity object to identify the interface if per_interface=True

    Keyword Args:
        distance: float = 8. - The distance to measure Residues across an interface
        oligomeric_interfaces: bool = False - Whether to query oligomeric interfaces

    Returns:
        A mapping of the following metrics for the requested structural region -
            {'center_indices',
             'total_indices',
             'nanohedra_score',
             'nanohedra_score_center',
             'nanohedra_score_normalized',
             'nanohedra_score_center_normalized',
             'number_residues_fragment_total',
             'number_residues_fragment_center',
             'multiple_fragment_ratio',
             'number_fragments_interface'
             'percent_fragment_helix'
             'percent_fragment_strand'
             'percent_fragment_coil'
             }
        Will include a single mapping if total_interface, a mapping for each interface if by_interface, and a
        mapping for each Entity if by_entity
    """

    if fragments is not None:
        fragment_db = self.fragment_db
        return fragment_db.format_fragment_metrics(fragment_db.calculate_match_metrics(fragments))

    fragment_metrics = self.fragment_metrics_by_entity_pair

    if by_interface:
        fragment_info = self.fragment_info_by_entity_pair
        # Check for either orientation as the final interface score will be the same
        if (entity1, entity2) not in fragment_info or (entity2, entity1) not in fragment_info:
            self.query_entity_pair_for_fragments(entity1=entity1, entity2=entity2, **kwargs)

        metric_d = deepcopy(fragment_metric_template)
        for query_pair, _metrics in fragment_metrics.items():
            # Check either orientation as the function query could vary from self.fragment_metrics
            if (entity1, entity2) in query_pair or (entity2, entity1) in query_pair:
                if _metrics:
                    metric_d = self.fragment_db.format_fragment_metrics(_metrics)
                    break
        else:
            self.log.warning(f"Couldn't locate query metrics for Entity pair {entity1.name}, {entity2.name}")
    elif by_entity:
        metric_d = {}
        for query_pair, _metrics in fragment_metrics.items():
            if not _metrics:
                continue
            for align_type, entity in zip(alignment_types, query_pair):
                if entity not in metric_d:
                    metric_d[entity] = deepcopy(fragment_metric_template)

                metric_d[entity]['center_indices'].update(_metrics[align_type]['center']['indices'])
                metric_d[entity]['total_indices'].update(_metrics[align_type]['total']['indices'])
                metric_d[entity]['nanohedra_score'] += _metrics[align_type]['total']['score']
                metric_d[entity]['nanohedra_score_center'] += _metrics[align_type]['center']['score']
                metric_d[entity]['multiple_fragment_ratio'] += _metrics[align_type]['multiple_ratio']
                metric_d[entity]['number_fragments_interface'] += _metrics['total']['observations']
                metric_d[entity]['percent_fragment_helix'] += _metrics[align_type]['index_count'][1]
                metric_d[entity]['percent_fragment_strand'] += _metrics[align_type]['index_count'][2]
                metric_d[entity]['percent_fragment_coil'] += _metrics[align_type]['index_count'][3] \
                    + _metrics[align_type]['index_count'][4] + _metrics[align_type]['index_count'][5]

        # Finally, tabulate based on the total for each Entity
        for entity, _metrics in metric_d.items():
            _metrics['number_residues_fragment_total'] = len(_metrics['total_indices'])
            _metrics['number_residues_fragment_center'] = len(_metrics['center_indices'])
            number_fragments_interface = _metrics['number_fragments_interface']
            _metrics['percent_fragment_helix'] /= number_fragments_interface
            _metrics['percent_fragment_strand'] /= number_fragments_interface
            _metrics['percent_fragment_coil'] /= number_fragments_interface
            try:
                _metrics['nanohedra_score_normalized'] = \
                    _metrics['nanohedra_score'] / _metrics['number_residues_fragment_total']
                _metrics['nanohedra_score_center_normalized'] = \
                    _metrics['nanohedra_score_center'] / _metrics['number_residues_fragment_center']
            except ZeroDivisionError:
                self.log.warning(f'{self.name}: No interface residues were found. Is there an interface in your '
                                 f'design?')
                _metrics['nanohedra_score_normalized'] = _metrics['nanohedra_score_center_normalized'] = 0.

    elif total_interface:  # For the entire interface
        metric_d = deepcopy(fragment_metric_template)
        for query_pair, _metrics in fragment_metrics.items():
            if not _metrics:
                continue
            metric_d['center_indices'].update(
                _metrics['mapped']['center']['indices'].union(_metrics['paired']['center']['indices']))
            metric_d['total_indices'].update(
                _metrics['mapped']['total']['indices'].union(_metrics['paired']['total']['indices']))
            metric_d['nanohedra_score'] += _metrics['total']['total']['score']
            metric_d['nanohedra_score_center'] += _metrics['total']['center']['score']
            metric_d['multiple_fragment_ratio'] += _metrics['total']['multiple_ratio']
            metric_d['number_fragments_interface'] += _metrics['total']['observations']
            metric_d['percent_fragment_helix'] += _metrics['total']['index_count'][1]
            metric_d['percent_fragment_strand'] += _metrics['total']['index_count'][2]
            metric_d['percent_fragment_coil'] += _metrics['total']['index_count'][3] \
                + _metrics['total']['index_count'][4] + _metrics['total']['index_count'][5]

        # Finally, tabulate based on the total
        metric_d['number_residues_fragment_total'] = len(metric_d['total_indices'])
        metric_d['number_residues_fragment_center'] = len(metric_d['center_indices'])
        total_observations = metric_d['number_fragments_interface'] * 2  # 2x observations in ['total']['index_count']
        try:
            metric_d['percent_fragment_helix'] /= total_observations
            metric_d['percent_fragment_strand'] /= total_observations
            metric_d['percent_fragment_coil'] /= total_observations
        except ZeroDivisionError:
            metric_d['percent_fragment_helix'] = metric_d['percent_fragment_strand'] = \
                metric_d['percent_fragment_coil'] = 0.
        try:
            metric_d['nanohedra_score_normalized'] = \
                metric_d['nanohedra_score'] / metric_d['number_residues_fragment_total']
            metric_d['nanohedra_score_center_normalized'] = \
                metric_d['nanohedra_score_center']/metric_d['number_residues_fragment_center']
        except ZeroDivisionError:
            self.log.debug(f'{self.name}: No fragment residues were found')
            metric_d['nanohedra_score_normalized'] = metric_d['nanohedra_score_center_normalized'] = 0.

    else:  # For the entire Pose?
        raise NotImplementedError("There isn't a mechanism to return fragments for the mode specified")

    return metric_d

residue_processing

residue_processing(design_scores: dict[str, dict[str, float | str]], columns: list[str]) -> dict[str, dict[int, dict[str, float | list]]]

Process Residue Metrics from Rosetta score dictionary (One-indexed residues)

Parameters:

  • design_scores (dict[str, dict[str, float | str]]) –

    {'001': {'buns': 2.0, 'res_energy_complex_15A': -2.71, ..., 'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...'}, ...}

  • columns (list[str]) –

    ['per_res_energy_complex_5', 'per_res_energy_1_unbound_5', ...]

Returns:

  • dict[str, dict[int, dict[str, float | list]]]

    {'001': {15: {'type': 'T', 'energy': {'complex': -2.71, 'unbound': [-1.9, 0]}, 'fsp': 0., 'cst': 0.}, ...}, ...}

Source code in symdesign/structure/model.py
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
def residue_processing(
    self, design_scores: dict[str, dict[str, float | str]], columns: list[str]
) -> dict[str, dict[int, dict[str, float | list]]]:
    """Process Residue Metrics from Rosetta score dictionary (One-indexed residues)

    Args:
        design_scores: {'001': {'buns': 2.0, 'res_energy_complex_15A': -2.71, ...,
                        'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...'}, ...}
        columns: ['per_res_energy_complex_5', 'per_res_energy_1_unbound_5', ...]

    Returns:
        {'001': {15: {'type': 'T', 'energy': {'complex': -2.71, 'unbound': [-1.9, 0]}, 'fsp': 0., 'cst': 0.}, ...},
         ...}
    """
    # energy_template = {'complex': 0., 'unbound': 0., 'fsp': 0., 'cst': 0.}
    residue_template = {'energy': {'complex': 0., 'unbound': [0. for ent in self.entities], 'fsp': 0., 'cst': 0.}}
    pose_length = self.number_of_residues
    # adjust the energy based on pose specifics
    pose_energy_multiplier = self.number_of_symmetry_mates  # Will be 1 if not self.is_symmetric()
    entity_energy_multiplier = [entity.number_of_symmetry_mates for entity in self.entities]

    warn = False
    parsed_design_residues = {}
    for design, scores in design_scores.items():
        residue_data = {}
        for column in columns:
            if column not in scores:
                continue
            metadata = column.strip('_').split('_')
            # remove chain_id in rosetta_numbering="False"
            # if we have enough chains, weird chain characters appear "per_res_energy_complex_19_" which mess up
            # split. Also numbers appear, "per_res_energy_complex_1161" which may indicate chain "1" or residue 1161
            residue_number = int(metadata[-1].translate(utils.keep_digit_table))
            if residue_number > pose_length:
                if not warn:
                    warn = True
                    logger.warning(
                        'Encountered %s which has residue number > the pose length (%d). If this system is '
                        'NOT a large symmetric system and output_as_pdb_nums="true" was used in Rosetta '
                        'PerResidue SimpleMetrics, there is an error in processing that requires your '
                        'debugging. Otherwise, this is likely a numerical chain and will be treated under '
                        'that assumption. Always ensure that output_as_pdb_nums="true" is set'
                        % (column, pose_length))
                residue_number = residue_number[:-1]
            if residue_number not in residue_data:
                residue_data[residue_number] = deepcopy(residue_template)  # deepcopy(energy_template)

            metric = metadata[2]  # energy [or sasa]
            if metric != 'energy':
                continue
            pose_state = metadata[-2]  # unbound or complex [or fsp (favor_sequence_profile) or cst (constraint)]
            entity_or_complex = metadata[3]  # 1,2,3,... or complex

            # use += because instances of symmetric residues from symmetry related chains are summed
            try:  # to convert to int. Will succeed if we have an entity value, ex: 1,2,3,...
                entity = int(entity_or_complex) - ZERO_OFFSET
                residue_data[residue_number][metric][pose_state][entity] += \
                    (scores.get(column, 0) / entity_energy_multiplier[entity])
            except ValueError:  # complex is the value, use the pose state
                residue_data[residue_number][metric][pose_state] += (scores.get(column, 0) / pose_energy_multiplier)
        parsed_design_residues[design] = residue_data

    return parsed_design_residues

process_rosetta_residue_scores

process_rosetta_residue_scores(design_scores: dict[str, dict[str, float | str]]) -> dict[str, dict[int, dict[str, float | list]]]

Process Residue Metrics from Rosetta score dictionary (One-indexed residues) accounting for symmetric energy

Parameters:

  • design_scores (dict[str, dict[str, float | str]]) –

    {'001': {'buns': 2.0, 'res_energy_complex_15A': -2.71, ..., 'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...'}, ...}

Returns:

  • dict[str, dict[int, dict[str, float | list]]]

    The parsed design information where the outer key is the design alias, and the next key is the Residue.index

  • dict[str, dict[int, dict[str, float | list]]]

    where the corresponding information belongs. Only returns Residue metrics for those positions where metrics

  • dict[str, dict[int, dict[str, float | list]]]

    were taken. Example: {'001': {15: {'complex': -2.71, 'bound': [-1.9, 0], 'unbound': [-1.9, 0], 'solv_complex': -2.71, 'solv_bound': [-1.9, 0], 'solv_unbound': [-1.9, 0], 'fsp': 0., 'cst': 0.}, ...}, ...}

Source code in symdesign/structure/model.py
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
def process_rosetta_residue_scores(self, design_scores: dict[str, dict[str, float | str]]) -> \
        dict[str, dict[int, dict[str, float | list]]]:
    """Process Residue Metrics from Rosetta score dictionary (One-indexed residues) accounting for symmetric energy

    Args:
        design_scores: {'001': {'buns': 2.0, 'res_energy_complex_15A': -2.71, ...,
                        'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...'}, ...}

    Returns:
        The parsed design information where the outer key is the design alias, and the next key is the Residue.index
        where the corresponding information belongs. Only returns Residue metrics for those positions where metrics
        were taken. Example:
            {'001':
                {15: {'complex': -2.71, 'bound': [-1.9, 0], 'unbound': [-1.9, 0],
                      'solv_complex': -2.71, 'solv_bound': [-1.9, 0], 'solv_unbound': [-1.9, 0],
                      'fsp': 0., 'cst': 0.},
                 ...},
             ...}
    """
    res_slice = slice(0, 4)
    pose_length = self.number_of_residues
    # Adjust the energy based on pose specifics
    pose_energy_multiplier = self.number_of_symmetry_mates  # Will be 1 if not self.is_symmetric()
    entity_energy_multiplier = [entity.number_of_symmetry_mates for entity in self.entities]

    def get_template(): return deepcopy({
        'complex': 0., 'bound': [0. for _ in self.entities], 'unbound': [0. for _ in self.entities],
        'solv_complex': 0., 'solv_bound': [0. for _ in self.entities],
        'solv_unbound': [0. for _ in self.entities], 'fsp': 0., 'cst': 0.})

    warn_additional = True
    parsed_design_residues = {}
    for design, scores in design_scores.items():
        residue_data = defaultdict(get_template)
        for key, value in scores.items():
            if key[res_slice] != 'res_':
                continue
            # key contains: 'per_res_energysolv_complex_15W' or 'per_res_energysolv_2_bound_415B'
            res, metric, entity_or_complex, *_ = metadata = key.strip('_').split('_')
            # metadata[1] is energy [or sasa]
            # metadata[2] is entity designation or complex such as '1','2','3',... or 'complex'

            # Take the "possibly" symmetric Rosetta residue index (one-indexed) and convert to python,
            # then take the modulus for the pose numbering
            try:
                residue_index = (int(metadata[-1])-1) % pose_length
            except ValueError:
                continue  # This is a residual metric
            # remove chain_id in rosetta_numbering="False"
            if metric == 'energysolv':
                metric_str = f'solv_{metadata[-2]}'  # pose_state - unbound, bound, complex
            elif metric == 'energy':
                metric_str = metadata[-2]  # pose_state - unbound, bound, complex
            else:  # Other residual such as sasa or something else old/new
                if warn_additional:
                    warn_additional = False
                    logger.warning(f"Found additional metrics that aren't being processed. Ex {key}={value}")
                continue

            # Use += because instances of symmetric residues from symmetry related chains are summed
            try:  # To convert to int. Will succeed if we have an entity as a string integer, ex: 1,2,3,...
                entity = int(entity_or_complex) - ZERO_OFFSET
            except ValueError:  # 'complex' is the value, use the pose state
                residue_data[residue_index][metric_str] += (value / pose_energy_multiplier)
            else:
                residue_data[residue_index][metric_str][entity] += (value / entity_energy_multiplier[entity])

        parsed_design_residues[design] = residue_data

    return parsed_design_residues

rosetta_hbond_processing

rosetta_hbond_processing(design_scores: dict[str, dict]) -> dict[str, set[int]]

Process Hydrogen bond Metrics from Rosetta score dictionary

if rosetta_numbering="true" in .xml then use offset, otherwise, hbonds are PDB numbering

Parameters:

  • design_scores (dict[str, dict]) –

    {'001': {'buns': 2.0, 'per_res_energy_complex_15A': -2.71, ..., 'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...', 'hbonds_res_selection_1_bound': '26A'}, ...}

Returns:

  • dict[str, set[int]]

    {'001': {34, 54, 67, 68, 106, 178}, ...}

Source code in symdesign/structure/model.py
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
def rosetta_hbond_processing(self, design_scores: dict[str, dict]) -> dict[str, set[int]]:
    """Process Hydrogen bond Metrics from Rosetta score dictionary

    if rosetta_numbering="true" in .xml then use offset, otherwise, hbonds are PDB numbering

    Args:
        design_scores: {'001': {'buns': 2.0, 'per_res_energy_complex_15A': -2.71, ...,
                                'yhh_planarity':0.885, 'hbonds_res_selection_complex': '15A,21A,26A,35A,...',
                                'hbonds_res_selection_1_bound': '26A'}, ...}

    Returns:
        {'001': {34, 54, 67, 68, 106, 178}, ...}
    """
    pose_length = self.number_of_residues
    hbonds = {}
    for design, scores in design_scores.items():
        unbound_bonds, complex_bonds = set(), set()
        for column, value in scores.items():
            if 'hbonds_res_' not in column:  # if not column.startswith('hbonds_res_selection'):
                continue
            meta_data = column.split('_')  # ['hbonds', 'res', 'selection', 'complex/interface_number', '[unbound]']
            # Offset rosetta numbering to python index and make asu index using the modulus
            parsed_hbond_indices = set((int(hbond)-1) % pose_length
                                       for hbond in value.split(',') if hbond != '')  # '' in case no hbonds
            # if meta_data[-1] == 'bound' and offset:  # find offset according to chain
            #     res_offset = offset[meta_data[-2]]
            #     parsed_hbonds = set(residue + res_offset for residue in parsed_hbonds)
            if meta_data[3] == 'complex':
                complex_bonds = parsed_hbond_indices
            else:  # From another state
                unbound_bonds = unbound_bonds.union(parsed_hbond_indices)
        if complex_bonds:  # 'complex', '1', '2'
            hbonds[design] = complex_bonds.difference(unbound_bonds)
        else:  # No hbonds were found in the complex
            hbonds[design] = complex_bonds

    return hbonds

generate_interface_fragments

generate_interface_fragments(oligomeric_interfaces: bool = False, **kwargs)

Generate fragments between the Pose interface(s). Finds interface(s) if not already available

Parameters:

  • oligomeric_interfaces (bool, default: False ) –

    Whether to query oligomeric interfaces

Other Parameters:

  • by_distance

    bool = False - Whether interface Residue instances should be found by inter-residue Cb distance

  • distance

    float = 8. - The distance to measure Residues across an interface

Source code in symdesign/structure/model.py
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
def generate_interface_fragments(self, oligomeric_interfaces: bool = False, **kwargs):
    """Generate fragments between the Pose interface(s). Finds interface(s) if not already available

    Args:
        oligomeric_interfaces: Whether to query oligomeric interfaces

    Keyword Args:
        by_distance: bool = False - Whether interface Residue instances should be found by inter-residue Cb distance
        distance: float = 8. - The distance to measure Residues across an interface
    """
    if not self._interface_residue_indices_by_interface:
        self.find_and_split_interface(oligomeric_interfaces=oligomeric_interfaces, **kwargs)

    if self.is_symmetric():
        entity_combinations = combinations_with_replacement(self.active_entities, 2)
    else:
        entity_combinations = combinations(self.active_entities, 2)

    entity_pair: Iterable[Entity]
    for entity_pair in entity_combinations:
        self.log.debug(f'Querying Entity pair: {", ".join(entity.name for entity in entity_pair)} '
                       f'for interface fragments')
        self.query_entity_pair_for_fragments(*entity_pair, oligomeric_interfaces=oligomeric_interfaces, **kwargs)

generate_fragments

generate_fragments(**kwargs)

Generate fragments pairs between every possible Residue instance in the Pose

Other Parameters:

  • distance

    float = 8. - The distance to query for neighboring fragments

Source code in symdesign/structure/model.py
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
def generate_fragments(self, **kwargs):
    """Generate fragments pairs between every possible Residue instance in the Pose

    Keyword Args:
        distance: float = 8. - The distance to query for neighboring fragments
    """
    for entity in self.active_entities:
        self.log.info(f'Querying Entity: {entity} for internal fragments')
        search_start_time = time.time()
        ghostfrag_surfacefrag_pairs = entity.find_fragments(**kwargs)
        self.log.info(f'Internal fragment search took {time.time() - search_start_time:8f}s')
        self._fragment_info_by_entity_pair[(entity.name, entity.name)] = \
            create_fragment_info_from_pairs(ghostfrag_surfacefrag_pairs)

write_fragment_pairs

write_fragment_pairs(out_path: AnyStr = os.getcwd(), multimodel: bool = False) -> AnyStr | None

Write the fragments associated with the pose to disk

Parameters:

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

    The path to the directory to output files to

  • multimodel (bool, default: False ) –

    Whether to write all fragments as a multimodel file. File written to "'out_path'/all_frags.pdb"

Returns:

  • AnyStr | None

    The path to the written file if one was written

Source code in symdesign/structure/model.py
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
def write_fragment_pairs(self, out_path: AnyStr = os.getcwd(), multimodel: bool = False) -> AnyStr | None:
    """Write the fragments associated with the pose to disk

    Args:
        out_path: The path to the directory to output files to
        multimodel: Whether to write all fragments as a multimodel file. File written to "'out_path'/all_frags.pdb"

    Returns:
        The path to the written file if one was written
    """
    residues = self.residues
    ghost_frags = []
    clusters = []
    for entity_pair, fragment_info in self.fragment_info_by_entity_pair.items():
        for info in fragment_info:
            ijk = info.cluster
            clusters.append(ijk)
            # match_score = info.match
            aligned_residue = residues[info.mapped]
            ghost_frag = aligned_residue.ghost_fragments[ijk]
            ghost_frags.append(ghost_frag)

    putils.make_path(out_path)
    file_path = None
    if multimodel:
        file_path = os.path.join(out_path, 'all_frags.pdb')
        write_fragments_as_multimodel(ghost_frags, file_path)
    else:
        match_count = count(1)
        for ghost_frag, ijk in zip(ghost_frags, clusters):
            file_path = os.path.join(
                out_path, '{}_{}_{}_fragment_match_{}.pdb'.format(*ijk, next(match_count)))
            ghost_frag.representative.write(out_path=file_path)

    # frag_file = Path(out_path, putils.frag_text_file)
    # frag_file.unlink(missing_ok=True)  # Ensure old file is removed before new write
    # for match_count, (ghost_frag, surface_frag, match_score) in enumerate(ghost_mono_frag_pairs, 1):
    #     ijk = ghost_frag.ijk
    #     fragment_pdb, _ = ghost_frag.fragment_db.paired_frags[ijk]
    #     trnsfmd_fragment = fragment_pdb.get_transformed_copy(*ghost_frag.transformation)
    # write_frag_match_info_file(ghost_frag=ghost_frag, matched_frag=surface_frag,
    #                                     overlap_error=z_value_from_match_score(match_score),
    #                                     match_number=match_count, out_path=out_path)
    return file_path

debug_pose

debug_pose(out_dir: AnyStr = os.getcwd(), tag: str = None)

Write out all Structure objects for the Pose PDB

Source code in symdesign/structure/model.py
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
def debug_pose(self, out_dir: AnyStr = os.getcwd(), tag: str = None):
    """Write out all Structure objects for the Pose PDB"""
    entity_debug_path = os.path.join(out_dir, f'{f"{tag}_" if tag else ""}POSE_DEBUG_Entities_{self.name}.pdb')
    with open(entity_debug_path, 'w') as f:
        available_chain_ids = chain_id_generator()
        for entity_idx, entity in enumerate(self.entities, 1):
            # f.write(f'REMARK 999   Entity {entity_idx} - ID {entity.name}\n')
            # entity.write(file_handle=f, chain_id=next(available_chain_ids))
            for chain_idx, chain in enumerate(entity.chains, 1):
                f.write(f'REMARK 999   Entity {entity_idx} - ID {entity.name}   '
                        f'Chain {chain_idx} - ID {chain.chain_id}\n')
                chain.write(file_handle=f, chain_id=next(available_chain_ids))

    debug_path = os.path.join(out_dir, f'{f"{tag}_" if tag else ""}POSE_DEBUG_{self.name}.pdb')
    assembly_debug_path = os.path.join(out_dir, f'{f"{tag}_" if tag else ""}POSE_DEBUG_Assembly_{self.name}.pdb')

    self.log.critical(f'Wrote debugging Pose Entities to: {entity_debug_path}')
    self.write(out_path=debug_path)
    self.log.critical(f'Wrote debugging Pose to: {debug_path}')
    self.write(assembly=True, out_path=assembly_debug_path)
    self.log.critical(f'Wrote debugging Pose assembly to: {assembly_debug_path}')

softmax

softmax(x: ndarray) -> ndarray

Take the softmax operation from an input array

Parameters:

  • x (ndarray) –

    The array to calculate softmax on. Uses the axis=-1

Returns:

  • ndarray

    The array with a softmax performed

Source code in symdesign/structure/model.py
64
65
66
67
68
69
70
71
72
73
74
def softmax(x: np.ndarray) -> np.ndarray:
    """Take the softmax operation from an input array

    Args:
        x: The array to calculate softmax on. Uses the axis=-1

    Returns:
        The array with a softmax performed
    """
    input_exp = np.exp(x)
    return input_exp / input_exp.sum(axis=-1, keepdims=True)

split_residue_pairs

split_residue_pairs(interface_pairs: list[tuple[Residue, Residue]]) -> tuple[list[Residue], list[Residue]]

Used to split Residue pairs, take the set, then sort by Residue.number, and return pairs separated by index

Source code in symdesign/structure/model.py
77
78
79
80
81
82
83
84
def split_residue_pairs(interface_pairs: list[tuple[Residue, Residue]]) -> tuple[list[Residue], list[Residue]]:
    """Used to split Residue pairs, take the set, then sort by Residue.number, and return pairs separated by index"""
    if interface_pairs:
        residues1, residues2 = zip(*interface_pairs)
        return sorted(set(residues1), key=lambda residue: residue.number), \
            sorted(set(residues2), key=lambda residue: residue.number)
    else:
        return [], []

split_number_pairs_and_sort

split_number_pairs_and_sort(pairs: list[tuple[int, int]]) -> tuple[list, list]

Used to split integer pairs and sort, and return pairs separated by index

Source code in symdesign/structure/model.py
 96
 97
 98
 99
100
101
102
def split_number_pairs_and_sort(pairs: list[tuple[int, int]]) -> tuple[list, list]:
    """Used to split integer pairs and sort, and return pairs separated by index"""
    if pairs:
        numbers1, numbers2 = zip(*pairs)
        return sorted(set(numbers1), key=int), sorted(set(numbers2), key=int)
    else:
        return [], []

parse_cryst_record

parse_cryst_record(cryst_record: str) -> tuple[list[float], str]

Get the unit cell length, height, width, and angles alpha, beta, gamma and the space group

Parameters:

  • cryst_record (str) –

    The CRYST1 record as found in .pdb file format

Source code in symdesign/structure/model.py
105
106
107
108
109
110
111
112
113
114
115
116
117
def parse_cryst_record(cryst_record: str) -> tuple[list[float], str]:
    """Get the unit cell length, height, width, and angles alpha, beta, gamma and the space group

    Args:
        cryst_record: The CRYST1 record as found in .pdb file format
    """
    try:
        cryst, a, b, c, ang_a, ang_b, ang_c, *space_group = cryst_record.split()
        # a = [6:15], b = [15:24], c = [24:33], ang_a = [33:40], ang_b = [40:47], ang_c = [47:54]
    except ValueError:  # split() or unpacking went wrong
        a = b = c = ang_a = ang_b = ang_c = 0

    return list(map(float, [a, b, c, ang_a, ang_b, ang_c])), cryst_record[55:66].strip()