pyPrepGDC 0.0.2__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.
- pyprepgdc-0.0.2.dist-info/METADATA +210 -0
- pyprepgdc-0.0.2.dist-info/RECORD +8 -0
- pyprepgdc-0.0.2.dist-info/WHEEL +5 -0
- pyprepgdc-0.0.2.dist-info/licenses/LICENSE.txt +201 -0
- pyprepgdc-0.0.2.dist-info/top_level.txt +1 -0
- src/__init__.py +34 -0
- src/aggreg.py +175 -0
- src/gparse.py +88 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyPrepGDC
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Preprocessing for GDC multiomics
|
|
5
|
+
Author-email: Hasan Alsharoh <hasanalsharoh@gmail.com>
|
|
6
|
+
License: Apache License (2.0)
|
|
7
|
+
Project-URL: Homepage, https://github.com/hasanalsharoh/pyPrepGDC
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/hasanalsharoh/pyPrepGDC/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE.txt
|
|
17
|
+
Requires-Dist: pandas==2.3.3
|
|
18
|
+
Requires-Dist: numpy==2.2.6
|
|
19
|
+
Requires-Dist: dask==2024.9.1
|
|
20
|
+
Requires-Dist: pyarrow
|
|
21
|
+
Requires-Dist: anndata
|
|
22
|
+
Requires-Dist: scipy
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pyPrepGDC
|
|
26
|
+
|
|
27
|
+
Python package for preprocessing multi-omics data downloaded from the [GDC (Genomic Data Commons)](https://gdc.cancer.gov/) portal via the GDC-Client into analysis-ready structures.
|
|
28
|
+
|
|
29
|
+
## Overview
|
|
30
|
+
|
|
31
|
+
GDC-Client downloads each file into its own folder (named by File ID). pyPrepGDC reads those folders, attaches clinical metadata, merges samples across omic types, and produces either a dict-of-dicts or an [AnnData](https://anndata.readthedocs.io/) object ready for downstream tools such as [scanpy](https://scanpy.readthedocs.io/) and [pydeseq2](https://pydeseq2.readthedocs.io/).
|
|
32
|
+
|
|
33
|
+
Supported omic types: **RNA-seq**, **miRNA-seq**, **DNA methylation (EPIC/450K)**, **gene-level CNV**.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install pyPrepGDC
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**Requirements:** Python ≥ 3.11, pandas, numpy, dask, pyarrow, anndata, scipy.
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
### 1 — Download data with GDC-Client
|
|
46
|
+
|
|
47
|
+
Your download directory should look like:
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
data/
|
|
51
|
+
├── <File ID 1>/
|
|
52
|
+
│ └── <data file>.tsv
|
|
53
|
+
├── <File ID 2>/
|
|
54
|
+
│ └── <data file>.tsv
|
|
55
|
+
│ annotations.txt ← flagged/duplicate samples are skipped automatically
|
|
56
|
+
└── ...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
You also need the **Sample Sheet** and **Clinical** files exported from the GDC portal.
|
|
60
|
+
|
|
61
|
+
### 2 — Parse a single omic type
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import pandas as pd
|
|
65
|
+
from pyPrepGDC import parse_gdc
|
|
66
|
+
|
|
67
|
+
# Load the sample sheet (contains File ID → Case ID / Sample ID mapping)
|
|
68
|
+
sample_sheet = pd.read_csv('sample_sheet.tsv', sep='\t')
|
|
69
|
+
|
|
70
|
+
# Parse RNA-seq files
|
|
71
|
+
rna_tumor = parse_gdc(
|
|
72
|
+
target_folders = sample_sheet[sample_sheet['Sample Type'] == 'Primary Tumor']['File ID'].tolist(),
|
|
73
|
+
base_dir = 'data/',
|
|
74
|
+
classific = 'Tumor',
|
|
75
|
+
grouped_list = sample_sheet,
|
|
76
|
+
file_ext = '.tsv',
|
|
77
|
+
data_cat = 'rna',
|
|
78
|
+
)
|
|
79
|
+
# rna_tumor = {'Tumor1': {'cd': <clinical df>, 'rna': <dask df>}, 'Tumor2': ...}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`data_cat` options:
|
|
83
|
+
|
|
84
|
+
| Value | File type |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `'rna'` | RNA-seq (STAR counts) |
|
|
87
|
+
| `'mirna'` | miRNA-seq |
|
|
88
|
+
| `'meth'` | DNA methylation beta values |
|
|
89
|
+
| `'gene'` | Gene-level CNV (WGS) |
|
|
90
|
+
|
|
91
|
+
### 3 — Merge two omic types
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from pyPrepGDC import merge_2dicts
|
|
95
|
+
|
|
96
|
+
# alignment_df must have a column matching join_key (default 'Case ID')
|
|
97
|
+
# and one column per File ID type
|
|
98
|
+
alignment = sample_sheet[['Case ID', 'File ID', 'MiRFile ID']].drop_duplicates()
|
|
99
|
+
|
|
100
|
+
merged = merge_2dicts(
|
|
101
|
+
dict1 = rna_tumor,
|
|
102
|
+
dict2 = mirna_tumor,
|
|
103
|
+
omic1_cat = 'rna',
|
|
104
|
+
omic2_cat = 'mirna',
|
|
105
|
+
alignment_df = alignment,
|
|
106
|
+
classific = 'Tumor',
|
|
107
|
+
join_key = 'Case ID', # use 'Sample ID' to preserve tumor/normal pairs
|
|
108
|
+
)
|
|
109
|
+
# merged = {'Tumor1': {'cd': ..., 'rna': ..., 'mirna': ...}, ...}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 4 — Merge three omic types
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from pyPrepGDC import merge_3dicts
|
|
116
|
+
|
|
117
|
+
alignment = sample_sheet[['Case ID', 'File ID', 'GFile ID', 'MFile ID']].drop_duplicates()
|
|
118
|
+
|
|
119
|
+
merged = merge_3dicts(
|
|
120
|
+
rna_dict = rna_tumor,
|
|
121
|
+
cnv_dict = cnv_tumor,
|
|
122
|
+
meth_dict = meth_tumor,
|
|
123
|
+
alignment_df = alignment,
|
|
124
|
+
classific = 'Tumor',
|
|
125
|
+
)
|
|
126
|
+
# merged = {'Tumor1': {'cd': ..., 'rna': ..., 'gene': ..., 'meth': ...}, ...}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### 5 — Build a count/beta matrix
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from pyPrepGDC import create_count_table
|
|
133
|
+
|
|
134
|
+
count_matrix = create_count_table(
|
|
135
|
+
data_dict1 = tumor_merged,
|
|
136
|
+
data_dict2 = normal_merged,
|
|
137
|
+
data_cat = 'rna',
|
|
138
|
+
cols = 'unstranded',
|
|
139
|
+
label = 'gene_id',
|
|
140
|
+
)
|
|
141
|
+
# Returns a DataFrame: rows = genes, columns = [gene_id, Tumor1, Tumor2, ..., Normal1, ...]
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### 6 — Build a clinical DataFrame
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
from pyPrepGDC import build_clinical_df
|
|
148
|
+
|
|
149
|
+
clinical = build_clinical_df(merged)
|
|
150
|
+
# Returns a long-form DataFrame with all samples stacked and a 'key' column
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 7 — Export to AnnData (.h5ad)
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from pyPrepGDC import build_anndata
|
|
157
|
+
import anndata as ad
|
|
158
|
+
|
|
159
|
+
adata = build_anndata(
|
|
160
|
+
merged_dict = merged,
|
|
161
|
+
data_cat = 'rna',
|
|
162
|
+
feature_col = 'gene_id',
|
|
163
|
+
count_col = 'unstranded',
|
|
164
|
+
extra_layers = {'tpm': 'tpm_unstranded'}, # optional additional matrices
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
# Save — HDF5 format, compressed, supports backed/lazy loading
|
|
168
|
+
adata.write_h5ad('merged_rna.h5ad', compression='gzip')
|
|
169
|
+
|
|
170
|
+
# Load full
|
|
171
|
+
adata = ad.read_h5ad('merged_rna.h5ad')
|
|
172
|
+
|
|
173
|
+
# Load in backed (lazy) mode — only reads requested slices into RAM
|
|
174
|
+
adata = ad.read_h5ad('merged_rna.h5ad', backed='r')
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**AnnData layout:**
|
|
178
|
+
|
|
179
|
+
| Slot | Contents |
|
|
180
|
+
|---|---|
|
|
181
|
+
| `adata.X` | Count / beta matrix (samples × features), `float32` |
|
|
182
|
+
| `adata.obs` | Clinical metadata (one row per sample) |
|
|
183
|
+
| `adata.var` | Feature metadata (gene / CpG site index) |
|
|
184
|
+
| `adata.layers['tpm']` | TPM values (if `extra_layers` supplied) |
|
|
185
|
+
|
|
186
|
+
### Downstream use with pydeseq2
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
import pandas as pd
|
|
190
|
+
from pydeseq2.dds import DeseqDataSet
|
|
191
|
+
|
|
192
|
+
counts_df = pd.DataFrame(adata.X, index=adata.obs_names, columns=adata.var_names)
|
|
193
|
+
meta_df = adata.obs[['condition']]
|
|
194
|
+
dds = DeseqDataSet(counts=counts_df, metadata=meta_df, design_factors='condition')
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## API reference
|
|
198
|
+
|
|
199
|
+
| Function | Description |
|
|
200
|
+
|---|---|
|
|
201
|
+
| `parse_gdc(target_folders, base_dir, classific, grouped_list, file_ext, data_cat)` | Parse GDC download folders into a dict-of-dicts |
|
|
202
|
+
| `merge_2dicts(dict1, dict2, omic1_cat, omic2_cat, alignment_df, classific, join_key)` | Merge any two omic dicts using a pre-built alignment DataFrame |
|
|
203
|
+
| `merge_3dicts(rna_dict, cnv_dict, meth_dict, alignment_df, classific)` | Merge RNA, CNV, and methylation dicts |
|
|
204
|
+
| `create_count_table(data_dict1, data_dict2, data_cat, cols, label)` | Build a count/value matrix from two merged dicts |
|
|
205
|
+
| `build_clinical_df(merged_dict)` | Concatenate clinical DataFrames into a single long-form table |
|
|
206
|
+
| `build_anndata(merged_dict, data_cat, feature_col, count_col, extra_layers)` | Convert a merged dict to an AnnData object |
|
|
207
|
+
|
|
208
|
+
## License
|
|
209
|
+
|
|
210
|
+
Apache License 2.0 — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
pyprepgdc-0.0.2.dist-info/licenses/LICENSE.txt,sha256=2lvVcfoBJ3gNPT-CU21QkSkbB2HSJcOoD7ulPsamx3U,11343
|
|
2
|
+
src/__init__.py,sha256=I-yW7VxCfcxz7S1a8B840m9YDeLy9juFWdOf9rS_yZs,1272
|
|
3
|
+
src/aggreg.py,sha256=y6yYbzMOMJk1NM-YfpiKXJsp_wEvhufqZyEexYPEdJs,7107
|
|
4
|
+
src/gparse.py,sha256=KD8iJ7cJuMHB8q2g2orAJFg_gYd-tkJh-GU8n1XdxI0,5192
|
|
5
|
+
pyprepgdc-0.0.2.dist-info/METADATA,sha256=-LGdy-R6RDgwTTb9wdDtR6oNUYRh0f_FF6uBGWgKVzA,6661
|
|
6
|
+
pyprepgdc-0.0.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
pyprepgdc-0.0.2.dist-info/top_level.txt,sha256=74rtVfumQlgAPzR5_2CgYN24MB0XARCg0t-gzk6gTrM,4
|
|
8
|
+
pyprepgdc-0.0.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Hasan Alsharoh
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
src
|
src/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pyPrepGDC: Python package for preprocessing --omics data obtained from GDC (Genomic Data Commons) Portal for downstream analysis.
|
|
3
|
+
This package is designed for preprocessing data downloaded through the GDC-Client python tool.
|
|
4
|
+
The main processing steps are:
|
|
5
|
+
1) After creating a metadata file, and downloading the data through the GDC-Client,
|
|
6
|
+
the data is created and organized in a folder structure as follows:
|
|
7
|
+
- data/
|
|
8
|
+
- sample1/
|
|
9
|
+
- file1
|
|
10
|
+
- sample2/
|
|
11
|
+
- file2
|
|
12
|
+
*- annotation file // in case errors are found in the data, they are often accompanied by annotation files that provide details about the errors. These files can be used to identify and address issues in the data.
|
|
13
|
+
2) Download from the GDC Portal, similarly to when obtaining the metadata file, Clinical.csv and Sample Sheet.csv must also be obtained.
|
|
14
|
+
3) The data is then preprocessed using the pyPrepGDC package.
|
|
15
|
+
"""
|
|
16
|
+
from .gparse import _omic_generator, parse_gdc
|
|
17
|
+
from .aggreg import (
|
|
18
|
+
create_count_table,
|
|
19
|
+
merge_2dicts,
|
|
20
|
+
merge_3dicts,
|
|
21
|
+
build_clinical_df,
|
|
22
|
+
build_anndata,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
__version__ = "0.0.2"
|
|
27
|
+
__all__ = [
|
|
28
|
+
"parse_gdc",
|
|
29
|
+
"create_count_table",
|
|
30
|
+
"merge_2dicts",
|
|
31
|
+
"merge_3dicts",
|
|
32
|
+
"build_clinical_df",
|
|
33
|
+
"build_anndata",
|
|
34
|
+
]
|
src/aggreg.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import anndata as ad
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def merge_3dicts(rna_dict, cnv_dict, meth_dict, alignment_df, classific):
|
|
7
|
+
"""
|
|
8
|
+
Merge three omics dicts (RNA, CNV, methylation) using a pre-built alignment DataFrame.
|
|
9
|
+
|
|
10
|
+
O(1) lookup via reverse indices built once before the loop. The caller supplies
|
|
11
|
+
alignment_df (e.g. tma/twa from the calling notebook) as the single source of truth
|
|
12
|
+
for which samples belong together — avoids re-deriving alignment by scanning.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
rna_dict: parsed RNA-seq dict from parse_gdc
|
|
16
|
+
cnv_dict: parsed CNV dict from parse_gdc
|
|
17
|
+
meth_dict: parsed methylation dict from parse_gdc
|
|
18
|
+
alignment_df: DataFrame with at least a 'Case ID' column joining all three omics
|
|
19
|
+
classific: string prefix for output keys (e.g. 'Tumor')
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
dict keyed classific+i with 'cd', 'rna', 'gene', 'meth' entries
|
|
23
|
+
"""
|
|
24
|
+
rna_idx = {next(iter(v['cd']['Case ID'])): k for k, v in rna_dict.items()}
|
|
25
|
+
cnv_idx = {next(iter(v['cd']['Case ID'])): k for k, v in cnv_dict.items()}
|
|
26
|
+
meth_idx = {next(iter(v['cd']['Case ID'])): k for k, v in meth_dict.items()}
|
|
27
|
+
|
|
28
|
+
merged = {}
|
|
29
|
+
for i, (_, row) in enumerate(alignment_df.iterrows(), 1):
|
|
30
|
+
case_id = row['Case ID']
|
|
31
|
+
rna_key = rna_idx.get(case_id)
|
|
32
|
+
cnv_key = cnv_idx.get(case_id)
|
|
33
|
+
meth_key = meth_idx.get(case_id)
|
|
34
|
+
if rna_key and cnv_key and meth_key:
|
|
35
|
+
merged[f'{classific}{i}'] = {
|
|
36
|
+
'cd': alignment_df[alignment_df['Case ID'] == case_id].reset_index(drop=True),
|
|
37
|
+
'rna': rna_dict[rna_key]['rna'],
|
|
38
|
+
'gene': cnv_dict[cnv_key]['gene'],
|
|
39
|
+
'meth': meth_dict[meth_key]['meth'],
|
|
40
|
+
}
|
|
41
|
+
return merged
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def merge_2dicts(dict1, dict2, omic1_cat, omic2_cat, alignment_df, classific, join_key='Case ID'):
|
|
45
|
+
"""
|
|
46
|
+
Merge any two omics dicts using a pre-built alignment DataFrame.
|
|
47
|
+
|
|
48
|
+
O(1) lookup via reverse indices. Both omic category names are caller-supplied so the
|
|
49
|
+
function is not tied to any specific omic type.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
dict1: first parsed omic dict from parse_gdc
|
|
53
|
+
dict2: second parsed omic dict from parse_gdc
|
|
54
|
+
omic1_cat: key name for the first omic in the output dict (e.g. 'rna', 'gene')
|
|
55
|
+
omic2_cat: key name for the second omic in the output dict (e.g. 'mirna', 'meth')
|
|
56
|
+
alignment_df: DataFrame with at least a join_key column joining both omics
|
|
57
|
+
classific: string prefix for output keys (e.g. 'Tumor')
|
|
58
|
+
join_key: column to join on (default 'Case ID'; use 'Sample ID' to preserve
|
|
59
|
+
tumor/normal pairs within the same case)
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
dict keyed classific+i with 'cd', omic1_cat, and omic2_cat entries
|
|
63
|
+
"""
|
|
64
|
+
idx1 = {next(iter(v['cd'][join_key])): k for k, v in dict1.items()}
|
|
65
|
+
idx2 = {next(iter(v['cd'][join_key])): k for k, v in dict2.items()}
|
|
66
|
+
|
|
67
|
+
merged = {}
|
|
68
|
+
for i, (_, row) in enumerate(alignment_df.iterrows(), 1):
|
|
69
|
+
key_val = row[join_key]
|
|
70
|
+
key1 = idx1.get(key_val)
|
|
71
|
+
key2 = idx2.get(key_val)
|
|
72
|
+
if key1 and key2:
|
|
73
|
+
merged[f'{classific}{i}'] = {
|
|
74
|
+
'cd': alignment_df[alignment_df[join_key] == key_val].reset_index(drop=True),
|
|
75
|
+
omic1_cat: dict1[key1][omic1_cat],
|
|
76
|
+
omic2_cat: dict2[key2][omic2_cat],
|
|
77
|
+
}
|
|
78
|
+
return merged
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def create_count_table(data_dict1, data_dict2, data_cat, cols, label):
|
|
82
|
+
"""
|
|
83
|
+
Build a count/value matrix from two merged dicts (e.g. cases and controls).
|
|
84
|
+
|
|
85
|
+
Iterates by dict key directly — no counter reconstruction, single concat at the end.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
data_dict1: first merged dict (e.g. tumor samples)
|
|
89
|
+
data_dict2: second merged dict (e.g. normal samples)
|
|
90
|
+
data_cat: omic key inside each sample ('rna', 'gene', 'meth', 'mirna')
|
|
91
|
+
cols: column holding count/value to extract (e.g. 'unstranded', 'betav')
|
|
92
|
+
label: column to use as the feature label (e.g. 'gene_id', 'site', 'miRNA_ID')
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
DataFrame with label column followed by one column per sample
|
|
96
|
+
"""
|
|
97
|
+
cols1 = {k: v[data_cat][cols].rename(k) for k, v in data_dict1.items()}
|
|
98
|
+
cols2 = {k: v[data_cat][cols].rename(k) for k, v in data_dict2.items()}
|
|
99
|
+
label_s = next(iter(data_dict1.values()))[data_cat][label]
|
|
100
|
+
return pd.concat([label_s, *cols1.values(), *cols2.values()], axis=1)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_clinical_df(merged_dict):
|
|
104
|
+
"""
|
|
105
|
+
Concatenate clinical DataFrames from a merged dict, adding a 'key' column.
|
|
106
|
+
|
|
107
|
+
Non-mutating — original DataFrames in merged_dict are not modified.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
merged_dict: output of merge_2dicts or merge_3dicts
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
Single long-form DataFrame with all samples stacked; 'key' column holds the dict key
|
|
114
|
+
"""
|
|
115
|
+
return pd.concat(
|
|
116
|
+
[v['cd'].assign(key=k) for k, v in merged_dict.items()],
|
|
117
|
+
axis=0,
|
|
118
|
+
ignore_index=True,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def build_anndata(merged_dict, data_cat, feature_col, count_col, extra_layers=None):
|
|
123
|
+
"""
|
|
124
|
+
Convert a merged dict-of-dicts into an AnnData object (samples × features).
|
|
125
|
+
|
|
126
|
+
Materializes any dask DataFrames lazily, aligns feature order across samples, and
|
|
127
|
+
stacks into a single X matrix without concat-in-loop. Saves with .write_h5ad() for
|
|
128
|
+
backed/lazy access and interoperability with scanpy / pydeseq2.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
merged_dict: output of merge_2dicts or merge_3dicts
|
|
132
|
+
data_cat: omic key inside each sample dict ('rna', 'meth', 'gene', 'mirna')
|
|
133
|
+
feature_col: column to use as var index ('gene_id', 'miRNA_ID', 'site')
|
|
134
|
+
count_col: column to use as X values ('unstranded', 'read_count', 'betav')
|
|
135
|
+
extra_layers: dict of {layer_name: column_name} for additional matrices,
|
|
136
|
+
e.g. {'tpm': 'tpm_unstranded'}
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
AnnData object: X shape (n_samples × n_features), obs=clinical, var=feature metadata
|
|
140
|
+
"""
|
|
141
|
+
keys = list(merged_dict.keys())
|
|
142
|
+
|
|
143
|
+
first_df = merged_dict[keys[0]][data_cat]
|
|
144
|
+
if hasattr(first_df, 'compute'):
|
|
145
|
+
first_df = first_df.compute()
|
|
146
|
+
features = first_df[feature_col].values
|
|
147
|
+
|
|
148
|
+
X_rows = []
|
|
149
|
+
layer_rows = {ln: [] for ln in (extra_layers or {})}
|
|
150
|
+
obs_rows = []
|
|
151
|
+
|
|
152
|
+
for key in keys:
|
|
153
|
+
df = merged_dict[key][data_cat]
|
|
154
|
+
if hasattr(df, 'compute'):
|
|
155
|
+
df = df.compute()
|
|
156
|
+
df = df.set_index(feature_col).reindex(features)
|
|
157
|
+
X_rows.append(df[count_col].values.astype(np.float32))
|
|
158
|
+
for layer_name, col in (extra_layers or {}).items():
|
|
159
|
+
layer_rows[layer_name].append(df[col].values.astype(np.float32))
|
|
160
|
+
|
|
161
|
+
cd = merged_dict[key]['cd']
|
|
162
|
+
if hasattr(cd, 'compute'):
|
|
163
|
+
cd = cd.compute()
|
|
164
|
+
obs_rows.append(cd.iloc[0])
|
|
165
|
+
|
|
166
|
+
X = np.vstack(X_rows)
|
|
167
|
+
obs = pd.DataFrame(obs_rows, index=keys)
|
|
168
|
+
var = pd.DataFrame(index=features)
|
|
169
|
+
var.index.name = feature_col
|
|
170
|
+
|
|
171
|
+
adata = ad.AnnData(X=X, obs=obs, var=var)
|
|
172
|
+
for layer_name, rows in layer_rows.items():
|
|
173
|
+
adata.layers[layer_name] = np.vstack(rows)
|
|
174
|
+
|
|
175
|
+
return adata
|
src/gparse.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Parsing function for TCGA data
|
|
2
|
+
import os
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import dask
|
|
5
|
+
import dask.dataframe as dd
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
def _omic_generator(target_folders, base_dir, classific, grouped_list, file_ext, data_cat):
|
|
9
|
+
"""
|
|
10
|
+
Target folders is a list of GDC folders containing files of either RNAseq, DNA methylation, or CNV data.
|
|
11
|
+
base_dir is the directory where the target folders are located.
|
|
12
|
+
classific is the string class of the samples in the target folders. In this example we have TMAs (tumors with metastatic
|
|
13
|
+
potential) and TWAs (tumors without metastatic potential).
|
|
14
|
+
grouped_list is a DataFrame containing clinical data for the samples in the target folders. This is to implement clinical data.
|
|
15
|
+
file_ext is the string file extension of the files in the target folders.
|
|
16
|
+
data_cat is the string category of the data in the target folders. It can be one of 'gene', 'meth', or 'rna'.
|
|
17
|
+
"""
|
|
18
|
+
counter = 1 # Counter for naming the DataFrames
|
|
19
|
+
processed_files = set() # Set to keep track of processed files, thiis avoids processing the same file multiple times in case of duplicates
|
|
20
|
+
|
|
21
|
+
for folder_name in target_folders:
|
|
22
|
+
folder_path = os.path.join(base_dir, folder_name)
|
|
23
|
+
if "annotations.txt" in os.listdir(folder_path): # Automatically skip folders with annotations.txt which are usually duplicates
|
|
24
|
+
print(f"Skipping folder: {folder_name} (contains 'annotations.txt')")
|
|
25
|
+
continue # Skip this folder
|
|
26
|
+
|
|
27
|
+
if os.path.isdir(folder_path):
|
|
28
|
+
for file_name in os.listdir(folder_path):
|
|
29
|
+
file_path = os.path.join(folder_path, file_name)
|
|
30
|
+
|
|
31
|
+
# Check if the file has already been processed
|
|
32
|
+
if file_path in processed_files:
|
|
33
|
+
continue # Skip this file
|
|
34
|
+
|
|
35
|
+
if os.path.isfile(file_path) and file_name.endswith(file_ext):
|
|
36
|
+
|
|
37
|
+
# Create a DataFrame from the file
|
|
38
|
+
# For gene-level copy number variation (CNV) data
|
|
39
|
+
if data_cat == "gene": # Genomic data for WGS files
|
|
40
|
+
df = dd.read_csv(file_path, sep='\t')
|
|
41
|
+
df = df.dropna(subset=['gene_id'])
|
|
42
|
+
cdsubs = grouped_list[grouped_list['GFile ID'] == folder_name] # Get the corresponding clinical data
|
|
43
|
+
|
|
44
|
+
# DNA methylation beta-values
|
|
45
|
+
elif data_cat == "meth": # DNA methylation beta values data
|
|
46
|
+
df = dd.read_csv(file_path, sep='\t', header=None)
|
|
47
|
+
df.columns = ['site', 'betav']
|
|
48
|
+
cdsubs = grouped_list[grouped_list['MFile ID'] == folder_name] # Get the corresponding clinical data
|
|
49
|
+
|
|
50
|
+
# RNAseq
|
|
51
|
+
elif data_cat == "rna": # RNA-seq data
|
|
52
|
+
df = dd.read_csv(file_path, sep='\t', comment='#',
|
|
53
|
+
na_values=['N_unmapped', 'N_multimapping',
|
|
54
|
+
'N_noFeature', 'N_ambiguous'],
|
|
55
|
+
usecols=['gene_id','gene_name','gene_type',
|
|
56
|
+
'unstranded','tpm_unstranded']) # read only columns useful for analysis, for managing memory
|
|
57
|
+
df = df.dropna(subset=['gene_id'])
|
|
58
|
+
cdsubs = grouped_list[grouped_list['File ID'] == folder_name] # Get the corresponding clinical data
|
|
59
|
+
|
|
60
|
+
# miRNA-seq
|
|
61
|
+
elif data_cat == "mirna": # miRNA-seq data
|
|
62
|
+
df = pd.read_csv(file_path, sep='\t',
|
|
63
|
+
usecols=['miRNA_ID','read_count']) # read only columns useful for analysis, for managing memory
|
|
64
|
+
df = df.dropna(subset=['miRNA_ID'])
|
|
65
|
+
cdsubs = grouped_list[grouped_list['File ID'] == folder_name] # Get the corresponding clinical data
|
|
66
|
+
|
|
67
|
+
# Give the DataFrame a name based on the file name
|
|
68
|
+
dataframe_name = f"{classific}{counter}" # e.g. 'Tumor1', dictionary key corresponding to the parsed sample data
|
|
69
|
+
counter += 1 # Add 1 to the counter for the next DataFrame to have dictionary keys in order
|
|
70
|
+
|
|
71
|
+
# Add to parsed_data dictionary
|
|
72
|
+
yield dataframe_name, {'cd': cdsubs, data_cat: df}
|
|
73
|
+
|
|
74
|
+
# Mark the file as processed
|
|
75
|
+
processed_files.add(file_path)
|
|
76
|
+
|
|
77
|
+
def parse_gdc(target_folders, base_dir, classific, grouped_list, file_ext, data_cat):
|
|
78
|
+
"""
|
|
79
|
+
This function takes parameters from _omic_generator to parse the data
|
|
80
|
+
Similarly, the arguments are duplicated to maintain the same functionality as _omic_generator
|
|
81
|
+
|
|
82
|
+
output: dictionary [classific1: {'cd': clinical data, data_cat: omic data}, classific2: {'cd': clinical data, data_cat: omic data}, ...]
|
|
83
|
+
"""
|
|
84
|
+
dict = {}
|
|
85
|
+
generator = _omic_generator(target_folders, base_dir, classific, grouped_list, file_ext, data_cat)
|
|
86
|
+
for name, data in generator:
|
|
87
|
+
dict[f'{name}'] = data
|
|
88
|
+
return dict
|