|
| 1 | +# aide_predict/bespoke_models/embedders/aa_properties.py |
| 2 | +''' |
| 3 | +* Author: Evan Komp |
| 4 | +* Created: 11/24/2024 |
| 5 | +* Company: National Renewable Energy Lab, Bioeneergy Science and Technology |
| 6 | +* License: MIT |
| 7 | +
|
| 8 | +Simple amino acid property embedder for testing position-specific functionality. |
| 9 | +''' |
| 10 | +import numpy as np |
| 11 | +from typing import List, Union, Optional |
| 12 | + |
| 13 | +from aide_predict.bespoke_models.base import ( |
| 14 | + ProteinModelWrapper, |
| 15 | + PositionSpecificMixin, |
| 16 | + CanHandleAlignedSequencesMixin, |
| 17 | + ExpectsNoFitMixin |
| 18 | +) |
| 19 | +from aide_predict.utils.data_structures import ProteinSequences, ProteinSequence |
| 20 | +from aide_predict.utils.common import MessageBool |
| 21 | + |
| 22 | +import logging |
| 23 | +logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | +AVAILABLE = MessageBool(True, "AAPropertiesEmbedding is always available") |
| 26 | + |
| 27 | + |
| 28 | +# Simple physicochemical properties for the 20 standard amino acids |
| 29 | +AA_PROPERTIES = { |
| 30 | + 'A': [1.8, 0.0, 0.0], # Alanine: hydrophobicity, charge, size |
| 31 | + 'C': [2.5, 0.0, 0.0], # Cysteine |
| 32 | + 'D': [-3.5, -1.0, 0.0], # Aspartic acid |
| 33 | + 'E': [-3.5, -1.0, 0.5], # Glutamic acid |
| 34 | + 'F': [2.8, 0.0, 1.0], # Phenylalanine |
| 35 | + 'G': [-0.4, 0.0, -1.0], # Glycine |
| 36 | + 'H': [-3.2, 0.5, 0.5], # Histidine |
| 37 | + 'I': [4.5, 0.0, 0.5], # Isoleucine |
| 38 | + 'K': [-3.9, 1.0, 0.5], # Lysine |
| 39 | + 'L': [3.8, 0.0, 0.5], # Leucine |
| 40 | + 'M': [1.9, 0.0, 0.5], # Methionine |
| 41 | + 'N': [-3.5, 0.0, 0.0], # Asparagine |
| 42 | + 'P': [-1.6, 0.0, 0.0], # Proline |
| 43 | + 'Q': [-3.5, 0.0, 0.5], # Glutamine |
| 44 | + 'R': [-4.5, 1.0, 1.0], # Arginine |
| 45 | + 'S': [-0.8, 0.0, -0.5], # Serine |
| 46 | + 'T': [-0.7, 0.0, 0.0], # Threonine |
| 47 | + 'V': [4.2, 0.0, 0.0], # Valine |
| 48 | + 'W': [-0.9, 0.0, 1.5], # Tryptophan |
| 49 | + 'Y': [-1.3, 0.0, 1.0], # Tyrosine |
| 50 | +} |
| 51 | + |
| 52 | + |
| 53 | +class AAPropertiesEmbedding( |
| 54 | + ExpectsNoFitMixin, |
| 55 | + PositionSpecificMixin, |
| 56 | + CanHandleAlignedSequencesMixin, |
| 57 | + ProteinModelWrapper |
| 58 | +): |
| 59 | + """ |
| 60 | + A simple amino acid property embedder for testing position-specific functionality. |
| 61 | + |
| 62 | + This embedder converts each amino acid to a 3-dimensional vector based on: |
| 63 | + - Hydrophobicity (Kyte-Doolittle scale approximation) |
| 64 | + - Charge (at physiological pH) |
| 65 | + - Size (relative volume) |
| 66 | + |
| 67 | + This is a simple, fast embedder that can handle aligned sequences with gaps |
| 68 | + and is useful for testing the PositionSpecificMixin functionality. |
| 69 | + |
| 70 | + Attributes: |
| 71 | + positions (Optional[List[int]]): Specific positions to encode. If None, all positions are encoded. |
| 72 | + pool (bool): Whether to pool the encoded vectors across positions. |
| 73 | + flatten (bool): Whether to flatten the output array. |
| 74 | + handle_aligned (bool): Whether to handle aligned sequences with gaps. |
| 75 | + gap_fill_value (float): Value to use for gap positions. |
| 76 | + """ |
| 77 | + |
| 78 | + _available = AVAILABLE |
| 79 | + |
| 80 | + def __init__( |
| 81 | + self, |
| 82 | + metadata_folder: str = None, |
| 83 | + positions: Optional[List[int]] = None, |
| 84 | + flatten: bool = False, |
| 85 | + pool: bool = False, |
| 86 | + handle_aligned: bool = True, |
| 87 | + gap_fill_value: float = 0.0, |
| 88 | + wt: Optional[Union[str, ProteinSequence]] = None, |
| 89 | + **kwargs |
| 90 | + ): |
| 91 | + """ |
| 92 | + Initialize the AAPropertiesEmbedding. |
| 93 | +
|
| 94 | + Args: |
| 95 | + metadata_folder (str): The folder where metadata is stored. |
| 96 | + positions (Optional[List[int]]): Specific positions to encode. If None, all positions are encoded. |
| 97 | + flatten (bool): Whether to flatten the output array. |
| 98 | + pool (bool): Whether to pool the encoded vectors across positions. |
| 99 | + handle_aligned (bool): Whether to handle aligned sequences with gaps. |
| 100 | + gap_fill_value (float): Value to use for gap positions. |
| 101 | + wt (Optional[Union[str, ProteinSequence]]): The wild type sequence, if any. |
| 102 | + """ |
| 103 | + super().__init__( |
| 104 | + metadata_folder=metadata_folder, |
| 105 | + wt=wt, |
| 106 | + positions=positions, |
| 107 | + pool=pool, |
| 108 | + flatten=flatten, |
| 109 | + handle_aligned=handle_aligned, |
| 110 | + gap_fill_value=gap_fill_value, |
| 111 | + **kwargs |
| 112 | + ) |
| 113 | + self.embedding_dim_ = 3 # 3 properties per amino acid |
| 114 | + |
| 115 | + def _fit(self, X: ProteinSequences, y: Optional[np.ndarray] = None) -> 'AAPropertiesEmbedding': |
| 116 | + """ |
| 117 | + Fit the embedder (no actual fitting needed as properties are predefined). |
| 118 | +
|
| 119 | + Args: |
| 120 | + X (ProteinSequences): The input protein sequences. |
| 121 | + y (Optional[np.ndarray]): Ignored. Present for API consistency. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + AAPropertiesEmbedding: The fitted embedder. |
| 125 | + """ |
| 126 | + self.fitted_ = True |
| 127 | + return self |
| 128 | + |
| 129 | + def _transform(self, X: ProteinSequences) -> List[np.ndarray]: |
| 130 | + """ |
| 131 | + Transform the protein sequences into amino acid property embeddings. |
| 132 | +
|
| 133 | + Args: |
| 134 | + X (ProteinSequences): The input protein sequences. |
| 135 | +
|
| 136 | + Returns: |
| 137 | + List[np.ndarray]: The amino acid property embeddings for the sequences. |
| 138 | + """ |
| 139 | + all_embeddings = [] |
| 140 | + |
| 141 | + for seq in X: |
| 142 | + seq_str = str(seq).upper() |
| 143 | + seq_len = len(seq_str) |
| 144 | + |
| 145 | + # Create embedding matrix: (seq_len, 3) |
| 146 | + embedding = np.zeros((1, seq_len, 3), dtype=np.float32) |
| 147 | + |
| 148 | + for i, aa in enumerate(seq_str): |
| 149 | + if aa in AA_PROPERTIES: |
| 150 | + embedding[0, i, :] = AA_PROPERTIES[aa] |
| 151 | + else: |
| 152 | + # Unknown amino acid - use zeros |
| 153 | + logger.warning(f"Unknown amino acid '{aa}' in sequence {seq.id}, using zeros") |
| 154 | + embedding[0, i, :] = [0.0, 0.0, 0.0] |
| 155 | + |
| 156 | + all_embeddings.append(embedding) |
| 157 | + |
| 158 | + # Return as list - PositionSpecificMixin will handle position selection, pooling, and alignment remapping |
| 159 | + return all_embeddings |
| 160 | + |
| 161 | + def get_feature_names_out(self, input_features: Optional[List[str]] = None) -> List[str]: |
| 162 | + """ |
| 163 | + Get output feature names for transformation. |
| 164 | +
|
| 165 | + Args: |
| 166 | + input_features (Optional[List[str]]): Ignored. Present for API consistency. |
| 167 | +
|
| 168 | + Returns: |
| 169 | + List[str]: Output feature names. |
| 170 | + """ |
| 171 | + if not hasattr(self, 'fitted_'): |
| 172 | + raise ValueError("Model has not been fitted yet. Call fit() before using this method.") |
| 173 | + |
| 174 | + positions = self.positions |
| 175 | + property_names = ['hydrophobicity', 'charge', 'size'] |
| 176 | + |
| 177 | + if self.pool: |
| 178 | + return [f"AAProps_{prop}" for prop in property_names] |
| 179 | + elif self.flatten: |
| 180 | + if positions is None: |
| 181 | + raise ValueError("Cannot return feature names for flattened embeddings without specifying positions") |
| 182 | + return [f"pos{p}_{prop}" for p in positions for prop in property_names] |
| 183 | + else: |
| 184 | + raise ValueError("Cannot return feature names for non-flattened non-pooled embeddings.") |
0 commit comments