|
| 1 | +""" |
| 2 | +This module provides functionality for handling and processing quantitative datapoints in the ProteoBench framework. |
| 3 | +""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import dataclasses |
| 8 | +import hashlib |
| 9 | +import logging |
| 10 | +from collections import ChainMap, defaultdict |
| 11 | +from dataclasses import dataclass |
| 12 | +from datetime import datetime |
| 13 | +from typing import Any, Dict |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +import pandas as pd |
| 17 | + |
| 18 | +import proteobench |
| 19 | +from proteobench.datapoint.datapoint_base import DatapointBase |
| 20 | +from proteobench.score.entrapmentscores import EntrapmentScores |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class EntrapmentDatapoint(DatapointBase): |
| 25 | + """ |
| 26 | + A data structure used to store the results of a entrapment benchmark run. |
| 27 | +
|
| 28 | + This class extends DatapointBase to implement entrapment-specific metrics and metadata |
| 29 | + storage for LFQ benchmarking runs. |
| 30 | +
|
| 31 | + Attributes: |
| 32 | + id (str): Unique identifier for the benchmark run. |
| 33 | + software_name (str): Name of the software used in the benchmark. |
| 34 | + software_version (str): Version of the software. |
| 35 | + search_engine (str): Name of the search engine used. |
| 36 | + search_engine_version (str): Version of the search engine. |
| 37 | + ident_fdr_psm (float): False discovery rate for PSMs. |
| 38 | + ident_fdr_peptide (float): False discovery rate for peptides. |
| 39 | + ident_fdr_protein (float): False discovery rate for proteins. |
| 40 | + enable_match_between_runs (bool): Whether matching between runs is enabled. |
| 41 | + precursor_mass_tolerance (str): Mass tolerance for precursor ions. |
| 42 | + fragment_mass_tolerance (str): Mass tolerance for fragment ions. |
| 43 | + enzyme (str): Enzyme used for digestion. |
| 44 | + allowed_miscleavages (int): Number of allowed miscleavages. |
| 45 | + min_peptide_length (int): Minimum peptide length. |
| 46 | + max_peptide_length (int): Maximum peptide length. |
| 47 | + is_temporary (bool): Whether the data is temporary. |
| 48 | + intermediate_hash (str): Hash of the intermediate result. |
| 49 | + results (dict): A dictionary of metrics for the benchmark run. |
| 50 | + nr_id_features (int): Number of identified features. |
| 51 | + lower_bound_FDP (float): estimated false discovery proportion based on entrapment IDs. |
| 52 | + combined_FDP (float): estimated False discovery proportion based on entrapment IDs. |
| 53 | + paired_FDP (float): estimated False discovery proportion based on entrapment IDs. |
| 54 | + reported_fdr_parsed_from_input (float): FDR threshold inferred from the input data (max Q-value). |
| 55 | + comments (str): Any additional comments. |
| 56 | + proteobench_version (str): Version of the Proteobench tool used. |
| 57 | + """ |
| 58 | + |
| 59 | + id: str = None |
| 60 | + software_name: str = None |
| 61 | + software_version: int = 0 |
| 62 | + search_engine: str = None |
| 63 | + search_engine_version: int = 0 |
| 64 | + ident_fdr_psm: int = 0 |
| 65 | + ident_fdr_peptide: int = 0 |
| 66 | + ident_fdr_protein: int = 0 |
| 67 | + enable_match_between_runs: bool = False |
| 68 | + precursor_mass_tolerance: str = None |
| 69 | + fragment_mass_tolerance: str = None |
| 70 | + enzyme: str = None |
| 71 | + allowed_miscleavages: int = 0 |
| 72 | + min_peptide_length: int = 0 |
| 73 | + max_peptide_length: int = 0 |
| 74 | + is_temporary: bool = True |
| 75 | + intermediate_hash: str = "" |
| 76 | + results: dict = None |
| 77 | + nr_id_features: int = 0 |
| 78 | + lower_bound_FDP: float = np.nan |
| 79 | + combined_FDP: float = np.nan |
| 80 | + category_combined: str = "" |
| 81 | + category_paired: str = "" |
| 82 | + paired_FDP: float = np.nan |
| 83 | + reported_fdr_parsed_from_input: float = np.nan |
| 84 | + fdp_curve: dict = None |
| 85 | + comments: str = "" |
| 86 | + proteobench_version: str = "" |
| 87 | + |
| 88 | + def generate_id(self) -> None: |
| 89 | + """ |
| 90 | + Generate a unique ID for the benchmark run by combining the software name and a timestamp. |
| 91 | +
|
| 92 | + This ID is used to uniquely identify each run of the benchmark. |
| 93 | + """ |
| 94 | + time_stamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| 95 | + self.id = "_".join([self.software_name, str(time_stamp)]) |
| 96 | + logging.info(f"Assigned the following ID to this run: {self.id}") |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def generate_datapoint( |
| 100 | + intermediate: pd.DataFrame, |
| 101 | + input_format: str, |
| 102 | + user_input: dict, |
| 103 | + ) -> pd.Series: |
| 104 | + """ |
| 105 | + Generate a Datapoint object containing metadata and results from the benchmark run. |
| 106 | +
|
| 107 | + Parameters |
| 108 | + ---------- |
| 109 | + intermediate : pd.DataFrame |
| 110 | + The intermediate DataFrame containing benchmark results. |
| 111 | + input_format : str |
| 112 | + The format of the input data (e.g., file format). |
| 113 | + user_input : dict |
| 114 | + User-defined input values for the benchmark. |
| 115 | + default_cutoff_min_prec : int, optional |
| 116 | + The default minimum precursor cutoff value. Defaults to 3. |
| 117 | + max_nr_observed : int, optional |
| 118 | + Maximum nr_observed value to calculate metrics for. If None, defaults to 6. |
| 119 | +
|
| 120 | + Returns |
| 121 | + ------- |
| 122 | + pd.Series |
| 123 | + A Pandas Series containing the Datapoint's attributes as key-value pairs. |
| 124 | + """ |
| 125 | + current_datetime = datetime.now() |
| 126 | + formatted_datetime = current_datetime.strftime("%Y%m%d_%H%M%S_%f") |
| 127 | + |
| 128 | + if "comments_for_plotting" not in user_input.keys(): |
| 129 | + user_input["comments_for_plotting"] = "" |
| 130 | + |
| 131 | + try: |
| 132 | + user_input = defaultdict( |
| 133 | + user_input.default_factory, # Preserve the default factory |
| 134 | + {key: ("" if value is None else value) for key, value in user_input.items()}, |
| 135 | + ) |
| 136 | + except AttributeError: |
| 137 | + user_input = {key: ("" if value is None else value) for key, value in user_input.items()} |
| 138 | + |
| 139 | + result_datapoint = EntrapmentDatapoint( |
| 140 | + id=input_format + "_" + user_input["software_version"] + "_" + formatted_datetime, |
| 141 | + software_name=input_format, |
| 142 | + software_version=user_input["software_version"], |
| 143 | + search_engine=user_input["search_engine"], |
| 144 | + search_engine_version=user_input["search_engine_version"], |
| 145 | + ident_fdr_psm=user_input["ident_fdr_psm"], |
| 146 | + ident_fdr_peptide=user_input["ident_fdr_peptide"], |
| 147 | + ident_fdr_protein=user_input["ident_fdr_protein"], |
| 148 | + enable_match_between_runs=user_input["enable_match_between_runs"], |
| 149 | + precursor_mass_tolerance=user_input["precursor_mass_tolerance"], |
| 150 | + fragment_mass_tolerance=user_input["fragment_mass_tolerance"], |
| 151 | + enzyme=user_input["enzyme"], |
| 152 | + allowed_miscleavages=user_input["allowed_miscleavages"], |
| 153 | + min_peptide_length=user_input["min_peptide_length"], |
| 154 | + max_peptide_length=user_input["max_peptide_length"], |
| 155 | + intermediate_hash=str(hashlib.sha1(intermediate.to_string().encode("utf-8")).hexdigest()), |
| 156 | + comments=user_input["comments_for_plotting"], |
| 157 | + proteobench_version=proteobench.__version__, |
| 158 | + ) |
| 159 | + |
| 160 | + result_datapoint.generate_id() |
| 161 | + metrics = EntrapmentDatapoint.get_metrics(intermediate) |
| 162 | + |
| 163 | + result_datapoint.reported_fdr_parsed_from_input = metrics["reported_fdr_parsed_from_input"] |
| 164 | + result_datapoint.nr_id_features = metrics["nr_id_features"] |
| 165 | + result_datapoint.lower_bound_FDP = metrics["lower_bound_FDP"] |
| 166 | + result_datapoint.combined_FDP = metrics["combined_FDP"] |
| 167 | + result_datapoint.paired_FDP = metrics["paired_FDP"] |
| 168 | + result_datapoint.category_combined = metrics["category_combined"] |
| 169 | + result_datapoint.category_paired = metrics["category_paired"] |
| 170 | + result_datapoint.fdp_curve = metrics["fdp_curve"] |
| 171 | + |
| 172 | + result_datapoint.results = metrics |
| 173 | + results_series = pd.Series(dataclasses.asdict(result_datapoint)) |
| 174 | + |
| 175 | + return results_series |
| 176 | + |
| 177 | + @staticmethod |
| 178 | + def get_metrics(intermediate: pd.DataFrame) -> Dict[str, Any]: |
| 179 | + metrics = EntrapmentScores.calculate_metrics(intermediate) |
| 180 | + return metrics |
0 commit comments