Core¶
Config¶
config
¶
logger = logging.getLogger(__name__)
module-attribute
¶
DEFAULT_CONFIG = {'outputDir': './results', 'inputType': 'pepxml', 'inputFile': [], 'decoyPrefix': 'DECOY_', 'visualization': True, 'saveModels': True, 'toFlashLFQ': True, 'allele': [], 'numProcesses': 4, 'removePreNxtAA': False, 'showProgress': True, 'logLevel': 'INFO', 'rescore': {'testFDR': 0.01, 'trainFDR': 0.01, 'model': 'Percolator', 'numJobs': 1}}
module-attribute
¶
Config(config_source=None)
¶
Configuration manager for optiMHC pipeline.
This class handles loading, validating, and providing access to configuration parameters from YAML files or dictionaries. It implements a fail-fast validation strategy to ensure configuration correctness before pipeline execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_source
|
str or dict or None
|
Path to YAML file, dictionary with configuration, or None for default config. If None, uses DEFAULT_CONFIG. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
_config |
dict
|
The internal configuration dictionary. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If configuration is invalid or required parameters are missing. |
FileNotFoundError
|
If specified YAML file does not exist. |
YAMLError
|
If YAML file is malformed. |
Examples:
>>> # Load from dictionary
>>> config_dict = {
... "inputType": "pepxml",
... "inputFile": ["data.pep.xml"],
... "outputDir": "./results",
... "rescore": {"testFDR": 0.01, "model": "Percolator"}
... }
>>> config = Config(config_dict)
>>> # Access configuration values
>>> input_type = config["inputType"]
>>> output_dir = config.get("outputDir", "./default")
Initialize Config from a YAML file path or a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_source
|
str or dict or None
|
Path to YAML file, dictionary with configuration, or None for default config. If None, uses DEFAULT_CONFIG. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If config_source is neither a string, dict, nor None. |
FileNotFoundError
|
If specified YAML file does not exist. |
YAMLError
|
If YAML file is malformed. |
Source code in optimhc/core/config.py
validate()
¶
Validate the configuration using a fail-fast strategy.
This method performs comprehensive validation of the configuration, including required fields, data types, file existence, and feature generator configurations.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any validation check fails. The error message will indicate the specific validation failure. |
Notes
The validation includes checks for: - Required fields (inputType, inputFile, outputDir, rescore) - Input file existence and type - Output directory creation - Rescore configuration validity (TODO) - Feature generator configuration primitive validity (TODO) - Optional parameter validity (TODO): we should validate 'allele' first !!!
Source code in optimhc/core/config.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
_deep_merge(default, override)
¶
Deep merge two dictionaries. The override dictionary values take precedence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
dict
|
Default dictionary. |
required |
override
|
dict
|
Dictionary with values to override defaults. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Merged dictionary. |
Source code in optimhc/core/config.py
load_config(config_path)
¶
Load and parse a configuration file using YAML. Merges loaded config with default configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str
|
Path to the YAML configuration file. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing all configurations. |
Source code in optimhc/core/config.py
Pipeline¶
pipeline
¶
rescore_model_factory = RescoreModelFactory()
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
Config(config_source=None)
¶
Configuration manager for optiMHC pipeline.
This class handles loading, validating, and providing access to configuration parameters from YAML files or dictionaries. It implements a fail-fast validation strategy to ensure configuration correctness before pipeline execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_source
|
str or dict or None
|
Path to YAML file, dictionary with configuration, or None for default config. If None, uses DEFAULT_CONFIG. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
_config |
dict
|
The internal configuration dictionary. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If configuration is invalid or required parameters are missing. |
FileNotFoundError
|
If specified YAML file does not exist. |
YAMLError
|
If YAML file is malformed. |
Examples:
>>> # Load from dictionary
>>> config_dict = {
... "inputType": "pepxml",
... "inputFile": ["data.pep.xml"],
... "outputDir": "./results",
... "rescore": {"testFDR": 0.01, "model": "Percolator"}
... }
>>> config = Config(config_dict)
>>> # Access configuration values
>>> input_type = config["inputType"]
>>> output_dir = config.get("outputDir", "./default")
Initialize Config from a YAML file path or a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_source
|
str or dict or None
|
Path to YAML file, dictionary with configuration, or None for default config. If None, uses DEFAULT_CONFIG. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If config_source is neither a string, dict, nor None. |
FileNotFoundError
|
If specified YAML file does not exist. |
YAMLError
|
If YAML file is malformed. |
Source code in optimhc/core/config.py
validate()
¶
Validate the configuration using a fail-fast strategy.
This method performs comprehensive validation of the configuration, including required fields, data types, file existence, and feature generator configurations.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any validation check fails. The error message will indicate the specific validation failure. |
Notes
The validation includes checks for: - Required fields (inputType, inputFile, outputDir, rescore) - Input file existence and type - Output directory creation - Rescore configuration validity (TODO) - Feature generator configuration primitive validity (TODO) - Optional parameter validity (TODO): we should validate 'allele' first !!!
Source code in optimhc/core/config.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
Pipeline(config)
¶
Main pipeline class for optiMHC, encapsulating the full data processing workflow.
This class orchestrates input parsing, feature generation, rescoring, result saving, and visualization. It supports both single-run and experiment modes (multiple feature/model combinations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
str, dict, or Config
|
Path to YAML config, dict, or Config object. |
required |
Examples:
Initialize the pipeline with a configuration file, dict, or Config object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
str, dict, or Config
|
Path to YAML config, dict, or Config object. |
required |
Source code in optimhc/core/pipeline.py
read_input()
¶
Read input PSMs based on configuration.
Returns:
| Type | Description |
|---|---|
PsmContainer
|
Object containing loaded PSMs. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If input type is unsupported. |
Exception
|
If file reading fails. |
Source code in optimhc/core/pipeline.py
rescore(psms, model_type=None, n_jobs=None, test_fdr=None, rescoring_features=None)
¶
Perform rescoring on the PSMs using the specified or configured model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
PSM container object. |
required |
model_type
|
str
|
Model type ('XGBoost', 'RandomForest', 'Percolator'). |
None
|
n_jobs
|
int
|
Number of parallel jobs. |
None
|
test_fdr
|
float
|
FDR threshold. List of features to use for rescoring. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
results |
Results
|
Rescoring results. |
models |
list
|
Trained models. |
Notes
Rescoring logic is adapted from mokapot (https://mokapot.readthedocs.io/)
Source code in optimhc/core/pipeline.py
save_results(psms, results, models, output_dir=None, file_root='optimhc')
¶
Save rescoring results, PSM data, and trained models to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
PSM container object. |
required |
results
|
Results
|
Rescoring results. |
required |
models
|
list
|
Trained models. |
required |
output_dir
|
str
|
Output directory. |
None
|
file_root
|
str
|
Root name for output files. |
'optimhc'
|
Source code in optimhc/core/pipeline.py
visualize_results(psms, results, models, output_dir=None, sources=None)
¶
Generate and save visualizations for the analysis results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
PSM container object. |
required |
results
|
Results
|
Rescoring results. |
required |
models
|
list
|
Trained models. |
required |
output_dir
|
str
|
Output directory. |
None
|
sources
|
list
|
Feature sources to include in visualizations. |
None
|
Source code in optimhc/core/pipeline.py
run()
¶
Run the complete optiMHC pipeline (single run mode).
This method executes the full workflow: input parsing, feature generation, rescoring, saving, and visualization.
Returns:
| Name | Type | Description |
|---|---|---|
psms |
PsmContainer
|
PSM container object. |
results |
Results
|
Rescoring results. |
models |
list
|
Trained models. |
Source code in optimhc/core/pipeline.py
run_experiments()
¶
Run experiments with different feature/model combinations using multiprocessing.
Each experiment is executed in its own process for complete resource isolation. The experiment configurations must be provided in the config under the 'experiments' key.
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in optimhc/core/pipeline.py
generate_features(psms, config)
¶
Generate features from different generators according to the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
A container object holding PSMs and relevant data. |
required |
config
|
dict
|
Configuration dictionary loaded from YAML or CLI. |
required |
Source code in optimhc/core/feature_generation.py
read_pepxml(pepxml_files, decoy_prefix='DECOY_')
¶
Read PSMs from a list of PepXML files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pepxml_files
|
Union[str, List[str]]
|
The file path to the PepXML file or a list of file paths. |
required |
decoy_prefix
|
str
|
The prefix used to indicate a decoy protein in the description lines of the FASTA file. Default is "DECOY_". |
'DECOY_'
|
Returns:
| Type | Description |
|---|---|
PsmContainer
|
A PsmContainer object containing the PSM data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the PepXML files were generated by Percolator or PeptideProphet. |
Notes
This function: 1. Reads and parses PepXML files 2. Calculates mass difference features 3. Processes matched ions and complementary ions 4. Creates charge columns 5. Log-transforms p-values 6. Returns a PsmContainer with the processed data
Source code in optimhc/parser/pepxml.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
read_pin(pin_files, retention_time_column=None, remove_pre_nxt_aa=False)
¶
Read PSMs from a Percolator INput (PIN) file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pin_files
|
Union[str, List[str]]
|
The file path to the PIN file or a list of file paths. |
required |
retention_time_column
|
Optional[str]
|
The column containing the retention time. If None, no retention time will be included. |
None
|
Returns:
| Type | Description |
|---|---|
PsmContainer
|
A PsmContainer object containing the PSM data. |
Notes
This function: 1. Reads PIN file(s) into a DataFrame 2. Identifies required columns (case-insensitive) 3. Processes scan IDs and hit ranks (Only support FragPipe PIN) 4. Converts data types appropriately 5. Creates a PsmContainer with the processed data
Source code in optimhc/parser/pin.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
plot_feature_importance(models, rescoring_features, save_path=None, sort=False, error=False, **kwargs)
¶
Unified function to plot average feature importance across multiple models.
This function supports: - Linear models (e.g., Linear SVR) which provide an 'estimator' attribute with a 'coef_'. The absolute value of the coefficients is used for importance, and hatch patterns are applied to differentiate between positive and negative coefficients. - XGBoost models which provide a 'feature_importances_' attribute. Since these values are always positive, no hatch patterns are applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list
|
A list of model objects. For linear models, each model should have an 'estimator' with 'coef_'. For XGBoost models, each model should have a 'feature_importances_' attribute. |
required |
rescoring_features
|
dict
|
A dictionary where keys are sources and values are lists of features. |
required |
save_path
|
str
|
If provided, saves the plot to the specified path. |
None
|
sort
|
bool
|
If True, sorts the features by their importance in descending order. Default is False. |
False
|
error
|
bool
|
If True, adds error bars to the plot. Default is False. |
False
|
**kwargs
|
dict
|
Additional plotting parameters: - 'figsize' : tuple, default (15, 10) Figure size in inches (width, height). - 'dpi' : int, default 300 Resolution in dots per inch. - 'palette' : str, default 'crest' Seaborn color palette name. Options include 'crest', 'flare', 'mako', 'rocket', 'tab10', 'husl', 'Set2', etc. |
{}
|
Notes
The function automatically detects the model type based on the presence of the corresponding attribute. For linear models, it uses hatch patterns to differentiate between positive and negative coefficients. For XGBoost models, it uses solid bars since the importances are always positive.
The color palette is automatically scaled to match the number of feature sources, ensuring consistent colors between the bars and legend.
Examples:
>>> # Use default crest palette
>>> plot_feature_importance(models, rescoring_features, save_path='importance.png')
>>> # Use a different palette
>>> plot_feature_importance(models, rescoring_features, palette='flare', sort=True, error=True)
Source code in optimhc/visualization/plot_features.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
plot_qvalues(results, save_path=None, dpi=300, figsize=(15, 10), threshold=0.05, colors=None, **kwargs)
¶
Plot q-values for the given results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
object or list
|
A list of results objects or a single result object.
Each result object should have a method |
required |
save_path
|
str
|
If provided, saves the plot to the specified path. |
None
|
dpi
|
int
|
The resolution of the plot. Default is 300. |
300
|
figsize
|
tuple
|
The size of the figure. Default is (15, 10). |
(15, 10)
|
threshold
|
float
|
The q-value threshold for plotting. Default is 0.05. |
0.05
|
colors
|
list
|
A list of colors for the plots. If not provided, uses default colors. |
None
|
**kwargs
|
dict
|
Additional plotting parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
The function displays or saves the plot. |
Notes
This function: 1. Creates a figure with two subplots for PSMs and peptides 2. Plots q-values for each result with different colors 3. Adds legends and titles to each subplot 4. Saves or displays the plot based on save_path
Source code in optimhc/visualization/plot_roc.py
visualize_feature_correlation(psms, save_path=None, **kwargs)
¶
Visualize the correlation between features in a DataFrame using a scatter plot heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
A PsmContainer object containing the features to visualize. |
required |
save_path
|
str
|
The file path to save the plot. If not provided, the plot is displayed. |
None
|
**kwargs
|
dict
|
Additional plotting parameters such as |
{}
|
Source code in optimhc/visualization/plot_features.py
visualize_target_decoy_features(psms, num_cols=5, save_path=None, **kwargs)
¶
Visualize the distribution of features in a DataFrame using kernel density estimation plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
A PsmContainer object containing the features to visualize. |
required |
num_cols
|
int
|
The number of columns in the plot grid. Default is 5. |
5
|
save_path
|
str
|
The file path to save the plot. If not provided, the plot is displayed. |
None
|
**kwargs
|
dict
|
Additional plotting parameters such as |
{}
|
Notes
This function: 1. Extracts rescoring features from the PsmContainer 2. Filters out features with only one unique value 3. Creates a grid of plots showing the distribution of each feature 4. Separates target and decoy PSMs in each plot 5. Uses kernel density estimation to show the distribution shape
Source code in optimhc/visualization/plot_tdc_distribution.py
Feature Generation¶
feature_generation
¶
feature_generator_factory = FeatureGeneratorFactory()
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
generate_features(psms, config)
¶
Generate features from different generators according to the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
PsmContainer
|
A container object holding PSMs and relevant data. |
required |
config
|
dict
|
Configuration dictionary loaded from YAML or CLI. |
required |
Source code in optimhc/core/feature_generation.py
PSM Container¶
psm_container
¶
logger = logging.getLogger(__name__)
module-attribute
¶
PsmContainer(psms, label_column, scan_column, spectrum_column, ms_data_file_column, peptide_column, protein_column, rescoring_features, hit_rank_column=None, charge_column=None, retention_time_column=None, calculated_mass_column=None, metadata_column=None)
¶
A container for managing peptide-spectrum matches (PSMs) in immunopeptidomics rescoring pipelines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
DataFrame
|
DataFrame containing the PSM data. |
required |
label_column
|
str
|
Column containing the label (True for target, False for decoy). |
required |
scan_column
|
str
|
Column containing the scan number. |
required |
spectrum_column
|
str
|
Column containing the spectrum identifier. |
required |
ms_data_file_column
|
str
|
Column containing the MS data file that the PSM originated from. |
required |
peptide_column
|
str
|
Column containing the peptide sequence. |
required |
protein_column
|
str
|
Column containing the protein accessions. |
required |
rescoring_features
|
dict of str to list of str
|
Dictionary of feature columns for rescoring. |
required |
hit_rank_column
|
str
|
Column containing the hit rank. |
None
|
charge_column
|
str
|
Column containing the charge state. |
None
|
retention_time_column
|
str
|
Column containing the retention time. |
None
|
calculated_mass_column
|
str
|
Column containing the calculated mass. |
None
|
metadata_column
|
str
|
Column containing metadata. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
psms |
DataFrame
|
Copy of the DataFrame containing the PSM data. |
target_psms |
DataFrame
|
DataFrame containing only target PSMs (label = True). |
decoy_psms |
DataFrame
|
DataFrame containing only decoy PSMs (label = False). |
peptides |
list of str
|
List containing all peptides from the PSM data. |
columns |
list of str
|
List of column names in the PSM DataFrame. |
rescoring_features |
dict of str to list of str
|
Dictionary of rescoring feature columns in the PSM DataFrame. |
Source code in optimhc/psm_container.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
psms
property
¶
Get a copy of the PSM DataFrame to prevent external modification.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A copy of the PSM DataFrame. |
target_psms
property
¶
Get a DataFrame containing only target PSMs.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with only target PSMs (label = True). |
decoy_psms
property
¶
Get a DataFrame containing only decoy PSMs.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with only decoy PSMs (label = False). |
columns
property
¶
Get the column names of the PSM DataFrame.
Returns:
| Type | Description |
|---|---|
list of str
|
List of column names. |
feature_columns
property
¶
Get a list of all feature columns in the PSM DataFrame.
Returns:
| Type | Description |
|---|---|
list of str
|
List of feature column names. |
feature_sources
property
¶
Get a list of all feature sources in the PSM DataFrame.
Returns:
| Type | Description |
|---|---|
list of str
|
List of feature source names. |
peptides
property
¶
Get the peptide sequences from the PSM data.
Returns:
| Type | Description |
|---|---|
list of str
|
List of peptide sequences. |
ms_data_files
property
¶
Get the MS data files from the PSM data.
Returns:
| Type | Description |
|---|---|
list of str
|
List of MS data file names. |
scan_ids
property
¶
Get the scan numbers from the PSM data.
Returns:
| Type | Description |
|---|---|
list of int
|
List of scan numbers. |
charges
property
¶
Get the charge states from the PSM data.
Returns:
| Type | Description |
|---|---|
list of int
|
List of charge states. |
metadata
property
¶
Get the metadata from the PSM data.
Returns:
| Type | Description |
|---|---|
Series
|
Series containing metadata for each PSM. |
spectrum_ids
property
¶
Get the spectrum identifiers from the PSM data.
Returns:
| Type | Description |
|---|---|
list of str
|
List of spectrum identifiers. |
identifier_columns
property
¶
Get the columns that uniquely identify each PSM.
Returns:
| Type | Description |
|---|---|
list of str
|
List of identifier column names. |
__len__()
¶
copy()
¶
Return a deep copy of the PsmContainer object.
Returns:
| Type | Description |
|---|---|
PsmContainer
|
A deep copy of the current PsmContainer. |
__repr__()
¶
Return a string representation of the PsmContainer.
Returns:
| Type | Description |
|---|---|
str
|
String summary of the PsmContainer. |
Source code in optimhc/psm_container.py
drop_features(features)
¶
Drop specified features from the PSM DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
list of str
|
List of feature column names to drop. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any of the features do not exist in the DataFrame. |
Source code in optimhc/psm_container.py
drop_source(source)
¶
Drop all features associated with a specific source from the PSM DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Name of the source to drop. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the source does not exist in the rescoring features. |
Source code in optimhc/psm_container.py
add_metadata(metadata_df, psms_key, metadata_key, source)
¶
Merge new metadata into the PSM DataFrame based on specified columns. Metadata from the specified source is stored as a nested dictionary inside the metadata column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_df
|
DataFrame
|
DataFrame containing new metadata to add. |
required |
psms_key
|
str or list of str
|
Column name(s) in the PSM data to merge on. |
required |
metadata_key
|
str or list of str
|
Column name(s) in the metadata data to merge on. |
required |
source
|
str
|
Name of the source of the new metadata. |
required |
Source code in optimhc/psm_container.py
get_top_hits(n=1)
¶
Get the top n hits based on the hit rank column. If the hit rank column is not specified, returns the original PSMs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of top hits to return. Default is 1. |
1
|
Returns:
| Type | Description |
|---|---|
PsmContainer
|
A new PsmContainer object containing the top n hits. |
Source code in optimhc/psm_container.py
add_features(features_df, psms_key, feature_key, source, suffix=None)
¶
Merge new features into the PSM DataFrame based on specified columns.
This method performs a left join between the PSM data and feature data, ensuring that all PSMs are preserved while adding new features. It handles column name conflicts through optional suffixing and maintains feature source tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features_df
|
DataFrame
|
DataFrame containing new features to add. |
required |
psms_key
|
str or list of str
|
Column name(s) in the PSM data to merge on. |
required |
feature_key
|
str or list of str
|
Column name(s) in the features data to merge on. |
required |
source
|
str
|
Name of the source of the new features (e.g., 'deeplc', 'netmhc'). |
required |
suffix
|
str
|
Suffix to add to the new columns if there's a name conflict. Required when new feature columns have the same names as existing columns. For example, if adding features from different sources (e.g., 'score' from DeepLC and NetMHC), use suffixes like '_deeplc' or '_netmhc' to distinguish them. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If duplicate columns exist without suffix. If merging features changes the number of PSMs. |
Notes
The method follows these steps: 1. Validates input and prepares merge keys 2. Checks for column name conflicts 3. Manages feature source: if the source already exists, it will be overwritten 4. Performs left join merge 5. Verifies data integrity
Suffix Usage
The suffix parameter is used to handle column name conflicts: - When adding features from different sources that might have the same column names - When you want to keep both the original and new features with the same name - When you need to track the source of features in the column names
If suffix is not provided and there are duplicate column names: - The method will raise a ValueError - You must either provide a suffix or rename the columns before adding
Examples:
>>> container = PsmContainer(...)
>>> # Adding features without suffix (no conflicts)
>>> features_df1 = pd.DataFrame({
... 'scan': [1, 2, 3],
... 'feature1': [0.1, 0.2, 0.3],
... 'feature2': [0.4, 0.5, 0.6]
... })
>>> container.add_features(
... features_df1,
... psms_key='scan',
... feature_key='scan',
... source='source1'
... )
>>> # Adding features with suffix (handling conflicts)
>>> features_df2 = pd.DataFrame({
... 'scan': [1, 2, 3],
... 'score': [0.8, 0.9, 0.7], # This would conflict with existing 'score'
... 'feature3': [0.7, 0.8, 0.9]
... })
>>> container.add_features(
... features_df2,
... psms_key='scan',
... feature_key='scan',
... source='source2',
... suffix='_new' # 'score' becomes 'score_new'
... )
Source code in optimhc/psm_container.py
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | |
add_features_by_index(features_df, source, suffix=None)
¶
Merge new features into the PSM DataFrame based on the DataFrame index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features_df
|
DataFrame
|
DataFrame containing new features to add. |
required |
source
|
str
|
Name of the source of the new features. |
required |
suffix
|
str
|
Suffix to add to the new columns if there's a name conflict. |
None
|
Source code in optimhc/psm_container.py
add_results(results_df, psms_key, result_key)
¶
Add results of rescore engine to the PSM DataFrame based on specified columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df
|
DataFrame
|
DataFrame containing new results to add. |
required |
psms_key
|
str or list of str
|
Column name(s) in the PSM data to merge on. |
required |
result_key
|
str or list of str
|
Column name(s) in the results data to merge on. |
required |
Source code in optimhc/psm_container.py
write_pin(output_file, style='default', source=None)
¶
Write the PSM data to a Percolator PIN file, supporting both generic Percolator and MSBooster-compatible formats. The style parameter is actually used to output a unified pin format file to benchmark the performance of different rescoring methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_file
|
str
|
Path to the output PIN file. |
required |
style
|
str
|
If set to 'msbooster', outputs only the columns required by MSBooster (SpecId, Label, ScanNr, retentiontime, rank, hyperscore or log10_evalue, Peptide, Proteins).
If set to 'default', outputs all features specified in |
'default'
|
source
|
list of str
|
List of feature sources to include. If None, includes all sources. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The DataFrame written to the PIN file. |
Notes
- The first three columns are always: SpecID, Label, ScanNr.
- For 'msbooster' style, the columns are: SpecId, Label, ScanNr, retentiontime, rank, hyperscore or log10_evalue, Peptide, Proteins.
- If
hit_rank_columnis not specified, rank is set to 1 for all rows. - Either 'hyperscore' or 'expect' must be present in features; for 'expect', the column is written as 'log10_evalue'.
- The 'log10_evalue' column should contain the base-10 logarithm of the e-value.
- The 'Peptide' column is formatted with underscores (e.g.,
_.PEPTIDE._). - For standard format, all features from
rescoring_featuresare appended between ScanNr and Peptide columns. - The 'Proteins' column is a semicolon-separated list if stored as a list or tuple.
- Label column is converted to 1 (target) and -1 (decoy), as required by Percolator.
Example output (default style): SpecId Label ScanNr feature1 feature2 ... Peptide Proteins
Example output (msbooster style): SpecId Label ScanNr retentiontime rank hyperscore Peptide Proteins or SpecId Label ScanNr retentiontime rank log10_evalue Peptide Proteins
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns are missing for the selected style. |
Source code in optimhc/psm_container.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 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 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
Utilities¶
utils
¶
logger = getLogger(__name__)
module-attribute
¶
convert_pfm_to_pwm(pfm_filename, pseudocount=0.8, background_freqs=None)
¶
Convert a Position Frequency Matrix (PFM) file to a Position Weight Matrix (PWM).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pfm_filename
|
str
|
The file path to the PFM file. |
required |
pseudocount
|
float
|
The pseudocount to add to the PFM to avoid zero probabilities. Default is 0.8. |
0.8
|
background_freqs
|
dict
|
Dictionary containing the background frequencies for each amino acid. If None, uses 1/20 for all. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame representation of the PWM. |
Notes
The conversion process involves: 1. Adding pseudocounts to the PFM 2. Converting to Position Probability Matrix (PPM) 3. Converting to PWM using log2(PPM/background_freqs)
Source code in optimhc/utils.py
strip_flanking_and_charge(peptide)
¶
Remove the pre and next amino acids from a peptide sequence. Also when there is a charge state at the end of the peptide, remove it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptide
|
str
|
The peptide sequence with flanking amino acids. Example: '.AANDAGYFNDEMAPIEVKTK.' Example: 'F.VTVQGRAIC[119.0041]SDPNNKRVKN4.A' Example: '-.RRVEHHDHAVVSGR4.L' |
required |
Returns:
| Type | Description |
|---|---|
str
|
The peptide sequence with flanking amino acids removed. Example: 'AANDAGYFNDEMAPIEVKTK' Example: 'VTVQGRAIC[119.0041]SDPNNKRVKN' Example: 'RRVEHHDHAVVSGR' |
Notes
This function removes any amino acids before the first '.' and after the last '.' in the peptide sequence.
Source code in optimhc/utils.py
remove_modifications(peptide, keep_modification=None)
¶
Remove modifications from a peptide sequence, with an option to keep specific modifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptide
|
str
|
The peptide sequence with modifications in brackets. Example: 'AANDAGYFNDEM[15.9949]APIEVK[42.0106]TK' |
required |
keep_modification
|
str or list
|
The modification(s) to keep. If provided, only these modifications will be preserved in the output sequence. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The peptide sequence with modifications removed or kept. Example: 'AANDAGYFNDEMAPIEVKTK' (if keep_modification is None) Example: 'AANDAGYFNDEM[15.9949]APIEVKTK' (if keep_modification=['15.9949']) |
Notes
Modifications are specified in square brackets after the amino acid. If keep_modification is provided, only those specific modifications will be preserved in the output sequence.
Source code in optimhc/utils.py
preprocess_peptide(peptide)
¶
Preprocess the peptide sequence by removing flanking regions and modifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptide
|
str
|
Original peptide sequence with possible flanking regions and modifications. Example: '.AANDAGYFNDEM[15.9949]APIEVK[42.0106]TK.' |
required |
Returns:
| Type | Description |
|---|---|
str
|
Cleaned peptide sequence without flanking regions and modifications. Example: 'AANDAGYFNDEMAPIEVKTK' |
Notes
This function performs two operations in sequence: 1. Removes flanking amino acids using remove_pre_and_nxt_aa 2. Removes all modifications using remove_modifications
Source code in optimhc/utils.py
list_all_files_in_directory(directory_path)
¶
Retrieve all files in the specified directory and return a list of file paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
str
|
The path to the directory to search in. Example: '/path/to/directory' |
required |
Returns:
| Type | Description |
|---|---|
list of str
|
List of absolute file paths found in the directory and its subdirectories. Example: ['/path/to/directory/file1.txt', '/path/to/directory/subdir/file2.txt'] |
Notes
This function recursively searches through all subdirectories and returns absolute paths for all files found.
Source code in optimhc/utils.py
extract_unimod_from_peptidoform(peptide, mod_dict)
¶
Convert a modified peptide sequence into DeepLC format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptide
|
str
|
The input peptide sequence with modifications in brackets. Example: 'AANDAGYFNDEM[15.9949]APIEVK[42.0106]TK' |
required |
mod_dict
|
dict
|
Dictionary mapping modification names (in peptide) to corresponding Unimod names. Example: {'15.9949': 'Oxidation', '42.0106': 'Acetyl'} |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
(seq, modifications):
seq : str
The unmodified peptide sequence.
modifications : str
String of modifications formatted as |
Source code in optimhc/utils.py
convert_to_unimod_format(peptide, mod_dict)
¶
Convert a modified peptide sequence into Unimod format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptide
|
str
|
The input peptide sequence with modifications in brackets. Example: 'AANDAGYFNDEM[15.9949]APIEVK[42.0106]TK' |
required |
mod_dict
|
dict
|
Dictionary mapping modification names (in peptide) to corresponding Unimod names. Example: {'15.9949': 'UNIMOD:4', '42.0106': 'UNIMOD:1'} |
required |
Returns:
| Type | Description |
|---|---|
str
|
The peptide sequence formatted for Unimod. Example: 'AANDAGYFNDEM[UNIMOD:4]APIEVK[UNIMOD:1]TK' |
Notes
This function replaces the modification names in brackets with their corresponding Unimod identifiers while preserving the peptide sequence structure.