protdata 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
io/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .maxquant_loader import read_maxquant
2
+ from .diann_loader import read_diann
3
+ from .fragpipe_loader import read_fragpipe
4
+ from .mztab_loader import read_mztab
5
+
6
+ __all__ = ["read_maxquant", "read_diann", "read_fragpipe", "read_mztab"]
io/diann_loader.py ADDED
@@ -0,0 +1,80 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import anndata as ad
4
+ from typing import Union
5
+ import os
6
+
7
+
8
+ def read_diann(
9
+ file: Union[str, pd.DataFrame],
10
+ index_column: str = "Protein.Group",
11
+ sep: str = "\t",
12
+ ) -> ad.AnnData:
13
+ """
14
+ Load DIA-NN protein group matrix (report.pg_matrix.tsv) into an AnnData object.
15
+
16
+ Args:
17
+ file: Path to DIA-NN report.pg_matrix.tsv or a pandas DataFrame.
18
+ intensity_suffix: Suffix for intensity columns (default: '_Intensity').
19
+ index_column: Column name for protein group IDs (default: 'Protein.Group').
20
+ sep: File separator (default: tab).
21
+
22
+ Returns:
23
+ AnnData object with:
24
+ - X: intensity matrix (proteins x samples)
25
+ - var: protein metadata
26
+ - obs: sample metadata
27
+ """
28
+ if isinstance(file, pd.DataFrame):
29
+ df = file.copy()
30
+ else:
31
+ df = pd.read_csv(file, sep=sep, low_memory=False)
32
+
33
+ # Columns that are not sample columns (from DIANNLoader.no_sample_column)
34
+ no_sample_column = [
35
+ "PG.Q.value",
36
+ "Global.PG.Q.value",
37
+ "PTM.Q.value",
38
+ "PTM.Site.Confidence",
39
+ "PG.Quantity",
40
+ "Protein.Group",
41
+ "Protein.Ids",
42
+ "Protein.Names",
43
+ "Genes",
44
+ "First.Protein.Description",
45
+ "contamination_library",
46
+ ]
47
+
48
+ df.columns = [
49
+ os.path.basename(col)
50
+ if isinstance(col, str) and col not in no_sample_column
51
+ else str(col)
52
+ for col in df.columns
53
+ ]
54
+
55
+ # Add contamination column if not present
56
+ if "contamination_library" not in df.columns:
57
+ df["contamination_library"] = False
58
+
59
+ # Find intensity columns (all columns not in no_sample_column)
60
+ intensity_cols = df.columns.difference(no_sample_column, sort=False).tolist()
61
+ if not intensity_cols:
62
+ raise ValueError(f"No intensity columns found.")
63
+
64
+ # Build X matrix (proteins x samples)
65
+ X = df[intensity_cols].to_numpy(dtype=np.float32).T
66
+
67
+ # Build var (proteins)
68
+ var = df[df.columns.intersection(no_sample_column, sort=False)].copy()
69
+ var.index = df[index_column]
70
+
71
+ # Build obs (samples)
72
+ obs = pd.DataFrame(index=intensity_cols)
73
+
74
+ # Build uns
75
+ uns = {"Search_Engine": "DIANN"}
76
+
77
+ # Create AnnData
78
+ adata = ad.AnnData(X=X, obs=obs, var=var)
79
+ adata.uns = uns
80
+ return adata
io/fragpipe_loader.py ADDED
@@ -0,0 +1,88 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import anndata as ad
4
+ from typing import Union
5
+ import warnings
6
+
7
+
8
+ def read_fragpipe(
9
+ file: Union[str, pd.DataFrame],
10
+ intensity_column_suffixes=[
11
+ " MaxLFQ Intensity",
12
+ " Spectral Count",
13
+ " Unique Spectral Count",
14
+ ],
15
+ index_column: str = "Protein ID",
16
+ sep: str = "\t",
17
+ ) -> ad.AnnData:
18
+ """
19
+ Load FragPipe-Philosopher protein group matrix into an AnnData object.
20
+
21
+ Args:
22
+ file: Path to combined_protein.tsv or a pandas DataFrame.
23
+ intensity_column_prefix: Prefix for intensity columns (default: '[sample] MaxLFQ Intensity ').
24
+ index_column: Column name for protein IDs (default: 'Protein').
25
+ gene_names_column: Column name for gene names (default: 'Gene Names').
26
+ confidence_column: Column name for protein probability (default: 'Protein Probability').
27
+ sep: File separator (default: tab).
28
+
29
+ Returns:
30
+ AnnData object with:
31
+ - X: intensity matrix (proteins x samples)
32
+ - var: protein metadata
33
+ - obs: sample metadata
34
+ """
35
+ if isinstance(intensity_column_suffixes, str):
36
+ intensity_column_suffixes = [intensity_column_suffixes]
37
+ main_intensity_suffix = intensity_column_suffixes[0]
38
+
39
+ if isinstance(file, pd.DataFrame):
40
+ df = file.copy()
41
+ else:
42
+ df = pd.read_csv(file, sep=sep, low_memory=False)
43
+
44
+ # Find intensity columns
45
+ intensity_cols = [col for col in df.columns if col.endswith(main_intensity_suffix)]
46
+ if not intensity_cols:
47
+ raise ValueError(f"No columns ending with '{main_intensity_suffix}' found.")
48
+
49
+ # Extract sample names from intensity columns
50
+ sample_names = [col[: -len(main_intensity_suffix)] for col in intensity_cols]
51
+
52
+ # Build X matrix (proteins x samples)
53
+ X = df[intensity_cols].to_numpy(dtype=np.float32).T
54
+ # If there are more intensity suffixes we store them as layers
55
+ layers = {}
56
+ if len(intensity_column_suffixes) > 1:
57
+ for suffix in intensity_column_suffixes[1:]:
58
+ suffix_cols = [
59
+ col
60
+ for col in df.columns
61
+ if col in [sample_name + suffix for sample_name in sample_names]
62
+ ]
63
+ if len(suffix_cols) == len(sample_names):
64
+ layers[suffix.strip()] = df[suffix_cols].to_numpy(dtype=np.float32).T
65
+ else:
66
+ warnings.warn(
67
+ f"Number of columns for suffix '{suffix}' does not match number of samples."
68
+ )
69
+
70
+ # Build var (proteins)
71
+ # A metadata column is anything that does not contain a sample name
72
+ sample_columns = np.array(
73
+ [any(sample_name in col for sample_name in sample_names) for col in df.columns]
74
+ )
75
+ var = df.loc[:, ~sample_columns].copy()
76
+ var.index = df[index_column]
77
+
78
+ # Build obs (samples)
79
+ obs = pd.DataFrame(index=sample_names)
80
+
81
+ # Build uns
82
+ uns = {"Search_Engine": "FragPipe_Philosopher"}
83
+
84
+ # Create AnnData
85
+ adata = ad.AnnData(X=X, obs=obs, var=var, layers=layers)
86
+ adata.uns = uns
87
+
88
+ return adata
io/maxquant_loader.py ADDED
@@ -0,0 +1,91 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import anndata as ad
4
+ from typing import Optional, Union, List
5
+ import warnings
6
+
7
+
8
+ def read_maxquant(
9
+ file: Union[str, pd.DataFrame],
10
+ intensity_column_prefixes: List[str] | str = ["LFQ intensity ", "Intensity "],
11
+ index_column: str = "Protein IDs",
12
+ filter_columns: list[str] = [
13
+ "Only identified by site",
14
+ "Reverse",
15
+ "Potential contaminant",
16
+ ],
17
+ # gene_names_column: str = "Gene names",
18
+ sep: str = "\t",
19
+ ) -> ad.AnnData:
20
+ """
21
+ Load MaxQuant proteinGroups.txt into an AnnData object.
22
+
23
+ Args:
24
+ file: Path to proteinGroups.txt or a pandas DataFrame.
25
+ intensity_column_prefix: Prefix for intensity columns (default: 'LFQ intensity ').
26
+ index_column: Column name for protein IDs (default: 'Protein IDs').
27
+ gene_names_column: Column name for gene names (default: 'Gene names').
28
+ sep: File separator (default: tab).
29
+
30
+ Returns:
31
+ AnnData object with:
32
+ - X: intensity matrix (proteins x samples)
33
+ - var: protein metadata
34
+ - obs: sample metadata
35
+ """
36
+ if isinstance(intensity_column_prefixes, str):
37
+ intensity_column_prefixes = [intensity_column_prefixes]
38
+
39
+ main_intensity_column = intensity_column_prefixes[0]
40
+ if isinstance(file, pd.DataFrame):
41
+ df = file
42
+ else:
43
+ df = pd.read_csv(file, sep=sep, low_memory=False)
44
+
45
+ # Find intensity columns
46
+ intensity_cols = [
47
+ col for col in df.columns if col.startswith(main_intensity_column)
48
+ ]
49
+ if not intensity_cols:
50
+ raise ValueError(f"No columns starting with '{main_intensity_column}' found.")
51
+
52
+ # Extract sample names from intensity columns
53
+ sample_names = [col[len(main_intensity_column) :] for col in intensity_cols]
54
+
55
+ # Build X matrix (proteins x samples)
56
+ X = df[intensity_cols].to_numpy(dtype=np.float32).T
57
+
58
+ # If there are more intensity suffixes we store them as layers
59
+ layers = {}
60
+ if len(intensity_column_prefixes) > 1:
61
+ for prefix in intensity_column_prefixes[1:]:
62
+ prefix_cols = [
63
+ col
64
+ for col in df.columns
65
+ if col in [prefix + sample_name for sample_name in sample_names]
66
+ ]
67
+ if len(prefix_cols) == len(sample_names):
68
+ layers[prefix.strip()] = df[prefix_cols].to_numpy(dtype=np.float32).T
69
+ else:
70
+ warnings.warn(
71
+ f"Number of columns for prefix '{prefix}' does not match number of samples."
72
+ )
73
+
74
+ # Build var (proteins)
75
+ # A metadata column is anything that does not contain a sample name
76
+ sample_columns = np.array(
77
+ [any(sample_name in col for sample_name in sample_names) for col in df.columns]
78
+ )
79
+ var = df.loc[:, ~sample_columns].copy()
80
+ var.index = df[index_column]
81
+
82
+ # Build obs (samples)
83
+ obs = pd.DataFrame(index=sample_names)
84
+
85
+ # Build uns
86
+ uns = {"Search_Engine": "MaxQuant"}
87
+
88
+ # Create AnnData
89
+ print(layers)
90
+ adata = ad.AnnData(X=X, obs=obs, var=var, layers=layers, uns=uns)
91
+ return adata
io/mztab_loader.py ADDED
@@ -0,0 +1,61 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import anndata as ad
4
+ from typing import Union
5
+ from pyteomics import mztab
6
+
7
+
8
+ def read_mztab(
9
+ file: Union[str, pd.DataFrame],
10
+ index_column: str = "accession",
11
+ ) -> ad.AnnData:
12
+ """
13
+ Load mzTab protein table into an AnnData object.
14
+
15
+ Args:
16
+ file: Path to mzTab file or a pandas DataFrame (protein table).
17
+ intensity_column_prefix: Prefix for intensity columns (default: 'protein_abundance_').
18
+ index_column: Column indicating the protein groups (default: 'accession').
19
+
20
+ Returns:
21
+ AnnData object with:
22
+ - X: intensity matrix (proteins x samples)
23
+ - var: protein metadata
24
+ - obs: sample metadata
25
+ """
26
+ if isinstance(file, pd.DataFrame):
27
+ df = file.copy()
28
+ else:
29
+ tables = mztab.MzTab(file)
30
+ df = tables.protein_table
31
+
32
+ # Find intensity columns
33
+ intensity_cols = [
34
+ col for col in df.columns if col.startswith("protein_abundance_study_variable[")
35
+ ]
36
+ if not intensity_cols:
37
+ raise ValueError(
38
+ f"No columns starting with 'protein_abundance_study_variable' found."
39
+ )
40
+
41
+ # Extract sample names from intensity columns
42
+ sample_names = [col.split("[")[1].split("]")[0] for col in intensity_cols]
43
+
44
+ # Build X matrix (proteins x samples)
45
+ X = df[intensity_cols].to_numpy(dtype=np.float32).T
46
+
47
+ # Build var (proteins)
48
+ var = df.drop(columns=intensity_cols).copy()
49
+ var.index = df[index_column].astype(str)
50
+
51
+ # Build obs (samples)
52
+ obs = pd.DataFrame.from_dict(tables.study_variables, orient="index")
53
+ obs.index.name = "sample"
54
+ obs.index = obs.index.astype(str)
55
+
56
+ # Build uns
57
+ uns = {"Search_Engine": df.search_engine.iloc[0]}
58
+
59
+ # Create AnnData
60
+ adata = ad.AnnData(X=X, obs=obs, var=var, uns=uns)
61
+ return adata
io/test_loaders.py ADDED
@@ -0,0 +1,25 @@
1
+ import os
2
+ import pytest
3
+ import anndata as ad
4
+ from .maxquant_loader import read_maxquant
5
+ from .fragpipe_loader import read_fragpipe
6
+ from .mztab_loader import read_mztab
7
+
8
+ data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data"))
9
+
10
+
11
+ @pytest.mark.parametrize(
12
+ "filename,loader",
13
+ [
14
+ ("proteinGroups.txt", read_maxquant),
15
+ ("combined_protein.tsv", read_fragpipe),
16
+ ("SILAC_SQ.mzTab", read_mztab),
17
+ ],
18
+ )
19
+ def test_loader(filename, loader):
20
+ path = os.path.join(data_dir, filename)
21
+ if not os.path.isfile(path):
22
+ pytest.skip(f"Test data file {filename} not found.")
23
+ adata = loader(path)
24
+ assert isinstance(adata, ad.AnnData)
25
+ assert adata.shape[0] > 0 and adata.shape[1] > 0
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: protdata
3
+ Version: 0.1.0
4
+ Summary: Proteomics data loaders for AnnData format.
5
+ Author: Max Frank
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: anndata
16
+ Requires-Dist: pandas
17
+ Requires-Dist: numpy
18
+ Requires-Dist: pyteomics
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # protdata
24
+
25
+ Proteomics data loaders for the [AnnData](https://anndata.readthedocs.io/) format.
26
+
27
+ This package provides loader functions to import proteomics data (e.g., MaxQuant) into the AnnData structure for downstream analysis and integration with single-cell and multi-omics workflows.
28
+
29
+ ## Features
30
+ - Load MaxQuant output into AnnData
31
+ - Designed for extensibility (other loaders coming soon)
32
+
33
+ ## Installation
34
+ ```bash
35
+ pip install .
36
+ ```
37
+
38
+ ## Usage Example
39
+ ```python
40
+ from protdata.io.maxquant_loader import load_maxquant_to_anndata
41
+ adata = load_maxquant_to_anndata("/path/to/proteinGroups.txt")
42
+ print(adata)
43
+ ```
@@ -0,0 +1,11 @@
1
+ io/__init__.py,sha256=UaNfWlZPWKhblNZo2D2vYiJs4ZSpi5pOLzIAnCuP5mE,234
2
+ io/diann_loader.py,sha256=CB1-Ec9vaDt7B2DuPBOxhNIcdUBs9paRbIzs_em-Z2g,2332
3
+ io/fragpipe_loader.py,sha256=dPkZzdWe2X2-aiUI2B1AUFqqVWe55HpjCcrT09EdxKY,3088
4
+ io/maxquant_loader.py,sha256=fUhd7Q9m7Pfqt4EMV9wc-V0P5kdVdqR24vsXAt-HX6c,3114
5
+ io/mztab_loader.py,sha256=GROk0Cv4pAErhTekRs1LAswXkJ4rRkG1E9huuqY6pYQ,1840
6
+ io/test_loaders.py,sha256=IoxPsZkHVfJQOwJWEHajItVoMXTOZoUfKGF9vbblSGw,744
7
+ protdata-0.1.0.dist-info/licenses/LICENSE,sha256=VKZRFKsnJP4_hBYDK3imU1zJCJ7oVzUEmBDOckhySFs,1116
8
+ protdata-0.1.0.dist-info/METADATA,sha256=SU6252IkZRLfKZ5FNV8A1qoTMVHcjHZ3fKcrwJfQnRo,1276
9
+ protdata-0.1.0.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
10
+ protdata-0.1.0.dist-info/top_level.txt,sha256=OfDt2rw7sJoV0Zxjiiuqx19W0dVQyP53izxE31dz0p8,3
11
+ protdata-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.4.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,11 @@
1
+ # Released under MIT License
2
+
3
+ Copyright (c) 2013 Mark Otto.
4
+
5
+ Copyright (c) 2017 Andrew Fong.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ io