|
| 1 | +import warnings |
| 2 | +from typing import Any, Dict, List, Optional, Tuple |
| 3 | + |
| 4 | +import anndata as ad |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | + |
| 8 | +def read_spectronaut( |
| 9 | + file: str, |
| 10 | + intensity_columns: Optional[List[str] | str] = ["PG.Quantity"], |
| 11 | + index_column: Optional[str] = "PG.ProteinGroups", |
| 12 | + sample_column: Optional[str] = "R.FileName", |
| 13 | + sep="\t", |
| 14 | +): |
| 15 | + """ |
| 16 | + Load Spectronaut results into an AnnData object. |
| 17 | +
|
| 18 | + Parameters |
| 19 | + ---------- |
| 20 | + file |
| 21 | + Path to the Spectronaut results file. |
| 22 | + intensity_columns |
| 23 | + Name of the intensity column. |
| 24 | + index_column |
| 25 | + Name of the column to use as protein index. |
| 26 | + sample_column |
| 27 | + Name of the column to use as sample index. |
| 28 | + sep |
| 29 | + File separator. |
| 30 | +
|
| 31 | + Returns |
| 32 | + ------- |
| 33 | + :class:`anndata.AnnData` object with: |
| 34 | +
|
| 35 | + - ``X``: intensity matrix (samples x proteins) |
| 36 | + - ``var``: protein metadata (indexed by protein group IDs) |
| 37 | + - ``obs``: sample metadata (indexed by sample names) |
| 38 | + """ |
| 39 | + |
| 40 | + if isinstance(intensity_columns, str): |
| 41 | + intensity_columns = [intensity_columns] |
| 42 | + # Check that intensity columns are all at the same level as the index column |
| 43 | + index_level = index_column.split(".")[0] |
| 44 | + intensity_levels = [col.split(".")[0] for col in intensity_columns] |
| 45 | + if not all(level == index_level for level in intensity_levels): |
| 46 | + raise ValueError( |
| 47 | + f"Intensity columns {intensity_columns} are not all at the same level as the index column {index_column}" |
| 48 | + ) |
| 49 | + |
| 50 | + sample_levels = ("E", "R") |
| 51 | + possible_levels = ("PG", "PEP", "EG", "FG", "F") |
| 52 | + df = _read_csv_auto_decimal(file, sep=sep) |
| 53 | + |
| 54 | + sample_level = sample_column.split(".")[0] |
| 55 | + sample_idx = sample_levels.index(sample_level) |
| 56 | + var_levels = sample_levels[: sample_idx + 1] |
| 57 | + var_levels = tuple(f"{level}." for level in var_levels) |
| 58 | + var_cols = [ |
| 59 | + col |
| 60 | + for col in df.columns |
| 61 | + if col.startswith(var_levels) and df[col].notna().sum() > 0 |
| 62 | + ] |
| 63 | + |
| 64 | + dfp = df.pivot_table( |
| 65 | + index=index_column, |
| 66 | + columns=var_cols, |
| 67 | + values=intensity_columns, |
| 68 | + aggfunc="mean", |
| 69 | + observed=True, |
| 70 | + dropna=True, |
| 71 | + ).T |
| 72 | + dfpx = dfp.loc[intensity_columns[0]] |
| 73 | + |
| 74 | + # Report if intensities were not unique for pivoting and aggregated. This might not be what the user wants. |
| 75 | + for intensity_column in intensity_columns: |
| 76 | + if df[intensity_column].nunique() > dfpx.size: |
| 77 | + warnings.warn( |
| 78 | + f"{intensity_column} is not unique within {index_column} and {sample_column}, pivoting with mean aggregation. Make sure this is what you want!" |
| 79 | + ) |
| 80 | + |
| 81 | + # Construct obs |
| 82 | + obs = dfpx.index.to_frame().set_index(sample_column) |
| 83 | + |
| 84 | + # Construct var |
| 85 | + # Only columns that are coarser than the value column make sense to keep in var |
| 86 | + var_levels = tuple( |
| 87 | + f"{level}." |
| 88 | + for level in possible_levels[: possible_levels.index(index_level) + 1] |
| 89 | + ) |
| 90 | + varg = df.loc[:, df.columns.str.startswith(var_levels)].groupby( |
| 91 | + index_column, observed=True, dropna=False |
| 92 | + ) |
| 93 | + uniquecols = varg.nunique().eq(1).all(axis=0) |
| 94 | + uniquecols = uniquecols[uniquecols].index |
| 95 | + var = varg[uniquecols].first().reindex(dfpx.columns) |
| 96 | + |
| 97 | + # Get the layers |
| 98 | + layers = {} |
| 99 | + for intensity_column in intensity_columns[1:]: |
| 100 | + layers[intensity_column] = dfp.loc[intensity_column] |
| 101 | + |
| 102 | + # Create AnnData |
| 103 | + uns = { |
| 104 | + "RawInfo": { |
| 105 | + "Search_Engine": "Spectronaut", |
| 106 | + }, |
| 107 | + } |
| 108 | + adata = ad.AnnData(X=dfpx.to_numpy(), obs=obs, var=var, uns=uns, layers=layers) |
| 109 | + return adata |
| 110 | + |
| 111 | + |
| 112 | +def _read_csv_auto_decimal( |
| 113 | + path: str, |
| 114 | + *, |
| 115 | + sample_rows: int = 2000, |
| 116 | + trials: List[Dict[str, Optional[str]]] = [ |
| 117 | + { |
| 118 | + "decimal": ".", |
| 119 | + }, |
| 120 | + { |
| 121 | + "decimal": ",", |
| 122 | + }, |
| 123 | + ], |
| 124 | + **kwargs: Any, |
| 125 | +) -> pd.DataFrame: |
| 126 | + """ |
| 127 | + Read a CSV by trying multiple (decimal, thousands) configurations on a sample |
| 128 | + using a fixed `sep` (no separator inference). Picks the best config and |
| 129 | + re-reads the full file once. |
| 130 | +
|
| 131 | + Parameters |
| 132 | + ---------- |
| 133 | + path : str |
| 134 | + CSV file path. |
| 135 | + sample_rows : int |
| 136 | + Number of rows to sample for scoring. |
| 137 | + trials : list of dict |
| 138 | + List of {'decimal': <'.' or ','>, 'thousands': <'.' or ',' or None>} to try. |
| 139 | + **kwargs : Any |
| 140 | + Passed through to `pd.read_csv`. |
| 141 | +
|
| 142 | + Returns |
| 143 | + ------- |
| 144 | + DataFrame |
| 145 | + """ |
| 146 | + |
| 147 | + scores: List[Tuple[int, Dict[str, Optional[str]]]] = [] |
| 148 | + base_kwargs = dict(kwargs) |
| 149 | + |
| 150 | + for cfg in trials: |
| 151 | + try: |
| 152 | + samp = pd.read_csv(path, nrows=sample_rows, **base_kwargs, **cfg) |
| 153 | + num = samp.select_dtypes(include="number") |
| 154 | + # Score = (non-NaN numeric cells)*10 + (# numeric cols) |
| 155 | + frac_valid = 1.0 - num.isna().to_numpy().mean() |
| 156 | + score = frac_valid * 10000 + num.shape[1] # or any large scale |
| 157 | + |
| 158 | + scores.append((score, cfg)) |
| 159 | + except Exception: |
| 160 | + scores.append((-1, cfg)) |
| 161 | + |
| 162 | + best_score, best_cfg = max(scores, key=lambda x: x[0]) |
| 163 | + if best_score < 0: |
| 164 | + # All trials failed; fall back to single read with caller's sep and defaults |
| 165 | + return pd.read_csv(path, **base_kwargs) |
| 166 | + |
| 167 | + return pd.read_csv(path, **base_kwargs, **best_cfg) |
0 commit comments