|
| 1 | +from dataclasses import dataclass |
| 2 | +import os |
| 3 | +from typing import Dict, Literal, Optional, Tuple, Union |
| 4 | +import warnings |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class RosettaEnergyUnitAnalyser: |
| 11 | + """ |
| 12 | + A tool class for analyzing Rosetta energy calculation results. |
| 13 | +
|
| 14 | + Parameters: |
| 15 | + - score_file (str): The path to the score file or directory containing score files. |
| 16 | + - score_term (str, optional): The column name in the score file to use as the score. Defaults to "total_score". |
| 17 | + - job_id (Optional[str], optional): An identifier for the job. Defaults to None. |
| 18 | + """ |
| 19 | + |
| 20 | + score_file: str |
| 21 | + score_term: str = "total_score" |
| 22 | + |
| 23 | + job_id: Optional[str] = None |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def scorefile2df(score_file: str) -> pd.DataFrame: |
| 27 | + """ |
| 28 | + Converts a score file into a pandas DataFrame. |
| 29 | +
|
| 30 | + Parameters: |
| 31 | + - score_file (str): Path to the score file. |
| 32 | +
|
| 33 | + Returns: |
| 34 | + - pd.DataFrame: DataFrame containing the data from the score file. |
| 35 | + """ |
| 36 | + df = pd.read_fwf(score_file, skiprows=1) |
| 37 | + |
| 38 | + if "SCORE:" in df.columns: |
| 39 | + df.drop("SCORE:", axis=1, inplace=True) |
| 40 | + |
| 41 | + return df |
| 42 | + |
| 43 | + def __post_init__(self): |
| 44 | + """ |
| 45 | + Initializes the DataFrame based on the provided score file or directory. |
| 46 | + """ |
| 47 | + if os.path.isfile(self.score_file): |
| 48 | + self.df = self.scorefile2df(self.score_file) |
| 49 | + elif os.path.isdir(self.score_file): |
| 50 | + dfs = [ |
| 51 | + self.scorefile2df(os.path.join(self.score_file, f)) |
| 52 | + for f in os.listdir(self.score_file) |
| 53 | + if f.endswith(".sc") |
| 54 | + ] |
| 55 | + warnings.warn(UserWarning(f"Concatenate {len(dfs)} score files")) |
| 56 | + self.df = pd.concat(dfs, axis=0, ignore_index=True) |
| 57 | + else: |
| 58 | + raise FileNotFoundError(f"Score file {self.score_file} not found.") |
| 59 | + |
| 60 | + if not self.score_term in self.df.columns: |
| 61 | + raise ValueError(f'Score term "{self.score_term}" not found in score file.') |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def df2dict(dfs: pd.DataFrame, k: str = "total_score") -> Tuple[Dict[Literal["score", "decoy"], Union[str, float]]]: |
| 65 | + """ |
| 66 | + Converts a DataFrame into a tuple of dictionaries with scores and decoys. |
| 67 | +
|
| 68 | + Parameters: |
| 69 | + - dfs (pd.DataFrame): DataFrame containing the scores. |
| 70 | + - k (str, optional): Column name to use as the score. Defaults to "total_score". |
| 71 | +
|
| 72 | + Returns: |
| 73 | + - Tuple[Dict[Literal["score", "decoy"], Union[str, float]]]: Tuple of dictionaries containing scores and decoys. |
| 74 | + """ |
| 75 | + t = tuple( |
| 76 | + { |
| 77 | + "score": float(dfs[dfs.index == i][k].iloc[0]), |
| 78 | + "decoy": str(dfs[dfs.index == i]["description"].iloc[0]), |
| 79 | + } |
| 80 | + for i in dfs.index |
| 81 | + ) |
| 82 | + |
| 83 | + return t # type: ignore |
| 84 | + |
| 85 | + @property |
| 86 | + def best_decoy(self) -> Dict[Literal["score", "decoy"], Union[str, float]]: |
| 87 | + """ |
| 88 | + Returns the best decoy based on the score term. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + - Dict[Literal["score", "decoy"], Union[str, float]]: Dictionary containing the score and decoy of the best entry. |
| 92 | + """ |
| 93 | + if self.df.empty: |
| 94 | + return {} |
| 95 | + return self.top(1)[0] |
| 96 | + |
| 97 | + def top( |
| 98 | + self, rank: int = 1, score_term: Optional[str] = None |
| 99 | + ) -> Tuple[Dict[Literal["score", "decoy"], Union[str, float]]]: |
| 100 | + """ |
| 101 | + Returns the top `rank` decoys based on the specified score term. |
| 102 | +
|
| 103 | + Parameters: |
| 104 | + - rank (int, optional): The number of top entries to return. Defaults to 1. |
| 105 | + - score_term (Optional[str], optional): The column name to use as the score. Defaults to the class attribute `score_term`. |
| 106 | +
|
| 107 | + Returns: |
| 108 | + - Tuple[Dict[Literal["score", "decoy"], Union[str, float]]]: Tuple of dictionaries containing scores and decoys of the top entries. |
| 109 | + """ |
| 110 | + if rank <= 0: |
| 111 | + raise ValueError(f"Rank must be greater than 0") |
| 112 | + |
| 113 | + # Override score_term if provided |
| 114 | + score_term = score_term if score_term is not None and score_term in self.df.columns else self.score_term |
| 115 | + |
| 116 | + df = self.df.sort_values( |
| 117 | + by=score_term if score_term is not None and score_term in self.df.columns else self.score_term |
| 118 | + ).head(rank) |
| 119 | + |
| 120 | + return self.df2dict(dfs=df, k=score_term) |
0 commit comments