Visualization¶
visualization
¶
__all__ = ['plot_feature_importance', 'visualize_target_decoy_features', 'visualize_feature_correlation', 'save_or_show_plot', 'plot_qvalues']
module-attribute
¶
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 | |
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
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_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
Q-value Plots¶
plot_roc
¶
logger = logging.getLogger(__name__)
module-attribute
¶
save_or_show_plot(save_path, logger, tight_layout=True)
¶
Source code in optimhc/visualization/save_or_show_plot.py
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
Feature Plots¶
plot_features
¶
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 | |
save_or_show_plot(save_path, logger, tight_layout=True)
¶
Source code in optimhc/visualization/save_or_show_plot.py
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 | |
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
Target/Decoy Distribution¶
plot_tdc_distribution
¶
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 | |
save_or_show_plot(save_path, logger, tight_layout=True)
¶
Source code in optimhc/visualization/save_or_show_plot.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